Reference)
Release 233
Guido van Rossum
Fred L Drake Jr editor
翻译团队 见文末名单
译文修改 2004年3月22日
PythonLabs
Email docs@pythonorgCopyright c° 2001 2002 2003 Python Software Foundation All rights reserved
Copyright c° 2000 BeOpencom All rights reserved
Copyright c° 19952000 Corporation for National Research Initiatives All rights reserved
Copyright c° 19911995 Stichting Mathematisch Centrum All rights reserved
See the end of this document for complete license and permissions information
详细版权许资料见文部份Python is an extensible interpreted objectoriented programming language It supports 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 describe
the standard library that is distributed with the language and which greatly enhances its immediate usability
This library contains builtin modules (written in C) that provide access to system functionality such as file IO
that would otherwise be inaccessible to Python programmers as well as modules written in Python that provide
standardized solutions for many problems that occur in everyday programming Some of these modules are
explicitly designed to encourage and enhance the portability of Python programs
Python 语言参考手册 中精确描述Python 语言句法语义 然语言参考手册中没提Python
附带功强标准库 函式库增强Python 实性 中包括C 写建模组 提供介面
程式进行操作系统层次工作 例档案输出输入 时Python 语言身编写模组 实际
编程时常遇问题提供标准解决方案 类模组特设计便Python 程式跨台情况运
行误
This library reference manual documents Python’s 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 the
configuration choices made at compile time) It also documents the standard types of the language and its builtin
functions and exceptions many of which are not or incompletely documented in the Reference Manual
参考手册罗列说明Python 标准库种功 许非核心模组(操作系统编译时
设置定 台机Python 模组) 手册时记载Python 语言标准数类
型 建函数 异常类 参考手册中忽略扼提
This manual assumes basic knowledge about the Python language For an informal introduction to Python see the
Python Tutorial the Python Reference Manual remains the highest authority on syntactic and semantic questions
Finally the manual entitled Extending and Embedding the Python Interpreter describes how to add new extensions
to Python and how to embed it in other applications
手册读者Python 基认识 初学者应该Python 指南 开始 Python 语言参考手册
该语言语法语义问题权威阐释 扩展嵌入Python 解释器 文解说Python 中加入
新扩展模组 样Python 解释器嵌入应程式中目录
第第第章章章 建建建象象象BuiltIn Objects 1
第第第二二二章章章 Python运运运行行行时时时服服服务务务Python Runtime Services 3
21 main — 顶层脚运行环境Toplevel script environment 3
第第第三三三章章章 类类类服服服务务务Miscellaneous Services 5
第第第四四四章章章 普普普遍遍遍操操操作作作系系系统统统 服服服务务务Generic Operating System Services 7
第第第五五五章章章 选选选配配配操操操作作作系系系统统统 服服服务务务Optional Operating System Services 9
第第第六六六章章章 互互互联联联网网网通通通 讯讯讯协协协 议议议支支支援援援Internet Protocols and Support 11
第第第七七七章章章 互互互联联联网网网资资资料料料处处处理理理Internet Data Handling 13
71 base64 — 编码解码MIME Base64数Encode and decode MIME base64 data 13
72 xmldom — The Document Object Model 文档象模式API 14
第第第八八八章章章 媒媒媒体体体服服服务务务Multimedia Services 25
第第第九九九章章章 加加加密密密服服服务务务Cryptographic Services 27
第第第十十十章章章 Python 语语语言言言服服服务务务Python Language Services 29
第第第十十十章章章SGI IRIX 特特特定定定服服服务务务SGI IRIX Specific Services 31
111 al — SGI 音讯功Audio functions on the SGI 31
112 AL — al 模组中常数Constants used with the al module 33
第第第十十十二二二章章章SunOS 特特特定定定服服服务务务SunOS Specific Services 35
第第第十十十三三三章章章MS Windows 关关关服服服务务务MS Windows Services 37
附附附录录录 A 翻翻翻译译译团团团队队队 39
iii第第第章章章
建建建象象象 BuiltIn Objects
Names for builtin exceptions and functions and a number of constants are found in a separate symbol table This
table is searched last when the interpreter looks up the meaning of a name so local and global userdefined names
can override builtin names Builtin types are described together here for easy reference1
建异常函数组常量名字独立符号表中找解释器查找名字意义
时候表格查找局部全局户定义名字覆盖建名字
建类型统章描述作简单参考2
The tables in this chapter document the priorities of operators by listing them in order of ascending priority (within
a table) and grouping operators that have the same priority in the same box Binary operators of the same priority
group from left to right (Unary operators group from right to left but there you have no real choice) See chapter
5 of the Python Reference Manual for the complete picture on operator priorities
章表格中操作符优先级表格中列出序升序排列(表格中)
相优先级操作符组织格中优先级二元操作符已左右序结合(
元操作符右左结合事实没选择余) 操作符优先级整体印象参
见Python参考手册第5章
1Most descriptions sorely lack explanations of the exceptions that may be raised — this will be fixed in a future version of this manual
2绝数描述非常缺乏抛出异常解释— 会手册未版修正
12第第第二二二章章章
Python运运运行行行时时时服服服务务务 Python Runtime
Services
The modules described in this chapter provide a wide range of services related to the Python interpreter and its
interaction with its environment Here’s an overview
章讲模块Python解释器相关解释器运行环境间交互提供丰
富服务综述:
main 顶层脚运行环境The environment where the toplevel script is run
21 main — 顶层脚运行环境Toplevel script environment
This module represents the (otherwise anonymous) scope in which the interpreter’s main program executes —
commands read either from standard input from a script file or from an interactive prompt It is this environment
in which the idiomatic conditional script stanza causes a script to run
模块描述(否匿名)解释器程序运行命令作域– 命令包括读取标准输入
脚文件 者交互模式提示符 般会条件脚块脚运行 环境
main
if __name__ __main__
main()
34第第第三三三章章章
类类类服服服务务务 Miscellaneous Services
The modules described in this chapter provide miscellaneous services that are available in all Python versions
Here’s an overview
章包含版Python 皆杂类模组 概览
56第第第四四四章章章
普普普遍遍遍操操操作作作系系系统统统服服服务务务 Generic Operating
System Services
The modules 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 UNIX or C
interfaces but they are available on most other systems as well Here’s an overview
章描述模组存取操作系统提供服务介面类服务(基)操作台
档案读写时钟值介面格式仿UNIX C 风格建立时数系统
78第第第五五五章章章
选选选配配配操操操作作作系系系统统统服服服务务务 Optional
Operating System Services
The modules described in this chapter provide interfaces to operating system features that are available on selected
operating systems only The interfaces are generally modeled after the UNIX or C interfaces but they are available
on some other systems as well (eg Windows or NT) Here’s an overview
章描述模组提供介面存取某特定操作系统功介面设计UNIX C 风格蓝
Windows NT 等台概述
910第第第六六六章章章
互互互联联联网网网通通通讯讯讯协协协议议议支支支援援援 Internet
Protocols and Support
The modules described in this chapter implement Internet protocols and support for related technology They are
all implemented in Python Most of these modules require the presence of the systemdependent module socket
which is currently supported on most popular platforms Here is an overview
课描述模组互联网通讯协议实现 相关技术支援模组Python
实现部份类模组赖於操作系统socket模组模组基存於数流行
台中章概述:
1112第第第七七七章章章
互互互联联联网网网资资资料料料处处处理理理 Internet Data Handling
This chapter describes modules which support handling data formats commonly used on the Internet
章描述模组帮助处理互联网通常会遇资料格式
base64 MIME Base64编码解码文件Encode and decode files using the MIME base64 data
xmldom Document Object Model API for Python 文档象模式
71 base64 — 编 码 解 码MIME Base64数 Encode and decode
MIME base64 data
This module performs base64 encoding and decoding of arbitrary binary strings into text strings that can be safely
sent 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 of
Internet Message Bodies section 52 Base64 ContentTransferEncoding) and is used for MIME email and
various other Internetrelated applications it is not the same as the output produced by the uuencode program
For example the string ’wwwpythonorg’ is encoded as the string ’d3d3LnB5dGhvbi5vcmc\n’
模块执行意二进制串文串Base64编码解码该数够安全email传
输者包含作HTTP POST请 求部分编码模式RFC 1521 (MIME(Multipurpose In
ternet Mail Extensions) 第部分:Mechanisms for Specifying and Describing the Format of Internet Mes
sage Bodies52节Base64 Base64 ContentTransferEncoding) 中定义MIME邮件种
Internet相关应程序中uuencode 程序输出例字符串’wwwpythonorg’
编码字符串’d3d3LnB5dGhvbi5vcmc\n’
decode(input output)
Decode the 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
putread() returns an empty string
decode(input output)
解码input 文件容输出结果二进制数output 文件input output 必须文件象模
拟文件象接口象input 直读取直inputread() 返回空串
decodestring(s)
Decode the string s which must contain one or more lines of base64 encoded data and return a string
containing the resulting binary data
decodestring(s)
解码字符串s必须包含行行Base64编码数返回包含结果二进制数字符串
encode(input output)
Encode the contents of the input file and write the resulting base64 encoded data to the output file input
and output must either be file objects or objects that mimic the file object interface input will be read
until inputread() returns an empty string encode() returns the encoded data plus a trailing newline
13character (’\n’)
encode(input output)
编码input 文件容输出结果Base64编码数output 文件input output 必须文件象
模拟文件象接口象input 直读取直inputread() 返回空串encode()
返回编码数外加结尾换行符(’\n’)
encodestring(s)
Encode the string s which can contain arbitrary binary data and return a string containing one or more
lines of base64encoded 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 Also
Module binascii (section )
Support module containing ASCIItobinary and binarytoASCII conversions
RFC 1521 MIME (Multipurpose Internet Mail Extensions) Part One Mechanisms for Specifying and Describing the Format of Internet Message Bodies
Section 52 Base64 ContentTransferEncoding provides the definition of the base64 encoding
72 xmldom — The Document Object Model 文档象模式API
New in version 20
The Document Object Model or DOM is a crosslanguage API from the World Wide Web Consortium (W3C)
for accessing and modifying XML documents A DOM implementation presents an XML document as a tree
structure or allows client code to build such a structure from scratch It then gives access to the structure through
a set of objects which provided wellknown interfaces
文档象模式称DOM 互联网协会(W3C) 种交叉语言访问修改XML文档 DOM
XML文档处理成种树状数结构客户代码生成种数结构 提供套易读
象访问种数结构
1
The DOM is extremely useful for randomaccess applications SAX only allows you a view of one bit of the
document at a time If you are looking at one SAX element you have no access to another If you are looking at a
text node you have no access to a containing element When you write a SAX application you need to keep track
of your program’s position in the document somewhere in your own code SAX does not do it for you Also if
you need to look ahead in the XML document you are just out of luck
DOM 机访问应非常 SAX允许时刻访问片XML文档 意味
着 果正关注SAX元素法访问 果正访问文结点法访问
容器元素 写SAX应时代码中踪程序XML文档中作位置 SAX进行位
置记录 果需时回前面处理SAX力
Some applications are simply impossible in an event driven model with no access to a tree Of course you could
build some sort of tree yourself in SAX events but the DOM allows you to avoid writing that code The DOM is
a standard tree representation for XML data
事务驱动模式应访问树形结构 然架构某种结构SAX事务程
中存放树结构 DOM 省种代码 DOM XML数标准树表达方式
The Document Object Model is being defined by the W3C in stages or levels in their terminology The Python
mapping of the API is substantially based on the DOM Level 2 recommendation The mapping of the Level 3
specification currently only available in draft form is being developed by the Python XML Special Interest
Group as part of the PyXML package Refer to the documentation bundled with that package for information on
1译:(crosslanguage交叉语言)
14 第七章 7 互联网资料处理Internet Data Handlingthe current state of DOM Level 3 support
文档象模式W3C 术语体系中划分阶段(stages)阶层(levels) Python 充分映射
DOM 阶层2 推荐特性 阶层3 规范前Python支持仅仅草案阶段Python XML 特殊兴趣组
成PyXML 包部分
2
DOM applications typically start by parsing some XML into a DOM How this is accomplished is not covered
at all by DOM Level 1 and Level 2 provides only limited improvements There is a DOMImplementation
object class which provides access to Document creation methods but no way to access an XML
readerparserDocument builder in an implementationindependent way There is also no welldefined way to
access these methods without an existing Document object In Python each DOM implementation will provide
a function getDOMImplementation() DOM Level 3 adds a LoadStore specification which defines an
interface to the reader but this is not yet available in the Python standard library
典 型 DOM应 解 析 XML成 DOM 开 始 Python 已 完 全 封 装 DOM 阶 层1
阶 层2 规 范仅 仅 点 限 制 DOMImplementation 象 类 提 供Document 创 建 方 法
没 独 立 执 行 XML 读 取解 析文 档 结 构 创 建 方 法 Python中 次DOM 执 行 需 函
式getDOMImplementation() DOM 阶层3 增加LoadStore 规范 定义实例进行XML
读取 没Python 标准库中实现
Once you have a DOM document object you can access the parts of your XML document through its properties
and methods These properties are defined in the DOM specification this portion of the reference manual describes
the 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 The Python
mapping defined here is based in large part on the IDL version of the specification but strict compliance is not
required (though implementations are free to support the strict mapping from IDL) See section 723 Confor
mance for a detailed discussion of mapping requirements
W3C定义DOM API 规范JavaECMAScript OMG IDL 版实现 Python映射基IDL 版
没严密匹配(允许IDL精确映射执行) 参考723节 致性Conformance 讨详细
映射必条件
See Also
Document Object Model (DOM) Level 2 Specification DOM 阶层2 规范
(httpwwww3orgTRDOMLevel2Core)
The W3C recommendation upon which the Python DOM API is based W3C 推荐Python DOM API 完
全符合
Document Object Model (DOM) Level 1 Specification DOM 阶层1 规范
(httpwwww3orgTRRECDOMLevel1)
The W3C recommendation for the DOM supported by W3C 建 议 少 支 持 Python
xmldomminidom提供映射
PyXML
(httppyxmlsourceforgenet)
Users that require a fullfeatured implementation of DOM should use the PyXML package 需全部执
行特性户PyXML 包
CORBA Scripting with Python CORBA 分布式象系统脚Python
(httpcgiomgorgcgibindocorbos990802pdf)
This specifies the mapping from OMG IDL to Python 述Python OMG IDL 映射
721 Module Contents 模块s
The xmldom contains the following functions
2译:(levels级阶层)
72 xmldom — The Document Object Model 文档象模式API 15xmldom 包含函式
registerDOMImplementation(name factory)
Register the factory function with the name name The factory function should return an object which
implements the DOMImplementation interface The factory function can return the same object every
time or a new one for each call as appropriate for the specific implementation (eg if that implementation
supports some customization)
3 name注册工厂(factory)函式 工厂函式应该返回DOMImplementation象实例
谓工厂函式次调总返回适象实例特定实现(例支持某定制实
现)
(译行文斟酌)
getDOMImplementation([name[ features ]])
Return a suitable DOM implementation The name is either wellknown the module name of a
DOM implementation or None If it is not None imports the corresponding module and returns a
DOMImplementation object if the import succeeds If no name is given and if the environment variable
PYTHON DOM is set this variable is used to find the implementation
If name is not given this examines the available implementations to find one with the required feature set If
no implementation can be found raise an ImportError The features list must be a sequence of (feature
version) pairs which are passed to the hasFeature() method on available DOMImplementation
objects
Some convenience constants are also provided
EMPTY NAMESPACE
The value used to indicate that no namespace is associated with a node in the DOM This is typically
found as the namespaceURI of a node or used as the namespaceURI parameter to a namespacesspecific
method New in version 22
XML NAMESPACE
The namespace URI associated with the reserved prefix xml as defined by Namespaces in XML (section 4)
New in version 22
XMLNS NAMESPACE
The namespace URI for namespace declarations as defined by Document Object Model (DOM) Level 2
Core Specification (section 118) New in version 22
XHTML NAMESPACE
The URI of the XHTML namespace as defined by XHTML 10 The Extensible HyperText Markup Language
(section 311) New in version 22
In addition xmldom contains a base Node class and the DOM exception classes The Node class provided
by this module does not implement any of the methods or attributes defined by the DOM specification concrete
DOM implementations must provide those The Node class provided as part of this module does provide the
constants used for the nodeType attribute on concrete Node objects they are located within the class rather than
at the module level to conform with the DOM specifications
722 Objects in the DOM
The definitive documentation for the DOM is the DOM specification from the W3C
Note that DOM attributes may also be manipulated as nodes instead of as simple strings It is fairly rare that you
must do this however so this usage is not yet documented
3译:(factory function工厂函式范式种模式)
16 第七章 7 互联网资料处理Internet Data HandlingInterface Section Purpose
DOMImplementation 722 Interface to the underlying implementation
Node 722 Base interface for most objects in a document
NodeList 722 Interface for a sequence of nodes
DocumentType 722 Information about the declarations needed to process a document
Document 722 Object which represents an entire document
Element 722 Element nodes in the document hierarchy
Attr 722 Attribute value nodes on element nodes
Comment 722 Representation of comments in the source document
Text 722 Nodes containing textual content from the document
ProcessingInstruction 722 Processing instruction representation
An additional section describes the exceptions defined for working with the DOM in Python
DOMImplementation Objects
The DOMImplementation interface provides a way for applications to determine the availability of par
ticular features in the DOM they are using DOM Level 2 added the ability to create new Document and
DocumentType objects using the DOMImplementation as well
hasFeature(feature version)
Node Objects
All of the components of an XML document are subclasses of Node
nodeType
An integer representing the node type Symbolic constants for the types are on the Node
object ELEMENT NODE ATTRIBUTE NODE TEXT NODE CDATA SECTION NODE
ENTITY NODE PROCESSING INSTRUCTION NODE COMMENT NODE DOCUMENT NODE
DOCUMENT TYPE NODE NOTATION NODE This is a readonly attribute
parentNode
The parent of the current node or None for the document node The value is always a Node object or
None For Element nodes this will be the parent element except for the root element in which case it
will be the Document object For Attr nodes this is always None This is a readonly attribute
attributes
A NamedNodeMap of attribute objects Only elements have actual values for this others provide None
for this attribute This is a readonly attribute
previousSibling
The node that immediately precedes this one with the same parent For instance the element with an endtag
that comes just before the self element’s starttag Of course XML documents are made up of more than
just elements so the previous sibling could be text a comment or something else If this node is the first
child of the parent this attribute will be None This is a readonly attribute
nextSibling
The node that immediately follows this one with the same parent See also previousSibling If this is
the last child of the parent this attribute will be None This is a readonly attribute
childNodes
A list of nodes contained within this node This is a readonly attribute
firstChild
The first child of the node if there are any or None This is a readonly attribute
lastChild
The last child of the node if there are any or None This is a readonly attribute
localName
The part of the tagName following the colon if there is one else the entire tagName The value is a string
72 xmldom — The Document Object Model 文档象模式API 17prefix
The part of the tagName preceding the colon if there is one else the empty string The value is a string or
None
namespaceURI
The namespace associated with the element name This will be a string or None This is a readonly
attribute
nodeName
This has a different meaning for each node type see the DOM specification for details You can always
get the information you would get here from another property such as the tagName property for elements
or the name property for attributes For all node types the value of this attribute will be either a string or
None This is a readonly attribute
nodeValue
This has a different meaning for each node type see the DOM specification for details The situation is
similar to that with nodeName The value is a string or None
hasAttributes()
Returns true if the node has any attributes
hasChildNodes()
Returns true if the node has any child nodes
isSameNode(other)
Returns true if other refers to the same node as this node This is especially useful for DOM implementations
which use any sort of proxy architecture (because more than one object can refer to the same node)
Note This is based on a proposed DOM Level 3 API which is still in the working draft stage but this
particular interface appears uncontroversial Changes from the W3C will not necessarily affect this method
in the Python DOM interface (though any new W3C API for this would also be supported)
appendChild(newChild)
Add a new child node to this node at the end of the list of children returning newChild
insertBefore(newChild refChild)
Insert a new child node before an existing child It must be the case that refChild is a child of this node if
not ValueError is raised newChild is returned
removeChild(oldChild)
Remove a child node oldChild must be a child of this node if not ValueError is raised oldChild is
returned on success If oldChild will not be used further its unlink() method should be called
replaceChild(newChild oldChild)
Replace an existing node with a new node It must be the case that oldChild is a child of this node if not
ValueError is raised
normalize()
Join adjacent text nodes so that all stretches of text are stored as single Text instances This simplifies
processing text from a DOM tree for many applications New in version 21
cloneNode(deep)
Clone this node Setting deep means to clone all child nodes as well This returns the clone
NodeList Objects
A NodeList represents a sequence of nodes These objects are used in two ways in the DOM Core recommen
dation the Element objects provides one as its list of child nodes and the getElementsByTagName() and
getElementsByTagNameNS() methods of Node return objects with this interface to represent query results
The DOM Level 2 recommendation defines one method and one attribute for these objects
item(i)
Return the i’th item from the sequence if there is one or None The index i is not allowed to be less then
zero or greater than or equal to the length of the sequence
18 第七章 7 互联网资料处理Internet Data Handlinglength
The number of nodes in the sequence
In addition the Python DOM interface requires that some additional support is provided to allow NodeList
objects to be used as Python sequences All NodeList implementations must include support for len ()
and getitem () this allows iteration over the NodeList in for statements and proper support for the
len() builtin function
If a DOM implementation supports modification of the document the NodeList implementation must also
support the setitem () and delitem () methods
DocumentType Objects
Information about the notations and entities declared by a document (including the external subset if the parser
uses it and can provide the information) is available from a DocumentType object The DocumentType for a
document is available from the Document object’s doctype attribute if there is no DOCTYPE declaration for
the document the document’s doctype attribute will be set to None instead of an instance of this interface
DocumentType is a specialization of Node and adds the following attributes
publicId
The public identifier for the external subset of the document type definition This will be a string or None
systemId
The system identifier for the external subset of the document type definition This will be a URI as a string
or None
internalSubset
A string giving the complete internal subset from the document This does not include the brackets which
enclose the subset If the document has no internal subset this should be None
name
The name of the root element as given in the DOCTYPE declaration if present
entities
This is a NamedNodeMap giving the definitions of external entities For entity names defined more than
once only the first definition is provided (others are ignored as required by the XML recommendation)
This may be None if the information is not provided by the parser or if no entities are defined
notations
This is a NamedNodeMap giving the definitions of notations For notation names defined more than once
only the first definition is provided (others are ignored as required by the XML recommendation) This may
be None if the information is not provided by the parser or if no notations are defined
Document Objects
A Document represents an entire XML document including its constituent elements attributes processing in
structions comments etc Remeber that it inherits properties from Node
documentElement
The one and only root element of the document
createElement(tagName)
Create and return a new element node The element is not inserted into the document when it is created You
need to explicitly insert it with one of the other methods such as insertBefore() or appendChild()
createElementNS(namespaceURI tagName)
Create and return a new element with a namespace The tagName may have a prefix The element is not
inserted into the document when it is created You need to explicitly insert it with one of the other methods
such as insertBefore() or appendChild()
createTextNode(data)
Create and return a text node containing the data passed as a parameter As with the other creation methods
this one does not insert the node into the tree
72 xmldom — The Document Object Model 文档象模式API 19createComment(data)
Create and return a comment node containing the data passed as a parameter As with the other creation
methods this one does not insert the node into the tree
createProcessingInstruction(target data)
Create and return a processing instruction node containing the target and data passed as parameters As
with the other creation methods this one does not insert the node into the tree
createAttribute(name)
Create and return an attribute node This method does not associate the attribute node with any particular
element You must use setAttributeNode() on the appropriate Element object to use the newly
created attribute instance
createAttributeNS(namespaceURI qualifiedName)
Create and return an attribute node with a namespace The tagName may have a prefix This method does
not associate the attribute node with any particular element You must use setAttributeNode() on
the appropriate Element object to use the newly created attribute instance
getElementsByTagName(tagName)
Search for all descendants (direct children children’s children etc) with a particular element type name
getElementsByTagNameNS(namespaceURI localName)
Search for all descendants (direct children children’s children etc) with a particular namespace URI and
localname The localname is the part of the namespace after the prefix
Element Objects
Element is a subclass of Node so inherits all the attributes of that class
tagName
The element type name In a namespaceusing document it may have colons in it The value is a string
getElementsByTagName(tagName)
Same as equivalent method in the Document class
getElementsByTagNameNS(tagName)
Same as equivalent method in the Document class
getAttribute(attname)
Return an attribute value as a string
getAttributeNode(attrname)
Return the Attr node for the attribute named by attrname
getAttributeNS(namespaceURI localName)
Return an attribute value as a string given a namespaceURI and localName
getAttributeNodeNS(namespaceURI localName)
Return an attribute value as a node given a namespaceURI and localName
removeAttribute(attname)
Remove an attribute by name No exception is raised if there is no matching attribute
removeAttributeNode(oldAttr)
Remove and return oldAttr from the attribute list if present If oldAttr is not present NotFoundErr is
raised
removeAttributeNS(namespaceURI localName)
Remove an attribute by name Note that it uses a localName not a qname No exception is raised if there is
no matching attribute
setAttribute(attname value)
Set an attribute value from a string
setAttributeNode(newAttr)
Add a new attibute node to the element replacing an existing attribute if necessary if the name attribute
20 第七章 7 互联网资料处理Internet Data Handlingmatches If a replacement occurs the old attribute node will be returned If newAttr is already in use
InuseAttributeErr will be raised
setAttributeNodeNS(newAttr)
Add a new attibute node to the element replacing an existing attribute if necessary if the namespaceURI
and localName attributes match If a replacement occurs the old attribute node will be returned If
newAttr is already in use InuseAttributeErr will be raised
setAttributeNS(namespaceURI qname value)
Set an attribute value from a string given a namespaceURI and a qname Note that a qname is the whole
attribute name This is different than above
Attr Objects
Attr inherits from Node so inherits all its attributes
name
The attribute name In a namespaceusing document it may have colons in it
localName
The part of the name following the colon if there is one else the entire name This is a readonly attribute
prefix
The part of the name preceding the colon if there is one else the empty string
NamedNodeMap Objects
NamedNodeMap does not inherit from Node
length
The length of the attribute list
item(index)
Return an attribute with a particular index The order you get the attributes in is arbitrary but will be
consistent for the life of a DOM Each item is an attribute node Get its value with the value attribbute
There are also experimental methods that give this class more mapping behavior You can use them or you can
use the standardized getAttribute*() family of methods on the Element objects
Comment Objects
Comment represents a comment in the XML document It is a subclass of Node but cannot have child nodes
data
The content of the comment as a string The attribute contains all characters between the leading < and
trailing > but does not include them
Text and CDATASection Objects
The Text interface represents text in the XML document If the parser and DOM implementation support the
DOM’s XML extension portions of the text enclosed in CDATA marked sections are stored in CDATASection
objects These two interfaces are identical but provide different values for the nodeType attribute
These interfaces extend the Node interface They cannot have child nodes
data
The content of the text node as a string
Note The use of a CDATASection node does not indicate that the node represents a complete CDATA marked
section only that the content of the node was part of a CDATA section A single CDATA section may be
represented by more than one node in the document tree There is no way to determine whether two adjacent
CDATASection nodes represent different CDATA marked sections
72 xmldom — The Document Object Model 文档象模式API 21ProcessingInstruction Objects
Represents a processing instruction in the XML document this inherits from the Node interface and cannot have
child nodes
target
The content of the processing instruction up to the first whitespace character This is a readonly attribute
data
The content of the processing instruction following the first whitespace character
Exceptions
New in version 21
The DOM Level 2 recommendation defines a single exception DOMException and a number of constants that
allow applications to determine what sort of error occurred DOMException instances carry a code attribute
that provides the appropriate value for the specific exception
The Python DOM interface provides the constants but also expands the set of exceptions so that a specific excep
tion exists for each of the exception codes defined by the DOM The implementations must raise the appropriate
specific exception each of which carries the appropriate value for the code attribute
exception DOMException
Base exception class used for all specific DOM exceptions This exception class cannot be directly instan
tiated
exception DomstringSizeErr
Raised when a specified range of text does not fit into a string This is not known to be used in the Python
DOM implementations but may be received from DOM implementations not written in Python
exception HierarchyRequestErr
Raised when an attempt is made to insert a node where the node type is not allowed
exception IndexSizeErr
Raised when an index or size parameter to a method is negative or exceeds the allowed values
exception InuseAttributeErr
Raised when an attempt is made to insert an Attr node that is already present elsewhere in the document
exception InvalidAccessErr
Raised if a parameter or an operation is not supported on the underlying object
exception InvalidCharacterErr
This exception is raised when a string parameter contains a character that is not permitted in the context it’s
being used in by the XML 10 recommendation For example attempting to create an Element node with
a space in the element type name will cause this error to be raised
exception InvalidModificationErr
Raised when an attempt is made to modify the type of a node
exception InvalidStateErr
Raised when an attempt is made to use an object that is not or is no longer usable
exception NamespaceErr
If an attempt is made to change any object in a way that is not permitted with regard to the Namespaces in
XML recommendation this exception is raised
exception NotFoundErr
Exception when a node does not exist in the referenced context For example
NamedNodeMapremoveNamedItem() will raise this if the node passed in does not exist in
the map
exception NotSupportedErr
Raised when the implementation does not support the requested type of object or operation
22 第七章 7 互联网资料处理Internet Data Handlingexception NoDataAllowedErr
This is raised if data is specified for a node which does not support data
exception NoModificationAllowedErr
Raised on attempts to modify an object where modifications are not allowed (such as for readonly nodes)
exception SyntaxErr
Raised when an invalid or illegal string is specified
exception WrongDocumentErr
Raised when a node is inserted in a different document than it currently belongs to and the implementation
does not support migrating the node from one document to the other
The exception codes defined in the DOM recommendation map to the exceptions described above according to
this table
Constant Exception
DOMSTRING SIZE ERR DomstringSizeErr
HIERARCHY REQUEST ERR HierarchyRequestErr
INDEX SIZE ERR IndexSizeErr
INUSE ATTRIBUTE ERR InuseAttributeErr
INVALID ACCESS ERR InvalidAccessErr
INVALID CHARACTER ERR InvalidCharacterErr
INVALID MODIFICATION ERR InvalidModificationErr
INVALID STATE ERR InvalidStateErr
NAMESPACE ERR NamespaceErr
NOT FOUND ERR NotFoundErr
NOT SUPPORTED ERR NotSupportedErr
NO DATA ALLOWED ERR NoDataAllowedErr
NO MODIFICATION ALLOWED ERR NoModificationAllowedErr
SYNTAX ERR SyntaxErr
WRONG DOCUMENT ERR WrongDocumentErr
723 Conformance
This section describes the conformance requirements and relationships between the Python DOM API the W3C
DOM recommendations and the OMG IDL mapping for Python
Type Mapping
The primitive IDL types used in the DOM specification are mapped to Python types according to the following
table
IDL Type Python Type
boolean IntegerType (with a value of 0 or 1)
int IntegerType
long int IntegerType
unsigned int IntegerType
Additionally the DOMString defined in the recommendation is mapped to a Python string or Unicode string
Applications should be able to handle Unicode whenever a string is returned from the DOM
The IDL null value is mapped to None which may be accepted or provided by the implementation whenever
null is allowed by the API
Accessor Methods
The mapping from OMG IDL to Python defines accessor functions for IDL attribute declarations in much
the way the Java mapping does Mapping the IDL declarations
72 xmldom — The Document Object Model 文档象模式API 23readonly attribute string someValue
attribute string anotherValue
yields three accessor functions a get method for someValue ( get someValue()) and get and set
methods for anotherValue ( get anotherValue() and set anotherValue()) The mapping in
particular does not require that the IDL attributes are accessible as normal Python attributes objectsomeValue
is not required to work and may raise an AttributeError
The Python DOM API however does require that normal attribute access work This means that the typical
surrogates generated by Python IDL compilers are not likely to work and wrapper objects may be needed on the
client if the DOM objects are accessed via CORBA While this does require some additional consideration for
CORBA DOM clients the implementers with experience using DOM over CORBA from Python do not consider
this a problem Attributes that are declared readonly may not restrict write access in all DOM implementations
Additionally the accessor functions are not required If provided they should take the form defined by the Python
IDL mapping but these methods are considered unnecessary since the attributes are accessible directly from
Python Set accessors should never be provided for readonly attributes
24 第七章 7 互联网资料处理Internet Data Handling第第第八八八章章章
媒媒媒体体体服服服务务务 Multimedia Services
The modules described in this chapter implement various algorithms or interfaces that are mainly useful for mul
timedia applications They are available at the discretion of the installation Here’s an overview
章描述模组实现媒体应中遇介面算法否调视安装Python 时
选项定概述
2526第第第九九九章章章
加加加密密密服服服务务务 Cryptographic Services
The modules described in this chapter implement various algorithms of a cryptographic nature They are available
at the discretion of the installation Here’s an overview
章描述模组实现具加密性质算法视安装时选项定概述
Hardcore cypherpunks will probably find the cryptographic modules written by AM Kuchling of further interest
the package adds builtin modules for DES and IDEA encryption provides a Python module for reading and
decrypting PGP files and then some These modules are not distributed with Python but available separately See
the URL httpwwwamkcapythoncodecryptohtml for more information
加密十分狂热者找找AM Kuchling 写加密模组 提供DES IDEA 加密法建模组 提
供Python 模组读取解读PGP 档案 东西 模组包括Python 发布中
处取详情请httpwwwamkcapythoncodecryptohtml
2728第第第十十十章章章
Python 语语语言言言服服服务务务 Python Language
Services
Python provides a number of modules to assist in working with the Python language These module support
tokenizing parsing syntax analysis bytecode disassembly and various other facilities
Python 系列模组分析Python 语言身工作提供帮助模组包括标记符辨识分词
字元码反编译辅助工具
These modules include
类模组包括:
2930第第第十十十章章章
SGI IRIX 特特特定定定服服服务务务 SGI IRIX Specific
Services
The modules described in this chapter provide interfaces to features that are unique to SGI’s IRIX operating system
(versions 4 and 5)
章描述模组SGI IRIX 操作系统(版4 5) 提供介面 存取该系统独功
al SGI 音讯功Audio functions on the SGI
AL al 模组中常数Constants used with the al module
111 al — SGI 音讯功Audio functions on the SGI
This module provides access to the audio facilities of the SGI Indy and Indigo workstations See section 3A of the
IRIX man pages for details You’ll need to read those man pages to understand what these functions do Some of
the functions are not available in IRIX releases before 405 Again see the manual to check whether a specific
function is available on your platform
模组存取SGI Indy Indigo 工作站音讯设备详细情况参考IRIX 帮助页第3A 节
帮助页明白函数干什函数IRIX 405 版前
说遍相关手册检查某指定函数否台
All functions and methods defined in this module are equivalent to the C functions with AL’ prefixed to their
name
模组定义函数方法C 中AL’ 前缀名函数等价
Symbolic constants from the C header file
C 标头档
Warning The current version of the audio library may dump core when bad argument values are passed rather
than returning an error status Unfortunately since the precise circumstances under which this may happen are
undocumented and hard to check the Python interface can provide no protection against this kind of problems
(One example is specifying an excessive queue size — there is no documented upper limit)
Warning 音讯函数库目版调时收合法引数时会产生core 档会传回错误态
惜底种情况会产生错法现文献中找难试出Python
法问题提供保护(例:提交额外队列时没文献提限
少)
The module defines the following functions
模组提供函数:
openport(name direction[ config])
The name and direction arguments are strings The optional config argument is a configuration object as
31returned by newconfig() The return value is an audio port object methods of audio port objects are
described below
name direction 引数皆字串选引数config 透调newconfig() 配置
象函数传回音讯端口象audio port object 象包含面描述方法
newconfig()
The return value is a new audio configuration object methods of audio configuration objects are described
below
传回新音讯配置象audio configuration object 该象包含面描述方法
queryparams(device)
The device argument is an integer The return value is a list of integers containing the data returned by
ALqueryparams()
device 引数整数传回整数列表中包含ALqueryparams() 传回数
getparams(device list)
The device argument is an integer The list argument is a list such as returned by queryparams() it is
modified in place ()
device 引数整数list 引数queryparam() 传回列表列表会场修改
()
setparams(device list)
The device argument is an integer The list argument is a list such as returned by queryparams()
device 引数整数list 引数queryparam() 传回列表
1111 配置象Configuration Objects
Configuration objects returned by newconfig() have the following methods
配置象newconfig() 传回 方
getqueuesize()
Return the queue size 传回队列
setqueuesize(size)
Set the queue size 设定队列
getwidth()
Get the sample width 获取样宽度
setwidth(width)
Set the sample width 设定取样宽度
getchannels()
Get the channel count 取频道数目
setchannels(nchannels)
Set the channel count 设定频道数目
getsampfmt()
Get the sample format 取样格式
setsampfmt(sampfmt)
Set the sample format 设定样格式
getfloatmax()
Get the maximum value for floating sample formats 取浮点样格式值
setfloatmax(floatmax)
Set the maximum value for floating sample formats 设定浮点样格式值
32 第十章 11 SGI IRIX 特定服务SGI IRIX Specific Services1112 端口象Port Objects
Port objects as returned by openport() have the following methods
端口象调openport() 方法:
closeport()
Close the port 关闭端口
getfd()
Return the file descriptor as an int 传回描述档案整数值
getfilled()
Return the number of filled samples 传回已取值样数目
getfillable()
Return the number of fillable samples 传回取值样数目
readsamps(nsamples)
Read a number of samples from the queue blocking if necessary Return the data as a string containing the
raw data (eg 2 bytes per sample in bigendian byte order (high byte low byte) if you have set the sample
width to 2 bytes)
队列中读取定数目样等候态直读取完毕传回代表原始数字符串(例
设定取样宽度两位元话 样双字元位次序存放(高字元 低字元))
writesamps(samples)
Write samples into the queue blocking if necessary The samples are encoded as described for the
readsamps() return value
样写队列中 等候态直写完样编码方式readsamps() 函数传回值描述
样
getfillpoint()
Return the fill point’ 传回填入点fill point
setfillpoint(fillpoint)
Set the fill point’ 设置填入点fill point
getconfig()
Return a configuration object containing the current configuration of the port
传回配置象中包含目前端口配置
setconfig(config)
Set the configuration from the argument a configuration object
引数配置象设置端口
getstatus(list)
Get status information on last error
取次错误状态资料
112 AL — al 模组中常数Constants used with the al module
This module defines symbolic constants needed to use the builtin module al (see above) they are equivalent to
those defined in the C header file
source for a complete list of the defined names Suggested use
模组定义建模组al (面)时常量C 标头档
样忽略掉AL ’ 前缀全部常量定义参源码建议法:
import al
from AL import *
112 AL — al 模组中常数Constants used with the al module 3334第第第十十十二二二章章章
SunOS 特特特定定定服服服务务务 SunOS Specific Services
The modules described in this chapter provide interfaces to features that are unique to the SunOS operating system
(versions 4 and 5 the latter is also known as Solaris version 2)
章描述模组提供介面存取SunOX 操作系统独功(版4 5 者称Solaris
Version 2)
3536第第第十十十三三三章章章
MS Windows 关关关服服服务务务 MS Windows
Services
This chapter describes modules that are only available on MS Windows platforms
章描述存MS Windows 台模组
3738附附附录录录 A
翻翻翻译译译团团团队队队
• 杜文山
• 刘鑫
• 余颖
• glace 勤
• Leira
• Hackgou
• ZoomQuiet
39
《香当网》用户分享的内容,不代表《香当网》观点或立场,请自行判断内容的真实性和可靠性!
该内容是文档的文本内容,更好的格式请下载文档