1、Python库参考手册(Python LibraryReference)Release 2.3.3Guido van RossumFred L.Drake,Jr.,editor翻译团队:见文末名单译文最后修改:2004年3月22日PythonLabsEmail:docspython.orgCopyright c?2001,2002,2003 Python Software Foundation.All rights reserved.Copyright c?2000 BeO.All rights reserved.Copyright c?1995-2000 Corporation for Na
2、tional Research Initiatives.All rights reserved.Copyright c?1991-1995 Stichting Mathematisch Centrum.All rights reserved.See the end of this document for complete license and permissions information.详细版权及使用许可的资料见本文的最后部份.Python is an extensible,interpreted,object-oriented programming language.It supp
3、orts a wide range of applica-tions,from simple text processing scripts to interactive Web browsers.Python 是一种可扩展的,即译式,面向对象规格的编程语言.它能应用在极广泛的地方,从简单的文字处理工作到交互式的网页浏览器.While the Python Reference Manual describes the exact syntax and semantics of the language,it does not describethe standard library that
4、is distributed with the language,and which greatly enhances its immediate usability.This library contains built-in modules(written in C)that provide access to system functionality such as file I/Othat would otherwise be inaccessible to Python programmers,as well as modules written in Python that pro
5、videstandardized solutions for many problems that occur in everyday programming.Some of these modules areexplicitly designed to encourage and enhance the portability of Python programs.Python语言参考手册中精确地描述了Python 语言的句法及语义.然而语言参考手册中没有提到Python 所附带功能强大的标准库.这个函式库大大地增强了Python 的实用性.其中包括C 写的内建模组,提供介面让程式进行操作系
6、统层次的工作,例如档案的输出输入;同时也有以Python 语言本身编写的模组,为实际编程时常遇的问题提供标准解决方案.这类模组有的经过特别设计以便Python 程式在跨平台的情况下运行无误.This library reference manual documents Pythons standard library,as well as many optional library modules(which may or may not be available,depending on whether the underlying platform supports them and on
7、 theconfiguration choices made at compile time).It also documents the standard types of the language and its built-infunctions and exceptions,many of which are not or incompletely documented in the Reference Manual.本参考手册罗列并说明了Python 标准库的各种功能,以及许多非核心的模组(按不同的操作系统和编译时的设置而定,不是每台机上的Python 都能用这些模组.)本手册同时记
8、载了Python 语言所有的标准数据类型,内建函数,异常类,这些在参考手册中被忽略了或只是扼要的提过一下.This manual assumes basic knowledge about the Python language.For an informal introduction to Python,see thePython Tutorial;the Python Reference Manual remains the highest authority on syntactic and semantic questions.Finally,the manual entitled E
9、xtending and Embedding the Python Interpreter describes how to add new extensionsto Python and how to embed it in other applications.本手册的读者要对Python 有基本的认识.初学者应该从Python指南开始.至于Python语言参考手册则是该语言的语法和语义问题上的权威阐释.最后扩展或嵌入Python解释器一文解说了如何在Python 中加入新的扩展模组;以及怎样把Python 解释器嵌入到其他的应用程式中.目录第第第一一一章章章内内内建建建对对对象象象Bui
10、lt-In Objects1第第第二二二章章章Python运运运行行行时时时服服服务务务Python Runtime Services32.1main 顶层脚本的运行环境Top-level script environment.3第第第三三三章章章其其其他他他各各各类类类服服服务务务Miscellaneous Services5第第第四四四章章章普普普遍遍遍的的的操操操作作作系系系统统统服服服务务务Generic Operating System Services7第第第五五五章章章可可可选选选配配配的的的操操操作作作系系系统统统服服服务务务Optional Operating System
11、Services9第第第六六六章章章互互互联联联网网网通通通讯讯讯协协协议议议及及及其其其支支支援援援Internet Protocols and Support11第第第七七七章章章互互互联联联网网网资资资料料料处处处理理理Internet Data Handling137.1base64 编码和解码MIME Base64数据Encode and decode MIME base64 data.137.2xml.dom The Document Object Model 文档对象模式API.14第第第八八八章章章多多多媒媒媒体体体服服服务务务Multimedia Services25第第第九
12、九九章章章加加加密密密服服服务务务Cryptographic Services27第第第十十十章章章Python 语语语言言言服服服务务务Python Language Services29第第第十十十一一一章章章SGI IRIX 特特特定定定服服服务务务SGI IRIX Specific Services3111.1al SGI 的音讯功能Audio functions on the SGI.3111.2AL al 模组中用到的常数。Constants used with the al module.33第第第十十十二二二章章章SunOS 特特特定定定服服服务务务SunOS Specific
13、 Services35第第第十十十三三三章章章MS Windows 有有有关关关的的的服服服务务务MS Windows Services37附附附录录录 A翻翻翻译译译团团团队队队39iii第第第一一一章章章内内内建建建对对对象象象Built-In ObjectsNames for built-in exceptions and functions and a number of constants are found in a separate symbol table.Thistable is searched last when the interpreter looks up the
14、meaning of a name,so local and global user-defined namescan override built-in names.Built-in types are described together here for easy reference.1内建的异常、函数和一组常量的名字都能在一个独立的符号表中找到。当解释器在查找一个名字的意义的时候,这个表格是被最后查找的,所以局部的和全局的用户定义的名字可以覆盖内建的名字。所有的内建类型都统一在本章描述,作为一个简单的参考。2The tables in this chapter document the
15、 priorities of operators by listing them in order of ascending priority(withina table)and grouping operators that have the same priority in the same box.Binary operators of the same prioritygroup from left to right.(Unary operators group from right to left,but there you have no real choice.)See chap
16、ter5 of the Python Reference Manual for the complete picture on operator priorities.在本章的表格中,对于操作符的优先级,以它们在表格中列出的顺序,升序排列,(在同一个表格中)并且把相同优先级的操作符组织在同一格当中。同一优先级的二元操作符已从左到右的顺序结合。(一元操作符从右到左结合,但事实上,你并没有选择的余地。)对于操作符优先级的一个整体印象参见Python参考手册第5章。1Most descriptions sorely lack explanations of the exceptions that m
17、ay be raised this will be fixed in a future version of this manual.2这儿的绝大多数描述都非常缺乏对它们所能抛出的异常的解释 这将会在本手册的未来版本得到修正。12第第第二二二章章章Python运运运行行行时时时服服服务务务Python RuntimeServicesThe modules described in this chapter provide a wide range of services related to the Python interpreter and itsinteraction with its
18、environment.Heres an overview:本章所讲到的这些模块,对于与Python解释器相关的,以及解释器和它运行环境之间的交互,提供了丰富的服务。以下是一个综述:main顶层脚本运行所在的环境The environment where the top-level script is run.2.1main 顶层脚本的运行环境Top-level script environmentThis module represents the(otherwise anonymous)scope in which the interpreters main program execute
19、s commands read either from standard input,from a script file,or from an interactive prompt.It is this environmentin which the idiomatic“conditional script”stanza causes a script to run:这个模块描述了(否则就是匿名的)解释器主程序运行命令的作用域 这些命令包括读取自标准输入的,脚本文件的,或者交互模式提示符的.一般我们会用以下的“条件脚本”块来使一个脚本运行,这个环境就是main.if _name_=_main
20、_:main()34第第第三三三章章章其其其他他他各各各类类类服服服务务务Miscellaneous ServicesThe modules described in this chapter provide miscellaneous services that are available in all Python versions.Heres an overview:本章所包含的为所有版本上的Python 皆有的各杂类模组.以下为概览:56第第第四四四章章章普普普遍遍遍的的的操操操作作作系系系统统统服服服务务务Generic OperatingSystem ServicesThe mod
21、ules described in this chapter provide interfaces to operating system features that are available on(al-most)all operating systems,such as files and a clock.The interfaces are generally modeled after the UNIXor Cinterfaces,but they are available on most other systems as well.Heres an overview:本章描述的模
22、组及为存取操作系统提供服务介面。此类服务多为(基本上)所有操作平台所共有的,如档案的读写及时钟值。介面的格式是仿照UNIX或C 的风格来建立的,但同时能使用在多数其他的系统上。78第第第五五五章章章可可可选选选配配配的的的操操操作作作系系系统统统服服服务务务OptionalOperating System ServicesThe modules described in this chapter provide interfaces to operating system features that are available on selectedoperating systems only
23、.The interfaces are generally modeled after the UNIXor C interfaces but they are availableon some other systems as well(e.g.Windows or NT).Heres an overview:本章描述的模组提供介面以存取只有某些特定操作系统才有的功能。介面设计以UNIX或C 风格为蓝本,但它们也能在其他如Windows,NT 等平台上使用。以下是概述:910第第第六六六章章章互互互联联联网网网通通通讯讯讯协协协议议议及及及其其其支支支援援援InternetProtocols
24、 and SupportThe modules described in this chapter implement Internet protocols and support for related technology.They areall implemented in Python.Most of these modules require the presence of the system-dependent module socket,which is currently supported on most popular platforms.Here is an overv
25、iew:本课描述的模组是对互联网通讯协议的实现,以及和其相关技术的支援。所有这些模组都是以Python 来实现的。大部份此类模组要用到一个依赖於操作系统的socket模组,此模组在基本存在於大多数流行的平台中。以下是本章的概述:1112第第第七七七章章章互互互联联联网网网资资资料料料处处处理理理Internet Data HandlingThis chapter describes modules which support handling data formats commonly used on the Internet.本章描述的模组帮助我们处理在互联网上通常会遇到的资料格式。base
26、64使用MIME Base64来编码和解码文件Encode and decode files using the MIME base64 data.xml.domDocument Object Model API for Python 文档对象模式.7.1 base64 编码和解码MIME Base64数据Encode and decodeMIME base64 dataThis module performs base64 encoding and decoding of arbitrary binary strings into text strings that can be safel
27、ysent by email or included as part of an HTTP POST request.The encoding scheme is defined in RFC 1521(MIME(Multipurpose Internet Mail Extensions)Part One:Mechanisms for Specifying and Describing the Format ofInternet Message Bodies,section 5.2,“Base64 Content-Transfer-Encoding”)and is used for MIME
28、email andvarious other Internet-related applications;it is not the same as the output produced by the uuencode program.For example,the string www.python.org is encoded as the string d3d3LnB5dGhvbi5vcmc=n.这个模块执行任意二进制串到文本串的Base64编码和解码,从而该数据能够被安全的由email传输或者包含并且作为HTTP POST请求的一部分。编码的模式在RFC 1521(MIME(Mult
29、ipurpose In-ternet Mail Extensions)第一部分:Mechanisms for Specifying and Describing the Format of Internet Mes-sage Bodies,5.2节,”Base64 Base64 Content-Transfer-Encoding”)中定义,并且在MIME邮件以及各种其它Internet相关的应用程序中使用;它不同于uuencode 程序的输出。例如,字符串www.python.org编码为字符串d3d3LnB5dGhvbi5vcmc=n。decode(input,output)Decode t
30、he contents of the input file and write the resulting binary data to the output file.input and out-put must either be file objects or objects that mimic the file object interface.input will be read until in-put.read()returns an empty string.decode(input,output)解码input 文件的内容,输出结果二进制数据到output 文件。input
31、 和output 必须都为文件对象或模拟文件对象接口的对象。input 将一直读取,直至input.read()返回一个空串。decodestring(s)Decode the string s,which must contain one or more lines of base64 encoded data,and return a stringcontaining the resulting binary data.decodestring(s)解码字符串s,必须包含一行或多行Base64编码数据,返回一个包含结果二进制数据的字符串。encode(input,output)Encode
32、 the contents of the input file and write the resulting base64 encoded data to the output file.inputand output must either be file objects or objects that mimic the file object interface.input will be readuntil input.read()returns an empty string.encode()returns the encoded data plus a trailing newl
33、ine13character(n).encode(input,output)编码input 文件的内容,输出结果Base64编码数据到output 文件。input 和output 必须都为文件对象或模拟文件对象接口的对象。input 将一直读取,直至input.read()返回一个空串。encode()返回编码后的数据外加一个结尾换行符(n)。encodestring(s)Encode the string s,which can contain arbitrary binary data,and return a string containing one or morelines of
34、base64-encoded data.encodestring()returns a string containing one or more lines of base64-encoded data always including an extra trailing newline(n).encodestring(s)编 码 字 符 串s,能 够 包 含 任 意 的 二 进 制 数 据,返 回 一 个 包 含 一 行 或 多 行Base64编 码 数据。encodestring()返回一个包含一行或多行Base64编码数据的字符串,而且总是包含一个额外的结尾换行符(n).See Als
35、o:Module binascii(section?):Support module containingASCII-to-binary and binary-to-ASCIIconversions.RFC 1521,“MIME(Multipurpose Internet Mail Extensions)Part One:Mechanisms for Specifying and Describing the Format of Internet Message Bodies”Section 5.2,“Base64 Content-Transfer-Encoding,”provides the
36、 definition of the base64 encoding.7.2 xml.dom The Document Object Model 文档对象模式APINew in version 2.0.The Document Object Model,or“DOM,”is a cross-language API from the World Wide Web Consortium(W3C)for accessing and modifying XML documents.A DOM implementation presents an XML document as a treestruc
37、ture,or allows client code to build such a structure from scratch.It then gives access to the structure througha set of objects which provided well-known interfaces.文档对象模式,或称”DOM”是来自互联网协会(W3C)的一种交叉语言,用以访问和修改XML文档.DOM 可以将XML文档处理成为一种树状的数据结构,或是从客户代码生成这种数据结构.并且提供了一套易读的对象来访问这种数据结构.1The DOM is extremely u
38、seful for random-access applications.SAX only allows you a view of one bit of thedocument at a time.If you are looking at one SAX element,you have no access to another.If you are looking at atext node,you have no access to a containing element.When you write a SAX application,you need to keep tracko
39、f your programs position in the document somewhere in your own code.SAX does not do it for you.Also,ifyou need to look ahead in the XML document,you are just out of luck.DOM 对于随机访问的应用非常有用.而对于SAX,则只允许你同一时刻只能访问一小片XML文档,这意味着:如果你正在关注一个SAX元素,则你无法访问另一个.如果你正在访问一个文本结点,则你无法访问其容器元素.当你写SAX应用时,你得在代码中跟踪你程序在XML文档
40、中的作用位置.SAX不能替你进行位置的记录.所以,如果你需要随时回到前面处理,SAX将无能为力!Some applications are simply impossible in an event driven model with no access to a tree.Of course you couldbuild some sort of tree yourself in SAX events,but the DOM allows you to avoid writing that code.The DOM isa standard tree representation for X
41、ML data.事务驱动模式的应用使你几乎不可能访问树形结构.当然你可以自个儿架构某种结构在SAX的事务过程中来存放树结构,但是DOM 省却了你的这种代码.DOM 是XML数据的标准树表达方式!The Document Object Model is being defined by the W3C in stages,or“levels”in their terminology.The Pythonmapping of the API is substantially based on the DOM Level 2 recommendation.The mapping of the Lev
42、el 3specification,currently only available in draft form,is being developed by the Python XML Special InterestGroup as part of the PyXML package.Refer to the documentation bundled with that package for information on1译按:(cross-language?交叉语言;)14第七章 7.互联网资料处理Internet Data Handlingthe current state of
43、DOM Level 3 support.文档对象模式在W3C 的术语体系中被划分为“阶段”(stages)或是“阶层”(levels).Python 充分的映射了DOM 阶层2 推荐的所有特性.阶层3 的规范当前Python的支持仅仅在草案阶段Python XML 特殊兴趣组也成为PyXML 包的一部分.2DOM applications typically start by parsing some XML into a DOM.How this is accomplished is not coveredat all by DOM Level 1,and Level 2 provides
44、only limited improvements:There is a DOMImplementationobject class which provides access to Document creation methods,but no way to access an XMLreader/parser/Document builder in an implementation-independent way.There is also no well-defined way toaccess these methods without an existing Document o
45、bject.In Python,each DOM implementation will providea function getDOMImplementation().DOM Level 3 adds a Load/Store specification,which defines aninterface to the reader,but this is not yet available in the Python standard library.典型的DOM应用由解析一些XML成为DOM 开始.这在Python 已经完全封装了DOM 阶层1 至阶层2的规范,仅仅除了一点限制:DOM
46、Implementation 对象类提供Document 创建方法,但是没有独立执行的XML 读取/解析/文档结构创建的方法.Python中,每次DOM 的执行都需使用函式getDOMImplementation().DOM 阶层3 增加了Load/Store 规范,可以定义一个实例来进行XML的读取,但是,这还没有在Python 标准库中实现.Once you have a DOM document object,you can access the parts of your XML document through its propertiesandmethods.Theseproper
47、tiesaredefinedintheDOMspecification;thisportionofthereferencemanualdescribesthe interpretation of the specification in Python.一但你获得了DOM文档对象,你便可以通过其提供的属性和方法来访问XML的各个部分.这些属性在DOM规范中进行了定义;手册的这一部分描述Python 的DOM 规范.The specification provided by the W3C defines the DOM API for Java,ECMAScript,and OMG IDL.Th
48、e Pythonmapping defined here is based in large part on the IDL version of the specification,but strict compliance is notrequired(though implementations are free to support the strict mapping from IDL).See section 7.2.3,“Confor-mance,”for a detailed discussion of mapping requirements.W3C定义的DOM API 规范
49、有Java,ECMAScript,和OMG IDL 版本的实现.Python的映射主要基于IDL 版本,但是并没有严密的匹配(尽管允许从IDL精确映射执行).参考7.2.3一节,一致性“Conformance,”讨论详细的映射必要条件.See Also:Document Object Model(DOM)Level 2 Specification DOM阶层2规范(http:/www.w3.org/TR/DOM-Level-2-Core/)The W3C recommendation upon which the Python DOM API is based.W3C 推荐!Python DO
50、M API 完全符合.Document Object Model(DOM)Level 1 Specification DOM阶层1规范(http:/www.w3.org/TR/REC-DOM-Level-1/)The W3C recommendation for the DOM supported by W3C 建 议 至 少 要 支 持 的,Python由xml.dom.minidom提供映射.PyXML(http:/)Users that require a full-featured implementation of DOM should use the PyXML package.需