Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

23711 lines (14262 sloc) 694.267 kb
/*-+未翻译部分
+-*/markup _ Structured Markup Processing Tools
+-*/+-*/xmlrpc _
+-*/+-*/+-*/client p XML-RPC client access.
+-*/+-*/+-*/+-*/dumps f
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
:exc:`Fault` 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 :const:`None` value cannot be used in standard XML-RPC; to allow using
it via an extension, provide a true value for *allow_none*.
+-*/+-*/+-*/+-*/loads f
loads(data, use_datetime=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 :exc:`Fault` exception.
The *use_datetime* flag can be used to cause date/time values to be presented as
:class:`datetime.datetime` objects; this is false by default.
+-*/+-*/+-*/+-*/MultiCall c
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
:class:`MultiCall` 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 :term:`generator`; iterating over this generator yields the individual
results.
+-*/+-*/+-*/+-*/ServerProxy c
ServerProxy(uri, transport=None, encoding=None, verbose=False, allow_none=False, use_datetime=False)
A :class:`ServerProxy` 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
:class:`SafeTransport` instance for https: URLs and an internal HTTP
:class:`Transport` instance otherwise. The optional third argument is an
encoding, by default UTF-8. The optional fourth argument is a debugging flag.
If *allow_none* is true, the Python constant ``None`` will be translated into
XML; the default behaviour is for ``None`` to raise a :exc:`TypeError`. 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 for a
description. The *use_datetime* flag can be used to cause date/time values to
be presented as :class:`datetime.datetime` objects; this is false by default.
:class:`datetime.datetime` objects may be passed to calls.
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.
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.
:class:`ServerProxy` instance methods take Python basic types and objects as
arguments and return Python basic types and classes. 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):
+---------------------------------+---------------------------------------------+
| Name | Meaning |
+=================================+=============================================+
| :const:`boolean` | The :const:`True` and :const:`False` |
| | constants |
+---------------------------------+---------------------------------------------+
| :const:`integers` | Pass in directly |
+---------------------------------+---------------------------------------------+
| :const:`floating-point numbers` | Pass in directly |
+---------------------------------+---------------------------------------------+
| :const:`strings` | Pass in directly |
+---------------------------------+---------------------------------------------+
| :const:`arrays` | Any Python sequence type containing |
| | conformable elements. Arrays are returned |
| | as lists |
+---------------------------------+---------------------------------------------+
| :const:`structures` | A Python dictionary. Keys must be strings, |
| | values may be any conformable type. Objects |
| | of user-defined classes can be passed in; |
| | only their *__dict__* attribute is |
| | transmitted. |
+---------------------------------+---------------------------------------------+
| :const:`dates` | in seconds since the epoch (pass in an |
| | instance of the :class:`DateTime` class) or |
| | a :class:`datetime.datetime` instance. |
+---------------------------------+---------------------------------------------+
| :const:`binary data` | pass in an instance of the :class:`Binary` |
| | wrapper class |
+---------------------------------+---------------------------------------------+
This is the full set of data types supported by XML-RPC. Method calls may also
raise a special :exc:`Fault` instance, used to signal XML-RPC server errors, or
:exc:`ProtocolError` used to signal an error in the HTTP/HTTPS transport layer.
Both :exc:`Fault` and :exc:`ProtocolError` derive from a base class called
:exc:`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 strings via
XML-RPC, use the :class:`Binary` wrapper class described below.
:class:`Server` is retained as an alias for :class:`ServerProxy` for backwards
compatibility. New code should use :class:`ServerProxy`.
+-*/+-*/+-*/+-*/Binary _
+-*/+-*/+-*/+-*/+-*/data d
data
The binary data encapsulated by the :class:`Binary` instance. The data is
provided as an 8-bit string.
+-*/+-*/+-*/+-*/+-*/decode m
decode(string)
Accept a base64 string and decode it as the instance's new data.
+-*/+-*/+-*/+-*/+-*/encode m
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 <http://tools.ietf.org/html/rfc2045#section-6.8>`_,
which was the de facto standard base64 specification when the
XML-RPC spec was written.
+-*/+-*/+-*/+-*/Fault _
+-*/+-*/+-*/+-*/+-*/faultCode d
faultCode
A string indicating the fault type.
+-*/+-*/+-*/+-*/+-*/faultString d
faultString
A string containing a diagnostic message associated with the fault.
+-*/+-*/+-*/+-*/ProtocolError _
+-*/+-*/+-*/+-*/+-*/url d
url
The URI or URL that triggered the error.
+-*/+-*/+-*/+-*/+-*/headers d
headers
A dict containing the headers of the HTTP/HTTPS request that triggered the
error.
+-*/+-*/+-*/+-*/+-*/errcode d
errcode
The error code.
+-*/+-*/+-*/+-*/+-*/errmsg d
errmsg
The error message or diagnostic string.
+-*/+-*/+-*/+-*/DateTime _
+-*/+-*/+-*/+-*/+-*/decode m
decode(string)
Accept a string as the instance's new time value.
+-*/+-*/+-*/+-*/+-*/encode m
encode(out)
Write the XML-RPC encoding of this :class:`DateTime` item to the *out* stream
object.
+-*/+-*/+-*/server p Basic XML-RPC server implementations.
+-*/+-*/+-*/+-*/DocXMLRPCRequestHandler c
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 :class:`DocXMLRPCServer` constructor parameter is
honored.
+-*/+-*/+-*/+-*/DocCGIXMLRPCRequestHandler c
DocCGIXMLRPCRequestHandler()
Create a new instance to handle XML-RPC requests in a CGI environment.
+-*/+-*/+-*/+-*/+-*/set_server_documentation m
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.
+-*/+-*/+-*/+-*/+-*/set_server_name m
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.
+-*/+-*/+-*/+-*/+-*/set_server_title m
set_server_title(server_title)
Set the title used in the generated HTML documentation. This title will be used
inside the HTML "title" element.
+-*/+-*/+-*/+-*/SimpleXMLRPCServer c
SimpleXMLRPCServer(addr, requestHandler=SimpleXMLRPCRequestHandler, logRequests=True, allow_none=False, encoding=None, bind_and_activate=True)
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
:class:`SimpleXMLRPCRequestHandler`. The *addr* and *requestHandler* parameters
are passed to the :class:`socketserver.TCPServer` 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 :mod:`xmlrpc.client` and control the XML-RPC responses that will be returned
from the server. The *bind_and_activate* parameter controls whether
:meth:`server_bind` and :meth:`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.
+-*/+-*/+-*/+-*/+-*/register_multicall_functions m
register_multicall_functions()
Registers the XML-RPC multicall function system.multicall.
+-*/+-*/+-*/+-*/+-*/register_function m
register_function(function, 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* can be either a normal or Unicode
string, and may contain characters not legal in Python identifiers, including
the period character.
+-*/+-*/+-*/+-*/+-*/register_introspection_functions m
register_introspection_functions()
Registers the XML-RPC introspection functions ``system.listMethods``,
``system.methodHelp`` and ``system.methodSignature``.
+-*/+-*/+-*/+-*/+-*/register_instance m
register_instance(instance, allow_dotted_names=False)
Register an object which is used to expose method names which have not been
registered using :meth:`register_function`. If *instance* contains a
:meth:`_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
:meth:`_dispatch` is returned to the client as the result. If *instance* does
not have a :meth:`_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 :meth:`_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.
.. warning::
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.
+-*/+-*/+-*/+-*/CGIXMLRPCRequestHandler c
CGIXMLRPCRequestHandler(allow_none=False, encoding=None)
Create a new instance to handle XML-RPC requests in a CGI environment. The
*allow_none* and *encoding* parameters are passed on to :mod:`xmlrpc.client`
and control the XML-RPC responses that will be returned from the server.
+-*/+-*/+-*/+-*/+-*/handle_request m
handle_request(request_text=None)
Handle a 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.
+-*/+-*/+-*/+-*/+-*/register_multicall_functions m
register_multicall_functions()
Register the XML-RPC multicall function ``system.multicall``.
+-*/+-*/+-*/+-*/+-*/register_function m
register_function(function, 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* can be either a normal or Unicode
string, and may contain characters not legal in Python identifiers, including
the period character.
+-*/+-*/+-*/+-*/+-*/register_introspection_functions m
register_introspection_functions()
Register the XML-RPC introspection functions ``system.listMethods``,
``system.methodHelp`` and ``system.methodSignature``.
+-*/+-*/+-*/+-*/+-*/register_instance m
register_instance(instance)
Register an object which is used to expose method names which have not been
registered using :meth:`register_function`. If instance contains a
:meth:`_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 :meth:`_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.
+-*/+-*/+-*/+-*/SimpleXMLRPCRequestHandler c
SimpleXMLRPCRequestHandler()
Create a new request handler instance. This request handler supports ``POST``
requests and modifies logging so that the *logRequests* parameter to the
:class:`SimpleXMLRPCServer` constructor parameter is honored.
+-*/+-*/+-*/+-*/+-*/rpc_paths d
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')``.
+-*/+-*/+-*/+-*/DocXMLRPCServer c
DocXMLRPCServer(addr, requestHandler=DocXMLRPCRequestHandler, logRequests=True, allow_none=False, encoding=None, bind_and_activate=True)
Create a new server instance. All parameters have the same meaning as for
:class:`SimpleXMLRPCServer`; *requestHandler* defaults to
:class:`DocXMLRPCRequestHandler`.
+-*/+-*/+-*/+-*/+-*/set_server_documentation m
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.
+-*/+-*/+-*/+-*/+-*/set_server_name m
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.
+-*/+-*/+-*/+-*/+-*/set_server_title m
set_server_title(server_title)
Set the title used in the generated HTML documentation. This title will be used
inside the HTML "title" element.
+-*/+-*/xml p
+-*/+-*/+-*/dom p Document Object Model API for Python.
+-*/+-*/+-*/+-*/getDOMImplementation f
getDOMImplementation(name=None, features=())
Return a suitable DOM implementation. The *name* is either well-known, the
module name of a DOM implementation, or ``None``. If it is not ``None``, imports
the corresponding module and returns a :class:`DOMImplementation` object if the
import succeeds. If no name is given, and if the environment variable
:envvar:`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
:exc:`ImportError`. The features list must be a sequence of ``(feature,
version)`` pairs which are passed to the :meth:`hasFeature` method on available
:class:`DOMImplementation` objects.
+-*/+-*/+-*/+-*/registerDOMImplementation f
registerDOMImplementation(name, factory)
Register the *factory* function with the name *name*. The factory function
should return an object which implements the :class:`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 (e.g. if that
implementation supports some customization).
+-*/+-*/+-*/+-*/XHTML_NAMESPACE d
+-*/+-*/+-*/+-*/XMLNS_NAMESPACE d
+-*/+-*/+-*/+-*/EMPTY_NAMESPACE d
+-*/+-*/+-*/+-*/XML_NAMESPACE d
+-*/+-*/+-*/+-*/DOMException e DOM异常
+-*/+-*/+-*/+-*/+-*/InvalidModificationErr e 修改无效错误(通常指CSS)
+-*/+-*/+-*/+-*/+-*/InvalidCharacterErr e 非法字符错误
+-*/+-*/+-*/+-*/+-*/HierarchyRequestErr e 插入节点位置不恰当错误
+-*/+-*/+-*/+-*/+-*/DomstringSizeErr e 文本太大错误
+-*/+-*/+-*/+-*/+-*/IndexSizeErr e 数组下标溢出错误
+-*/+-*/+-*/+-*/+-*/InuseAttributeErr e 属性节点已使用错误
+-*/+-*/+-*/+-*/+-*/NotSupportedErr e 不支持操作错误
+-*/+-*/+-*/+-*/+-*/SyntaxErr e 语法错误(通常指CSS)
+-*/+-*/+-*/+-*/+-*/WrongDocumentErr e 不同文档节点混用错误
+-*/+-*/+-*/+-*/+-*/NamespaceErr e 命名空间错误
+-*/+-*/+-*/+-*/+-*/NotFoundErr e 未找到节点错误
+-*/+-*/+-*/+-*/+-*/NoDataAllowedErr e 非数据节点操作错误
+-*/+-*/+-*/+-*/+-*/InvalidAccessErr e 对象节点操作错误
+-*/+-*/+-*/+-*/+-*/InvalidStateErr e 状态错误
+-*/+-*/+-*/+-*/+-*/NoModificationAllowedErr e 修改只读节点错误
+-*/+-*/+-*/+-*/Comment _
+-*/+-*/+-*/+-*/+-*/data d
data
The content of the comment as a string. The attribute contains all characters
between the leading ``<!-``\ ``-`` and trailing ``-``\ ``->``, but does not
include them.
+-*/+-*/+-*/+-*/Node _
+-*/+-*/+-*/+-*/+-*/lastChild d 最后一个子节点(只读),没有则为None
+-*/+-*/+-*/+-*/+-*/nodeType d
nodeType
An integer representing the node type. Symbolic constants for the types are on
the :class:`Node` object: :const:`ELEMENT_NODE`, :const:`ATTRIBUTE_NODE`,
:const:`TEXT_NODE`, :const:`CDATA_SECTION_NODE`, :const:`ENTITY_NODE`,
:const:`PROCESSING_INSTRUCTION_NODE`, :const:`COMMENT_NODE`,
:const:`DOCUMENT_NODE`, :const:`DOCUMENT_TYPE_NODE`, :const:`NOTATION_NODE`.
This is a read-only attribute.
+-*/+-*/+-*/+-*/+-*/nodeName d
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 :attr:`tagName` property for elements or the :attr:`name`
property for attributes. For all node types, the value of this attribute will be
either a string or ``None``. This is a read-only attribute.
+-*/+-*/+-*/+-*/+-*/parentNode d
parentNode
The parent of the current node, or ``None`` for the document node. The value is
always a :class:`Node` object or ``None``. For :class:`Element` nodes, this
will be the parent element, except for the root element, in which case it will
be the :class:`Document` object. For :class:`Attr` nodes, this is always
``None``. This is a read-only attribute.
+-*/+-*/+-*/+-*/+-*/nextSibling d
nextSibling
The node that immediately follows this one with the same parent. See also
:attr:`previousSibling`. If this is the last child of the parent, this
attribute will be ``None``. This is a read-only attribute.
+-*/+-*/+-*/+-*/+-*/nodeValue d
nodeValue
This has a different meaning for each node type; see the DOM specification for
details. The situation is similar to that with :attr:`nodeName`. The value is
a string or ``None``.
+-*/+-*/+-*/+-*/+-*/namespaceURI d
namespaceURI
The namespace associated with the element name. This will be a string or
``None``. This is a read-only attribute.
+-*/+-*/+-*/+-*/+-*/prefix d
prefix
The part of the :attr:`tagName` preceding the colon if there is one, else the
empty string. The value is a string, or ``None``
+-*/+-*/+-*/+-*/+-*/firstChild d 第一个子节点(只读),没有则为None
+-*/+-*/+-*/+-*/+-*/localName d
localName
The part of the :attr:`tagName` following the colon if there is one, else the
entire :attr:`tagName`. The value is a string.
+-*/+-*/+-*/+-*/+-*/attributes d
attributes
A :class:`NamedNodeMap` of attribute objects. Only elements have actual values
for this; others provide ``None`` for this attribute. This is a read-only
attribute.
+-*/+-*/+-*/+-*/+-*/childNodes d
childNodes
A list of nodes contained within this node. This is a read-only attribute.
+-*/+-*/+-*/+-*/+-*/previousSibling d
previousSibling
The node that immediately precedes this one with the same parent. For
instance the element with an end-tag that comes just before the *self*
element's start-tag. 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 read-only attribute.
+-*/+-*/+-*/+-*/+-*/normalize m
normalize()
Join adjacent text nodes so that all stretches of text are stored as single
:class:`Text` instances. This simplifies processing text from a DOM tree for
many applications.
+-*/+-*/+-*/+-*/+-*/appendChild m
appendChild(newChild)
Add a new child node to this node at the end of the list of
children, returning *newChild*. If the node was already in
in the tree, it is removed first.
+-*/+-*/+-*/+-*/+-*/hasAttributes m
hasAttributes()
Returns true if the node has any attributes.
+-*/+-*/+-*/+-*/+-*/insertBefore m
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, :exc:`ValueError` is raised.
*newChild* is returned. If *refChild* is ``None``, it inserts *newChild* at the
end of the children's list.
+-*/+-*/+-*/+-*/+-*/isSameNode m
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).
+-*/+-*/+-*/+-*/+-*/cloneNode m
cloneNode(deep)
Clone this node. Setting *deep* means to clone all child nodes as well. This
returns the clone.
+-*/+-*/+-*/+-*/+-*/removeChild m
removeChild(oldChild)
Remove a child node. *oldChild* must be a child of this node; if not,
:exc:`ValueError` is raised. *oldChild* is returned on success. If *oldChild*
will not be used further, its :meth:`unlink` method should be called.
+-*/+-*/+-*/+-*/+-*/hasChildNodes m
hasChildNodes()
Returns true if the node has any child nodes.
+-*/+-*/+-*/+-*/+-*/replaceChild m
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, :exc:`ValueError` is raised.
+-*/+-*/+-*/+-*/Document _
+-*/+-*/+-*/+-*/+-*/documentElement d
documentElement
The one and only root element of the document.
+-*/+-*/+-*/+-*/+-*/createAttribute m
createAttribute(name)
Create and return an attribute node. This method does not associate the
attribute node with any particular element. You must use
:meth:`setAttributeNode` on the appropriate :class:`Element` object to use the
newly created attribute instance.
+-*/+-*/+-*/+-*/+-*/createComment m
createComment(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.
+-*/+-*/+-*/+-*/+-*/getElementsByTagName m
getElementsByTagName(tagName)
Search for all descendants (direct children, children's children, etc.) with a
particular element type name.
+-*/+-*/+-*/+-*/+-*/createElementNS m
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
:meth:`insertBefore` or :meth:`appendChild`.
+-*/+-*/+-*/+-*/+-*/getElementsByTagNameNS m
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.
+-*/+-*/+-*/+-*/+-*/createAttributeNS m
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 :meth:`setAttributeNode` on the appropriate
:class:`Element` object to use the newly created attribute instance.
+-*/+-*/+-*/+-*/+-*/createElement m
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 :meth:`insertBefore` or :meth:`appendChild`.
+-*/+-*/+-*/+-*/+-*/createProcessingInstruction m
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.
+-*/+-*/+-*/+-*/+-*/createTextNode m
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.
+-*/+-*/+-*/+-*/NodeList _
+-*/+-*/+-*/+-*/+-*/length d
length
The number of nodes in the sequence.
+-*/+-*/+-*/+-*/+-*/item m
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.
+-*/+-*/+-*/+-*/Attr _
+-*/+-*/+-*/+-*/+-*/localName d
localName
The part of the name following the colon if there is one, else the
entire name.
This is a read-only attribute.
+-*/+-*/+-*/+-*/+-*/prefix d
prefix
The part of the name preceding the colon if there is one, else the
empty string.
+-*/+-*/+-*/+-*/+-*/name d
name
The attribute name.
In a namespace-using document it may include a colon.
+-*/+-*/+-*/+-*/+-*/value d
value
The text value of the attribute. This is a synonym for the
:attr:`nodeValue` attribute.
+-*/+-*/+-*/+-*/ProcessingInstruction _
+-*/+-*/+-*/+-*/+-*/data d
data
The content of the processing instruction following the first whitespace
character.
+-*/+-*/+-*/+-*/+-*/target d
target
The content of the processing instruction up to the first whitespace character.
This is a read-only attribute.
+-*/+-*/+-*/+-*/Text _
+-*/+-*/+-*/+-*/+-*/data d
data
The content of the text node as a string.
+-*/+-*/+-*/+-*/Element _
+-*/+-*/+-*/+-*/+-*/tagName d
tagName
The element type name. In a namespace-using document it may have colons in it.
The value is a string.
+-*/+-*/+-*/+-*/+-*/removeAttributeNS m
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.
+-*/+-*/+-*/+-*/+-*/removeAttribute m
removeAttribute(name)
Remove an attribute by name. If there is no matching attribute, a
:exc:`NotFoundErr` is raised.
+-*/+-*/+-*/+-*/+-*/getAttributeNode m
getAttributeNode(attrname)
Return the :class:`Attr` node for the attribute named by *attrname*.
+-*/+-*/+-*/+-*/+-*/getElementsByTagName m
getElementsByTagName(tagName)
Same as equivalent method in the :class:`Document` class.
+-*/+-*/+-*/+-*/+-*/setAttributeNodeNS m
setAttributeNodeNS(newAttr)
Add a new attribute node to the element, replacing an existing attribute if
necessary if the :attr:`namespaceURI` and :attr:`localName` attributes match.
If a replacement occurs, the old attribute node will be returned. If *newAttr*
is already in use, :exc:`InuseAttributeErr` will be raised.
+-*/+-*/+-*/+-*/+-*/setAttribute m
setAttribute(name, value)
Set an attribute value from a string.
+-*/+-*/+-*/+-*/+-*/getElementsByTagNameNS m
getElementsByTagNameNS(namespaceURI, localName)
Same as equivalent method in the :class:`Document` class.
+-*/+-*/+-*/+-*/+-*/hasAttributeNS m
hasAttributeNS(namespaceURI, localName)
Returns true if the element has an attribute named by *namespaceURI* and
*localName*.
+-*/+-*/+-*/+-*/+-*/getAttribute m
getAttribute(name)
Return the value of the attribute named by *name* as a string. If no such
attribute exists, an empty string is returned, as if the attribute had no value.
+-*/+-*/+-*/+-*/+-*/getAttributeNodeNS m
getAttributeNodeNS(namespaceURI, localName)
Return an attribute value as a node, given a *namespaceURI* and *localName*.
+-*/+-*/+-*/+-*/+-*/hasAttribute m
hasAttribute(name)
Returns true if the element has an attribute named by *name*.
+-*/+-*/+-*/+-*/+-*/setAttributeNS m
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.
+-*/+-*/+-*/+-*/+-*/setAttributeNode m
setAttributeNode(newAttr)
Add a new attribute node to the element, replacing an existing attribute if
necessary if the :attr:`name` attribute matches. If a replacement occurs, the
old attribute node will be returned. If *newAttr* is already in use,
:exc:`InuseAttributeErr` will be raised.
+-*/+-*/+-*/+-*/+-*/getAttributeNS m
getAttributeNS(namespaceURI, localName)
Return the value of the attribute named by *namespaceURI* and *localName* as a
string. If no such attribute exists, an empty string is returned, as if the
attribute had no value.
+-*/+-*/+-*/+-*/+-*/removeAttributeNode m
removeAttributeNode(oldAttr)
Remove and return *oldAttr* from the attribute list, if present. If *oldAttr* is
not present, :exc:`NotFoundErr` is raised.
+-*/+-*/+-*/+-*/NamedNodeMap c 节点列表对象
+-*/+-*/+-*/+-*/+-*/length d
+-*/+-*/+-*/+-*/+-*/item m
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 :attr:`value` attribute.
+-*/+-*/+-*/+-*/DocumentType _
+-*/+-*/+-*/+-*/+-*/publicId d
publicId
The public identifier for the external subset of the document type definition.
This will be a string or ``None``.
+-*/+-*/+-*/+-*/+-*/name d
name
The name of the root element as given in the ``DOCTYPE`` declaration, if
present.
+-*/+-*/+-*/+-*/+-*/notations d
notations
This is a :class:`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.
+-*/+-*/+-*/+-*/+-*/entities d
entities
This is a :class:`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.
+-*/+-*/+-*/+-*/+-*/internalSubset d
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``.
+-*/+-*/+-*/+-*/+-*/systemId d
systemId
The system identifier for the external subset of the document type definition.
This will be a URI as a string, or ``None``.
+-*/+-*/+-*/+-*/DOMImplementation _
+-*/+-*/+-*/+-*/+-*/hasFeature m
hasFeature(feature, version)
Return true if the feature identified by the pair of strings *feature* and
*version* is implemented.
+-*/+-*/+-*/+-*/+-*/createDocument m
createDocument(namespaceUri, qualifiedName, doctype)
Return a new :class:`Document` object (the root of the DOM), with a child
:class:`Element` object having the given *namespaceUri* and *qualifiedName*. The
*doctype* must be a :class:`DocumentType` object created by
:meth:`createDocumentType`, or ``None``. In the Python DOM API, the first two
arguments can also be ``None`` in order to indicate that no :class:`Element`
child is to be created.
+-*/+-*/+-*/+-*/+-*/createDocumentType m
createDocumentType(qualifiedName, publicId, systemId)
Return a new :class:`DocumentType` object that encapsulates the given
*qualifiedName*, *publicId*, and *systemId* strings, representing the
information contained in an XML document type declaration.
+-*/+-*/+-*/+-*/minidom p Lightweight Document Object Model (DOM) implementation.
+-*/+-*/+-*/+-*/+-*/parse f
parse(filename_or_file, parser=None, bufsize=None)
Return a :class:`Document` from the given input. *filename_or_file* may be
either a file name, or a file-like object. *parser*, if given, must be a SAX2
parser object. This function will change the document handler of the parser and
activate namespace support; other parser configuration (like setting an entity
resolver) must have been done in advance.
+-*/+-*/+-*/+-*/+-*/parseString f
parseString(string, parser=None)
Return a :class:`Document` that represents the *string*. This method creates a
:class:`StringIO` object for the string and passes that on to :func:`parse`.
+-*/+-*/+-*/+-*/+-*/Node _
+-*/+-*/+-*/+-*/+-*/+-*/unlink m
unlink()
Break internal references within the DOM so that it will be garbage collected on
versions of Python without cyclic GC. Even when cyclic GC is available, using
this can make large amounts of memory available sooner, so calling this on DOM
objects as soon as they are no longer needed is good practice. This only needs
to be called on the :class:`Document` object, but may be called on child nodes
to discard children of that node.
You can avoid calling this method explicitly by using the :keyword:`with`
statement. The following code will automatically unlink *dom* when the
:keyword:`with` block is exited::
with xml.dom.minidom.parse(datasource) as dom:
... # Work with dom.
+-*/+-*/+-*/+-*/+-*/+-*/writexml m
writexml(writer, indent="", addindent="", newl="")
Write XML to the writer object. The writer should have a :meth:`write` method
which matches that of the file object interface. The *indent* parameter is the
indentation of the current node. The *addindent* parameter is the incremental
indentation to use for subnodes of the current one. The *newl* parameter
specifies the string to use to terminate newlines.
For the :class:`Document` node, an additional keyword argument *encoding* can
be used to specify the encoding field of the XML header.
+-*/+-*/+-*/+-*/+-*/+-*/toprettyxml m
toprettyxml(indent="", newl="", encoding="")
Return a pretty-printed version of the document. *indent* specifies the
indentation string and defaults to a tabulator; *newl* specifies the string
emitted at the end of each line and defaults to ``\n``.
The *encoding* argument behaves like the corresponding argument of
:meth:`toxml`.
+-*/+-*/+-*/+-*/+-*/+-*/toxml m
toxml(encoding=None)
Return a string or byte string containing the XML represented by
the DOM node.
With an explicit *encoding* [1]_ argument, the result is a byte
string in the specified encoding. It is recommended that you
always specify an encoding; you may use any encoding you like, but
an argument of "utf-8" is the most common choice, avoiding
:exc:`UnicodeError` exceptions in case of unrepresentable text
data.
With no *encoding* argument, the result is a Unicode string, and the
XML declaration in the resulting string does not specify an
encoding. Encoding this string in an encoding other than UTF-8 is
likely incorrect, since UTF-8 is the default encoding of XML.
+-*/+-*/+-*/etree p
+-*/+-*/+-*/+-*/ElementTree p Implementation of the ElementTree API.
+-*/+-*/+-*/+-*/+-*/Comment f
Comment(text=None)
Comment element factory. This factory function creates a special element
that will be serialized as an XML comment by the standard serializer. The
comment string can be either a bytestring or a Unicode string. *text* is a
string containing the comment string. Returns an element instance
representing a comment.
+-*/+-*/+-*/+-*/+-*/register_namespace f
register_namespace(prefix, uri)
Registers a namespace prefix. The registry is global, and any existing
mapping for either the given prefix or the namespace URI will be removed.
*prefix* is a namespace prefix. *uri* is a namespace uri. Tags and
attributes in this namespace will be serialized with the given prefix, if at
all possible.
.. versionadded:: 3.2
+-*/+-*/+-*/+-*/+-*/ProcessingInstruction f
ProcessingInstruction(target, text=None)
PI element factory. This factory function creates a special element that
will be serialized as an XML processing instruction. *target* is a string
containing the PI target. *text* is a string containing the PI contents, if
given. Returns an element instance, representing a processing instruction.
+-*/+-*/+-*/+-*/+-*/dump f
dump(elem)
Writes an element tree or element structure to sys.stdout. This function
should be used for debugging only.
The exact output format is implementation dependent. In this version, it's
written as an ordinary XML file.
*elem* is an element tree or an individual element.
+-*/+-*/+-*/+-*/+-*/XMLID f
XMLID(text, parser=None)
Parses an XML section from a string constant, and also returns a dictionary
which maps from element id:s to elements. *text* is a string containing XML
data. *parser* is an optional parser instance. If not given, the standard
:class:`XMLParser` parser is used. Returns a tuple containing an
:class:`Element` instance and a dictionary.
+-*/+-*/+-*/+-*/+-*/tostringlist f
tostringlist(element, encoding="us-ascii", method="xml")
Generates a string representation of an XML element, including all
subelements. *element* is an :class:`Element` instance. *encoding* [1]_ is
the output encoding (default is US-ASCII). Use ``encoding="unicode"`` to
generate a Unicode string. *method* is either ``"xml"``,
``"html"`` or ``"text"`` (default is ``"xml"``). Returns a list of
(optionally) encoded strings containing the XML data. It does not guarantee
any specific sequence, except that ``"".join(tostringlist(element)) ==
tostring(element)``.
.. versionadded:: 3.2
+-*/+-*/+-*/+-*/+-*/fromstring f
fromstring(text)
Parses an XML section from a string constant. Same as :func:`XML`. *text*
is a string containing XML data. Returns an :class:`Element` instance.
+-*/+-*/+-*/+-*/+-*/parse f
parse(source, parser=None)
Parses an XML section into an element tree. *source* is a filename or file
object containing XML data. *parser* is an optional parser instance. If
not given, the standard :class:`XMLParser` parser is used. Returns an
:class:`ElementTree` instance.
+-*/+-*/+-*/+-*/+-*/iterparse f
iterparse(source, events=None, parser=None)
Parses an XML section into an element tree incrementally, and reports what's
going on to the user. *source* is a filename or :term:`file object` containing
XML data. *events* is a list of events to report back. If omitted, only "end"
events are reported. *parser* is an optional parser instance. If not
given, the standard :class:`XMLParser` parser is used. Returns an
:term:`iterator` providing ``(event, elem)`` pairs.
.. note::
:func:`iterparse` only guarantees that it has seen the ">"
character of a starting tag when it emits a "start" event, so the
attributes are defined, but the contents of the text and tail attributes
are undefined at that point. The same applies to the element children;
they may or may not be present.
If you need a fully populated element, look for "end" events instead.
+-*/+-*/+-*/+-*/+-*/SubElement f
SubElement(parent, tag, attrib={}, **extra)
Subelement factory. This function creates an element instance, and appends
it to an existing element.
The element name, attribute names, and attribute values can be either
bytestrings or Unicode strings. *parent* is the parent element. *tag* is
the subelement name. *attrib* is an optional dictionary, containing element
attributes. *extra* contains additional attributes, given as keyword
arguments. Returns an element instance.
+-*/+-*/+-*/+-*/+-*/XML f
XML(text, parser=None)
Parses an XML section from a string constant. This function can be used to
embed "XML literals" in Python code. *text* is a string containing XML
data. *parser* is an optional parser instance. If not given, the standard
:class:`XMLParser` parser is used. Returns an :class:`Element` instance.
+-*/+-*/+-*/+-*/+-*/fromstringlist f
fromstringlist(sequence, parser=None)
Parses an XML document from a sequence of string fragments. *sequence* is a
list or other sequence containing XML data fragments. *parser* is an
optional parser instance. If not given, the standard :class:`XMLParser`
parser is used. Returns an :class:`Element` instance.
.. versionadded:: 3.2
+-*/+-*/+-*/+-*/+-*/iselement f
iselement(element)
Checks if an object appears to be a valid element object. *element* is an
element instance. Returns a true value if this is an element object.
+-*/+-*/+-*/+-*/+-*/tostring f
tostring(element, encoding="us-ascii", method="xml")
Generates a string representation of an XML element, including all
subelements. *element* is an :class:`Element` instance. *encoding* [1]_ is
the output encoding (default is US-ASCII). Use ``encoding="unicode"`` to
generate a Unicode string. *method* is either ``"xml"``,
``"html"`` or ``"text"`` (default is ``"xml"``). Returns an (optionally)
encoded string containing the XML data.
+-*/+-*/+-*/+-*/+-*/ElementTree c
ElementTree(element=None, file=None)
ElementTree wrapper class. This class represents an entire element
hierarchy, and adds some extra support for serialization to and from
standard XML.
*element* is the root element. The tree is initialized with the contents
of the XML *file* if given.
+-*/+-*/+-*/+-*/+-*/+-*/write m
write(file, encoding="us-ascii", xml_declaration=None, method="xml")
Writes the element tree to a file, as XML. *file* is a file name, or a
:term:`file object` opened for writing. *encoding* [1]_ is the output encoding
(default is US-ASCII). Use ``encoding="unicode"`` to write a Unicode string.
*xml_declaration* controls if an XML declaration
should be added to the file. Use False for never, True for always, None
for only if not US-ASCII or UTF-8 or Unicode (default is None). *method* is
either ``"xml"``, ``"html"`` or ``"text"`` (default is ``"xml"``).
Returns an (optionally) encoded string.
+-*/+-*/+-*/+-*/+-*/+-*/getroot m
getroot()
Returns the root element for this tree.
+-*/+-*/+-*/+-*/+-*/+-*/getiterator m
getiterator(tag=None)
.. deprecated:: 3.2
Use method :meth:`ElementTree.iter` instead.
+-*/+-*/+-*/+-*/+-*/+-*/iterfind m
iterfind(match)
Finds all matching subelements, by tag name or path. Same as
getroot().iterfind(match). Returns an iterable yielding all matching
elements in document order.
.. versionadded:: 3.2
+-*/+-*/+-*/+-*/+-*/+-*/findtext m
findtext(match, default=None)
Finds the element text for the first toplevel element with given tag.
Same as getroot().findtext(match). *match* may be a tag name or path.
*default* is the value to return if the element was not found. Returns
the text content of the first matching element, or the default value no
element was found. Note that if the element is found, but has no text
content, this method returns an empty string.
+-*/+-*/+-*/+-*/+-*/+-*/iter m
iter(tag=None)
Creates and returns a tree iterator for the root element. The iterator
loops over all elements in this tree, in section order. *tag* is the tag
to look for (default is to return all elements)
+-*/+-*/+-*/+-*/+-*/+-*/find m
find(match)
Finds the first toplevel element matching *match*. *match* may be a tag
name or path. Same as getroot().find(match). Returns the first matching
element, or ``None`` if no element was found.
+-*/+-*/+-*/+-*/+-*/+-*/parse m
parse(source, parser=None)
Loads an external XML section into this element tree. *source* is a file
name or :term:`file object`. *parser* is an optional parser instance.
If not given, the standard XMLParser parser is used. Returns the section
root element.
+-*/+-*/+-*/+-*/+-*/+-*/_setroot m
_setroot(element)
Replaces the root element for this tree. This discards the current
contents of the tree, and replaces it with the given element. Use with
care. *element* is an element instance.
+-*/+-*/+-*/+-*/+-*/+-*/findall m
findall(match)
Finds all matching subelements, by tag name or path. Same as
getroot().findall(match). *match* may be a tag name or path. Returns a
list containing all matching elements, in document order.
+-*/+-*/+-*/+-*/+-*/XMLParser c
XMLParser(html=0, target=None, encoding=None)
:class:`Element` structure builder for XML source data, based on the expat
parser. *html* are predefined HTML entities. This flag is not supported by
the current implementation. *target* is the target object. If omitted, the
builder uses an instance of the standard TreeBuilder class. *encoding* [1]_
is optional. If given, the value overrides the encoding specified in the
XML file.
+-*/+-*/+-*/+-*/+-*/+-*/feed m
feed(data)
Feeds data to the parser. *data* is encoded data.
+-*/+-*/+-*/+-*/+-*/+-*/close m
close()
Finishes feeding data to the parser. Returns an element structure.
+-*/+-*/+-*/+-*/+-*/+-*/doctype m
doctype(name, pubid, system)
.. deprecated:: 3.2
Define the :meth:`TreeBuilder.doctype` method on a custom TreeBuilder
target.
+-*/+-*/+-*/+-*/+-*/QName c
QName(text_or_uri, tag=None)
QName wrapper. This can be used to wrap a QName attribute value, in order
to get proper namespace handling on output. *text_or_uri* is a string
containing the QName value, in the form {uri}local, or, if the tag argument
is given, the URI part of a QName. If *tag* is given, the first argument is
interpreted as an URI, and this argument is interpreted as a local name.
:class:`QName` instances are opaque.
+-*/+-*/+-*/+-*/+-*/TreeBuilder c
TreeBuilder(element_factory=None)
Generic element structure builder. This builder converts a sequence of
start, data, and end method calls to a well-formed element structure. You
can use this class to build an element structure using a custom XML parser,
or a parser for some other XML-like format. The *element_factory* is called
to create new :class:`Element` instances when given.
+-*/+-*/+-*/+-*/+-*/+-*/close m
close()
Flushes the builder buffers, and returns the toplevel document
element. Returns an :class:`Element` instance.
+-*/+-*/+-*/+-*/+-*/+-*/end m
end(tag)
Closes the current element. *tag* is the element name. Returns the
closed element.
+-*/+-*/+-*/+-*/+-*/+-*/doctype m
doctype(name, pubid, system)
Handles a doctype declaration. *name* is the doctype name. *pubid* is
the public identifier. *system* is the system identifier. This method
does not exist on the default :class:`TreeBuilder` class.
.. versionadded:: 3.2
+-*/+-*/+-*/+-*/+-*/+-*/data m
data(data)
Adds text to the current element. *data* is a string. This should be
either a bytestring, or a Unicode string.
+-*/+-*/+-*/+-*/+-*/+-*/start m
start(tag, attrs)
Opens a new element. *tag* is the element name. *attrs* is a dictionary
containing element attributes. Returns the opened element.
+-*/+-*/+-*/+-*/+-*/Element c
Element(tag, attrib={}, **extra)
Element class. This class defines the Element interface, and provides a
reference implementation of this interface.
The element name, attribute names, and attribute values can be either
bytestrings or Unicode strings. *tag* is the element name. *attrib* is
an optional dictionary, containing element attributes. *extra* contains
additional attributes, given as keyword arguments.
+-*/+-*/+-*/+-*/+-*/+-*/text d
text
The *text* attribute can be used to hold additional data associated with
the element. As the name implies this attribute is usually a string but
may be any application-specific object. If the element is created from
an XML file the attribute will contain any text found between the element
tags.
+-*/+-*/+-*/+-*/+-*/+-*/tail d
tail
The *tail* attribute can be used to hold additional data associated with
the element. This attribute is usually a string but may be any
application-specific object. If the element is created from an XML file
the attribute will contain any text found after the element's end tag and
before the next tag.
+-*/+-*/+-*/+-*/+-*/+-*/tag d
tag
A string identifying what kind of data this element represents (the
element type, in other words).
+-*/+-*/+-*/+-*/+-*/+-*/attrib d
attrib
A dictionary containing the element's attributes. Note that while the
*attrib* value is always a real mutable Python dictionary, an ElementTree
implementation may choose to use another internal representation, and
create the dictionary only if someone asks for it. To take advantage of
such implementations, use the dictionary methods below whenever possible.
+-*/+-*/+-*/+-*/+-*/+-*/insert m
insert(index, element)
Inserts a subelement at the given position in this element.
+-*/+-*/+-*/+-*/+-*/+-*/set m
set(key, value)
Set the attribute *key* on the element to *value*.
+-*/+-*/+-*/+-*/+-*/+-*/extend m
extend(subelements)
Appends *subelements* from a sequence object with zero or more elements.
Raises :exc:`AssertionError` if a subelement is not a valid object.
.. versionadded:: 3.2
+-*/+-*/+-*/+-*/+-*/+-*/get m
get(key, default=None)
Gets the element attribute named *key*.
Returns the attribute value, or *default* if the attribute was not found.
+-*/+-*/+-*/+-*/+-*/+-*/keys m
keys()
Returns the elements attribute names as a list. The names are returned
in an arbitrary order.
+-*/+-*/+-*/+-*/+-*/+-*/items m
items()
Returns the element attributes as a sequence of (name, value) pairs. The
attributes are returned in an arbitrary order.
+-*/+-*/+-*/+-*/+-*/+-*/clear m
clear()
Resets an element. This function removes all subelements, clears all
attributes, and sets the text and tail attributes to None.
+-*/+-*/+-*/+-*/+-*/+-*/iterfind m
iterfind(match)
Finds all matching subelements, by tag name or path. Returns an iterable
yielding all matching elements in document order.
.. versionadded:: 3.2
+-*/+-*/+-*/+-*/+-*/+-*/findtext m
findtext(match, default=None)
Finds text for the first subelement matching *match*. *match* may be
a tag name or path. Returns the text content of the first matching
element, or *default* if no element was found. Note that if the matching
element has no text content an empty string is returned.
+-*/+-*/+-*/+-*/+-*/+-*/makeelement m
makeelement(tag, attrib)
Creates a new element object of the same type as this element. Do not
call this method, use the :func:`SubElement` factory function instead.
+-*/+-*/+-*/+-*/+-*/+-*/iter m
iter(tag=None)
Creates a tree :term:`iterator` with the current element as the root.
The iterator iterates over this element and all elements below it, in
document (depth first) order. If *tag* is not ``None`` or ``'*'``, only
elements whose tag equals *tag* are returned from the iterator. If the
tree structure is modified during iteration, the result is undefined.
+-*/+-*/+-*/+-*/+-*/+-*/find m
find(match)
Finds the first subelement matching *match*. *match* may be a tag name
or path. Returns an element instance or ``None``.
+-*/+-*/+-*/+-*/+-*/+-*/itertext m
itertext()
Creates a text iterator. The iterator loops over this element and all
subelements, in document order, and returns all inner text.
.. versionadded:: 3.2
+-*/+-*/+-*/+-*/+-*/+-*/getchildren m
getchildren()
.. deprecated:: 3.2
Use ``list(elem)`` or iteration.
+-*/+-*/+-*/+-*/+-*/+-*/remove m
remove(subelement)
Removes *subelement* from the element. Unlike the find\* methods this
method compares elements based on the instance identity, not on tag value
or contents.
+-*/+-*/+-*/+-*/+-*/+-*/getiterator m
getiterator(tag=None)
.. deprecated:: 3.2
Use method :meth:`Element.iter` instead.
+-*/+-*/+-*/+-*/+-*/+-*/findall m
findall(match)
Finds all matching subelements, by tag name or path. Returns a list
containing all matching elements in document order.
+-*/+-*/+-*/+-*/+-*/+-*/append m
append(subelement)
Adds the element *subelement* to the end of this elements internal list
of subelements.
+-*/+-*/+-*/parsers p
+-*/+-*/+-*/+-*/expat p An interface to the Expat non-validating XML parser.
+-*/+-*/+-*/+-*/+-*/ParserCreate f
ParserCreate(encoding=None, namespace_separator=None)
Creates and returns a new :class:`xmlparser` object. *encoding*, if specified,
must be a string naming the encoding used by the XML data. Expat doesn't
support as many encodings as Python does, and its repertoire of encodings can't
be extended; it supports UTF-8, UTF-16, ISO-8859-1 (Latin1), and ASCII. If
*encoding* [1]_ is given it will override the implicit or explicit encoding of the
document.
Expat can optionally do XML namespace processing for you, enabled by providing a
value for *namespace_separator*. The value must be a one-character string; a
:exc:`ValueError` will be raised if the string has an illegal length (``None``
is considered the same as omission). When namespace processing is enabled,
element type names and attribute names that belong to a namespace will be
expanded. The element name passed to the element handlers
:attr:`StartElementHandler` and :attr:`EndElementHandler` will be the
concatenation of the namespace URI, the namespace separator character, and the
local part of the name. If the namespace separator is a zero byte (``chr(0)``)
then the namespace URI and the local part will be concatenated without any
separator.
For example, if *namespace_separator* is set to a space character (``' '``) and
the following document is parsed::
<?xml version="1.0"?>
<root xmlns = "http://default-namespace.org/"
xmlns:py = "http://www.python.org/ns/">
<py:elem1 />
<elem2 xmlns="" />
</root>
:attr:`StartElementHandler` will receive the following strings for each
element::
http://default-namespace.org/ root
http://www.python.org/ns/ elem1
elem2
+-*/+-*/+-*/+-*/+-*/ErrorString f
ErrorString(errno)
Returns an explanatory string for a given error number *errno*.
+-*/+-*/+-*/+-*/+-*/XMLParserType d
XMLParserType
The type of the return values from the :func:`ParserCreate` function.
+-*/+-*/+-*/+-*/+-*/error e
error
Alias for :exc:`ExpatError`.
+-*/+-*/+-*/+-*/+-*/ExpatError e
ExpatError
The exception raised when Expat reports an error. See section
:ref:`expaterror-objects` for more information on interpreting Expat errors.
+-*/+-*/+-*/+-*/+-*/xmlparser _
+-*/+-*/+-*/+-*/+-*/+-*/CurrentColumnNumber d
CurrentColumnNumber
Current column number in the parser input.
+-*/+-*/+-*/+-*/+-*/+-*/CurrentLineNumber d
CurrentLineNumber
Current line number in the parser input.
+-*/+-*/+-*/+-*/+-*/+-*/CurrentByteIndex d
CurrentByteIndex
Current byte index in the parser input.
+-*/+-*/+-*/+-*/+-*/+-*/buffer_used d
buffer_used
If :attr:`buffer_text` is enabled, the number of bytes stored in the buffer.
These bytes represent UTF-8 encoded text. This attribute has no meaningful
interpretation when :attr:`buffer_text` is false.
+-*/+-*/+-*/+-*/+-*/+-*/ordered_attributes d
ordered_attributes
Setting this attribute to a non-zero integer causes the attributes to be
reported as a list rather than a dictionary. The attributes are presented in
the order found in the document text. For each attribute, two list entries are
presented: the attribute name and the attribute value. (Older versions of this
module also used this format.) By default, this attribute is false; it may be
changed at any time.
+-*/+-*/+-*/+-*/+-*/+-*/ErrorCode d
ErrorCode
Numeric code specifying the problem. This value can be passed to the
:func:`ErrorString` function, or compared to one of the constants defined in the
``errors`` object.
+-*/+-*/+-*/+-*/+-*/+-*/specified_attributes d
specified_attributes
If set to a non-zero integer, the parser will report only those attributes which
were specified in the document instance and not those which were derived from
attribute declarations. Applications which set this need to be especially
careful to use what additional information is available from the declarations as
needed to comply with the standards for the behavior of XML processors. By
default, this attribute is false; it may be changed at any time.
+-*/+-*/+-*/+-*/+-*/+-*/buffer_text d
buffer_text
Setting this to true causes the :class:`xmlparser` object to buffer textual
content returned by Expat to avoid multiple calls to the
:meth:`CharacterDataHandler` callback whenever possible. This can improve
performance substantially since Expat normally breaks character data into chunks
at every line ending. This attribute is false by default, and may be changed at
any time.
+-*/+-*/+-*/+-*/+-*/+-*/ErrorByteIndex d
ErrorByteIndex
Byte index at which an error occurred.
+-*/+-*/+-*/+-*/+-*/+-*/buffer_size d
buffer_size
The size of the buffer used when :attr:`buffer_text` is true.
A new buffer size can be set by assigning a new integer value
to this attribute.
When the size is changed, the buffer will be flushed.
+-*/+-*/+-*/+-*/+-*/+-*/ErrorColumnNumber d
ErrorColumnNumber
Column number at which an error occurred.
+-*/+-*/+-*/+-*/+-*/+-*/ErrorLineNumber d
ErrorLineNumber
Line number at which an error occurred.
+-*/+-*/+-*/+-*/+-*/+-*/UnparsedEntityDeclHandler m
UnparsedEntityDeclHandler(entityName, base, systemId, publicId, notationName)
Called for unparsed (NDATA) entity declarations. This is only present for
version 1.2 of the Expat library; for more recent versions, use
:attr:`EntityDeclHandler` instead. (The underlying function in the Expat
library has been declared obsolete.)
+-*/+-*/+-*/+-*/+-*/+-*/StartCdataSectionHandler m
StartCdataSectionHandler()
Called at the start of a CDATA section. This and :attr:`EndCdataSectionHandler`
are needed to be able to identify the syntactical start and end for CDATA
sections.
+-*/+-*/+-*/+-*/+-*/+-*/EndElementHandler m
EndElementHandler(name)
Called for the end of every element.
+-*/+-*/+-*/+-*/+-*/+-*/GetInputContext m
GetInputContext()
Returns the input data that generated the current event as a string. The data is
in the encoding of the entity which contains the text. When called while an
event handler is not active, the return value is ``None``.
+-*/+-*/+-*/+-*/+-*/+-*/ExternalEntityParserCreate m
ExternalEntityParserCreate(context[, encoding])
Create a "child" parser which can be used to parse an external parsed entity
referred to by content parsed by the parent parser. The *context* parameter
should be the string passed to the :meth:`ExternalEntityRefHandler` handler
function, described below. The child parser is created with the
:attr:`ordered_attributes` and :attr:`specified_attributes` set to the values of
this parser.
+-*/+-*/+-*/+-*/+-*/+-*/UseForeignDTD m
UseForeignDTD([flag])
Calling this with a true value for *flag* (the default) will cause Expat to call
the :attr:`ExternalEntityRefHandler` with :const:`None` for all arguments to
allow an alternate DTD to be loaded. If the document does not contain a
document type declaration, the :attr:`ExternalEntityRefHandler` will still be
called, but the :attr:`StartDoctypeDeclHandler` and
:attr:`EndDoctypeDeclHandler` will not be called.
Passing a false value for *flag* will cancel a previous call that passed a true
value, but otherwise has no effect.
This method can only be called before the :meth:`Parse` or :meth:`ParseFile`
methods are called; calling it after either of those have been called causes
:exc:`ExpatError` to be raised with the :attr:`code` attribute set to
``errors.codes[errors.XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING]``.
+-*/+-*/+-*/+-*/+-*/+-*/EndCdataSectionHandler m
EndCdataSectionHandler()
Called at the end of a CDATA section.
+-*/+-*/+-*/+-*/+-*/+-*/ExternalEntityRefHandler m
ExternalEntityRefHandler(context, base, systemId, publicId)
Called for references to external entities. *base* is the current base, as set
by a previous call to :meth:`SetBase`. The public and system identifiers,
*systemId* and *publicId*, are strings if given; if the public identifier is not
given, *publicId* will be ``None``. The *context* value is opaque and should
only be used as described below.
For external entities to be parsed, this handler must be implemented. It is
responsible for creating the sub-parser using
``ExternalEntityParserCreate(context)``, initializing it with the appropriate
callbacks, and parsing the entity. This handler should return an integer; if it
returns ``0``, the parser will raise an
:const:`XML_ERROR_EXTERNAL_ENTITY_HANDLING` error, otherwise parsing will
continue.
If this handler is not provided, external entities are reported by the
:attr:`DefaultHandler` callback, if provided.
+-*/+-*/+-*/+-*/+-*/+-*/EndNamespaceDeclHandler m
EndNamespaceDeclHandler(prefix)
Called when the closing tag is reached for an element that contained a
namespace declaration. This is called once for each namespace declaration on
the element in the reverse of the order for which the
:attr:`StartNamespaceDeclHandler` was called to indicate the start of each
namespace declaration's scope. Calls to this handler are made after the
corresponding :attr:`EndElementHandler` for the end of the element.
+-*/+-*/+-*/+-*/+-*/+-*/NotationDeclHandler m
NotationDeclHandler(notationName, base, systemId, publicId)
Called for notation declarations. *notationName*, *base*, and *systemId*, and
*publicId* are strings if given. If the public identifier is omitted,
*publicId* will be ``None``.
+-*/+-*/+-*/+-*/+-*/+-*/StartDoctypeDeclHandler m
StartDoctypeDeclHandler(doctypeName, systemId, publicId, has_internal_subset)
Called when Expat begins parsing the document type declaration (``<!DOCTYPE
...``). The *doctypeName* is provided exactly as presented. The *systemId* and
*publicId* parameters give the system and public identifiers if specified, or
``None`` if omitted. *has_internal_subset* will be true if the document
contains and internal document declaration subset. This requires Expat version
1.2 or newer.
+-*/+-*/+-*/+-*/+-*/+-*/GetBase m
GetBase()
Returns a string containing the base set by a previous call to :meth:`SetBase`,
or ``None`` if :meth:`SetBase` hasn't been called.
+-*/+-*/+-*/+-*/+-*/+-*/DefaultHandler m
DefaultHandler(data)
Called for any characters in the XML document for which no applicable handler
has been specified. This means characters that are part of a construct which
could be reported, but for which no handler has been supplied.
+-*/+-*/+-*/+-*/+-*/+-*/ProcessingInstructionHandler m
ProcessingInstructionHandler(target, data)
Called for every processing instruction.
+-*/+-*/+-*/+-*/+-*/+-*/XmlDeclHandler m
XmlDeclHandler(version, encoding, standalone)
Called when the XML declaration is parsed. The XML declaration is the
(optional) declaration of the applicable version of the XML recommendation, the
encoding of the document text, and an optional "standalone" declaration.
*version* and *encoding* will be strings, and *standalone* will be ``1`` if the
document is declared standalone, ``0`` if it is declared not to be standalone,
or ``-1`` if the standalone clause was omitted. This is only available with
Expat version 1.95.0 or newer.
+-*/+-*/+-*/+-*/+-*/+-*/CommentHandler m
CommentHandler(data)
Called for comments. *data* is the text of the comment, excluding the leading
'``<!-``\ ``-``' and trailing '``-``\ ``->``'.
+-*/+-*/+-*/+-*/+-*/+-*/EntityDeclHandler m
EntityDeclHandler(entityName, is_parameter_entity, value, base, systemId, publicId, notationName)
Called for all entity declarations. For parameter and internal entities,
*value* will be a string giving the declared contents of the entity; this will
be ``None`` for external entities. The *notationName* parameter will be
``None`` for parsed entities, and the name of the notation for unparsed
entities. *is_parameter_entity* will be true if the entity is a parameter entity
or false for general entities (most applications only need to be concerned with
general entities). This is only available starting with version 1.95.0 of the
Expat library.
+-*/+-*/+-*/+-*/+-*/+-*/SetBase m
SetBase(base)
Sets the base to be used for resolving relative URIs in system identifiers in
declarations. Resolving relative identifiers is left to the application: this
value will be passed through as the *base* argument to the
:func:`ExternalEntityRefHandler`, :func:`NotationDeclHandler`, and
:func:`UnparsedEntityDeclHandler` functions.
+-*/+-*/+-*/+-*/+-*/+-*/NotStandaloneHandler m
NotStandaloneHandler()
Called if the XML document hasn't been declared as being a standalone document.
This happens when there is an external subset or a reference to a parameter
entity, but the XML declaration does not set standalone to ``yes`` in an XML
declaration. If this handler returns ``0``, then the parser will raise an
:const:`XML_ERROR_NOT_STANDALONE` error. If this handler is not set, no
exception is raised by the parser for this condition.
+-*/+-*/+-*/+-*/+-*/+-*/SetParamEntityParsing m
SetParamEntityParsing(flag)
Control parsing of parameter entities (including the external DTD subset).
Possible *flag* values are :const:`XML_PARAM_ENTITY_PARSING_NEVER`,
:const:`XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE` and
:const:`XML_PARAM_ENTITY_PARSING_ALWAYS`. Return true if setting the flag
was successful.
+-*/+-*/+-*/+-*/+-*/+-*/EndDoctypeDeclHandler m
EndDoctypeDeclHandler()
Called when Expat is done parsing the document type declaration. This requires
Expat version 1.2 or newer.
+-*/+-*/+-*/+-*/+-*/+-*/StartNamespaceDeclHandler m
StartNamespaceDeclHandler(prefix, uri)
Called when an element contains a namespace declaration. Namespace declarations
are processed before the :attr:`StartElementHandler` is called for the element
on which declarations are placed.
+-*/+-*/+-*/+-*/+-*/+-*/Parse m
Parse(data[, isfinal])
Parses the contents of the string *data*, calling the appropriate handler
functions to process the parsed data. *isfinal* must be true on the final call
to this method. *data* can be the empty string at any time.
+-*/+-*/+-*/+-*/+-*/+-*/ParseFile m
ParseFile(file)
Parse XML data reading from the object *file*. *file* only needs to provide
the ``read(nbytes)`` method, returning the empty string when there's no more
data.
+-*/+-*/+-*/+-*/+-*/+-*/DefaultHandlerExpand m
DefaultHandlerExpand(data)
This is the same as the :func:`DefaultHandler`, but doesn't inhibit expansion
of internal entities. The entity reference will not be passed to the default
handler.
+-*/+-*/+-*/+-*/+-*/+-*/AttlistDeclHandler m
AttlistDeclHandler(elname, attname, type, default, required)
Called for each declared attribute for an element type. If an attribute list
declaration declares three attributes, this handler is called three times, once
for each attribute. *elname* is the name of the element to which the
declaration applies and *attname* is the name of the attribute declared. The
attribute type is a string passed as *type*; the possible values are
``'CDATA'``, ``'ID'``, ``'IDREF'``, ... *default* gives the default value for
the attribute used when the attribute is not specified by the document instance,
or ``None`` if there is no default value (``#IMPLIED`` values). If the
attribute is required to be given in the document instance, *required* will be
true. This requires Expat version 1.95.0 or newer.
+-*/+-*/+-*/+-*/+-*/+-*/ElementDeclHandler m
ElementDeclHandler(name, model)
Called once for each element type declaration. *name* is the name of the
element type, and *model* is a representation of the content model.
+-*/+-*/+-*/+-*/+-*/+-*/StartElementHandler m
StartElementHandler(name, attributes)
Called for the start of every element. *name* is a string containing the
element name, and *attributes* is a dictionary mapping attribute names to their
values.
+-*/+-*/+-*/+-*/+-*/+-*/CharacterDataHandler m
CharacterDataHandler(data)
Called for character data. This will be called for normal character data, CDATA
marked content, and ignorable whitespace. Applications which must distinguish
these cases can use the :attr:`StartCdataSectionHandler`,
:attr:`EndCdataSectionHandler`, and :attr:`ElementDeclHandler` callbacks to
collect the required information.
+-*/+-*/+-*/+-*/+-*/ExpatError _
+-*/+-*/+-*/+-*/+-*/+-*/code d
code
Expat's internal error number for the specific error. The
:data:`errors.messages` dictionary maps these error numbers to Expat's error
messages. For example::
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])
The :mod:`errors` module also provides error message constants and a
dictionary :data:`~errors.codes` mapping these messages back to the error
codes, see below.
+-*/+-*/+-*/+-*/+-*/+-*/lineno d
lineno
Line number on which the error was detected. The first line is numbered ``1``.
+-*/+-*/+-*/+-*/+-*/+-*/offset d
offset
Character offset into the line where the error occurred. The first column is
numbered ``0``.
+-*/+-*/+-*/+-*/+-*/errors p
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_SUSPENDED d
XML_ERROR_SUSPENDED
The requested operation was made on a suspended parser, but isn't allowed. This
includes attempts to provide additional input or to stop the parser.
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_BINARY_ENTITY_REF d
XML_ERROR_BINARY_ENTITY_REF
An entity reference referred to an entity which was declared with a notation, so
cannot be parsed.
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_ASYNC_ENTITY d
XML_ERROR_ASYNC_ENTITY
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_UNEXPECTED_STATE d
XML_ERROR_UNEXPECTED_STATE
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_NO_MEMORY d
XML_ERROR_NO_MEMORY
Expat was not able to allocate memory internally.
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF d
XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF
An entity reference in an attribute value referred to an external entity instead
of an internal entity.
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_DUPLICATE_ATTRIBUTE d
XML_ERROR_DUPLICATE_ATTRIBUTE
An attribute was used more than once in a start tag.
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_JUNK_AFTER_DOC_ELEMENT d
XML_ERROR_JUNK_AFTER_DOC_ELEMENT
Something other than whitespace occurred after the document element.
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_INVALID_TOKEN d
XML_ERROR_INVALID_TOKEN
Raised when an input byte could not properly be assigned to a character; for
example, a NUL byte (value ``0``) in a UTF-8 input stream.
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_NOT_SUSPENDED d
XML_ERROR_NOT_SUSPENDED
An attempt to resume the parser was made when the parser had not been suspended.
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_PARAM_ENTITY_REF d
XML_ERROR_PARAM_ENTITY_REF
A parameter entity reference was found where it was not allowed.
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_MISPLACED_XML_PI d
XML_ERROR_MISPLACED_XML_PI
An XML declaration was found somewhere other than the start of the input data.
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_NOT_STANDALONE d
XML_ERROR_NOT_STANDALONE
The parser determined that the document was not "standalone" though it declared
itself to be in the XML declaration, and the :attr:`NotStandaloneHandler` was
set and returned ``0``.
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_SYNTAX d
XML_ERROR_SYNTAX
Some unspecified syntax error was encountered.
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_ENTITY_DECLARED_IN_PE d
XML_ERROR_ENTITY_DECLARED_IN_PE
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_XML_DECL d
XML_ERROR_XML_DECL
The document contained no document element at all.
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_UNDECLARING_PREFIX d
XML_ERROR_UNDECLARING_PREFIX
The document attempted to remove the namespace declaration associated with a
prefix.
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_UNKNOWN_ENCODING d
XML_ERROR_UNKNOWN_ENCODING
The document encoding is not supported by Expat.
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_TAG_MISMATCH d
XML_ERROR_TAG_MISMATCH
An end tag did not match the innermost open start tag.
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_UNDEFINED_ENTITY d
XML_ERROR_UNDEFINED_ENTITY
A reference was made to a entity which was not defined.
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_BAD_CHAR_REF d
XML_ERROR_BAD_CHAR_REF
A character reference referred to a character which is illegal in XML (for
example, character ``0``, or '``&#0;``').
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_EXTERNAL_ENTITY_HANDLING d
XML_ERROR_EXTERNAL_ENTITY_HANDLING
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_UNCLOSED_TOKEN d
XML_ERROR_UNCLOSED_TOKEN
Some token (such as a start tag) was not closed before the end of the stream or
the next token was encountered.
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_ABORTED d
XML_ERROR_ABORTED
This should not be reported to Python applications.
+-*/+-*/+-*/+-*/+-*/+-*/codes d
codes
A dictionary mapping numeric error codes to their string descriptions.
.. versionadded:: 3.2
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_INCORRECT_ENCODING d
XML_ERROR_INCORRECT_ENCODING
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_FINISHED d
XML_ERROR_FINISHED
The requested operation was made on a parser which was finished parsing input,
but isn't allowed. This includes attempts to provide additional input or to
stop the parser.
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_RECURSIVE_ENTITY_REF d
XML_ERROR_RECURSIVE_ENTITY_REF
An entity reference contained another reference to the same entity; possibly via
a different name, and possibly indirectly.
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_FEATURE_REQUIRES_XML_DTD d
XML_ERROR_FEATURE_REQUIRES_XML_DTD
An operation was requested that requires DTD support to be compiled in, but
Expat was configured without DTD support. This should never be reported by a
standard build of the :mod:`xml.parsers.expat` module.
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_UNCLOSED_CDATA_SECTION d
XML_ERROR_UNCLOSED_CDATA_SECTION
A CDATA marked section was not closed.
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_NO_ELEMENTS d
XML_ERROR_NO_ELEMENTS
The document contains no elements (XML requires all documents to contain exactly
one top-level element)..
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_PUBLICID d
XML_ERROR_PUBLICID
Characters were found in the public id that are not allowed.
+-*/+-*/+-*/+-*/+-*/+-*/messages d
messages
A dictionary mapping string descriptions to their error codes.
.. versionadded:: 3.2
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_PARTIAL_CHAR d
XML_ERROR_PARTIAL_CHAR
An incomplete character was found in the input.
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING d
XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING
A behavioral change was requested after parsing started that can only be changed
before parsing has started. This is (currently) only raised by
:meth:`UseForeignDTD`.
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_SUSPEND_PE d
XML_ERROR_SUSPEND_PE
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_INCOMPLETE_PE d
XML_ERROR_INCOMPLETE_PE
A parameter entity contained incomplete markup.
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_TEXT_DECL d
XML_ERROR_TEXT_DECL
There was an error parsing a text declaration in an external entity.
+-*/+-*/+-*/+-*/+-*/+-*/XML_ERROR_UNBOUND_PREFIX d
XML_ERROR_UNBOUND_PREFIX
An undeclared prefix was found when namespace processing was enabled.
+-*/+-*/+-*/+-*/+-*/model p
+-*/+-*/+-*/+-*/+-*/+-*/XML_CQUANT_REP d
XML_CQUANT_REP
The model must occur zero or more times, as for ``A*``.
+-*/+-*/+-*/+-*/+-*/+-*/XML_CTYPE_NAME d
XML_CTYPE_NAME
+-*/+-*/+-*/+-*/+-*/+-*/XML_CQUANT_PLUS d
XML_CQUANT_PLUS
The model must occur one or more times (like ``A+``).
+-*/+-*/+-*/+-*/+-*/+-*/XML_CQUANT_NONE d
XML_CQUANT_NONE
No modifier is given, so it can appear exactly once, as for ``A``.
+-*/+-*/+-*/+-*/+-*/+-*/XML_CTYPE_MIXED d
XML_CTYPE_MIXED
+-*/+-*/+-*/+-*/+-*/+-*/XML_CTYPE_ANY d
XML_CTYPE_ANY
The element named by the model name was declared to have a content model of
``ANY``.
+-*/+-*/+-*/+-*/+-*/+-*/XML_CTYPE_EMPTY d
XML_CTYPE_EMPTY
Elements which are declared to be ``EMPTY`` have this model type.
+-*/+-*/+-*/+-*/+-*/+-*/XML_CQUANT_OPT d
XML_CQUANT_OPT
The model is optional: it can appear once or not at all, as for ``A?``.
+-*/+-*/+-*/+-*/+-*/+-*/XML_CTYPE_SEQ d
XML_CTYPE_SEQ
Models which represent a series of models which follow one after the other are
indicated with this model type. This is used for models such as ``(A, B, C)``.
+-*/+-*/+-*/+-*/+-*/+-*/XML_CTYPE_CHOICE d
XML_CTYPE_CHOICE
The named element allows a choice from a number of options; this is used for
content models such as ``(A | B | C)``.
+-*/+-*/+-*/sax p Package containing SAX2 base classes and convenience functions.
+-*/+-*/+-*/+-*/parse f
parse(filename_or_stream, handler, error_handler=handler.ErrorHandler())
Create a SAX parser and use it to parse a document. The document, passed in as
*filename_or_stream*, can be a filename or a file object. The *handler*
parameter needs to be a SAX :class:`ContentHandler` instance. If
*error_handler* is given, it must be a SAX :class:`ErrorHandler` instance; if
omitted, :exc:`SAXParseException` will be raised on all errors. There is no
return value; all work must be done by the *handler* passed in.
+-*/+-*/+-*/+-*/make_parser f
make_parser(parser_list=[])
Create and return a SAX :class:`XMLReader` object. The first parser found will
be used. If *parser_list* is provided, it must be a sequence of strings which
name modules that have a function named :func:`create_parser`. Modules listed
in *parser_list* will be used before modules in the default list of parsers.
+-*/+-*/+-*/+-*/parseString f
parseString(string, handler, error_handler=handler.ErrorHandler())
Similar to :func:`parse`, but parses from a buffer *string* received as a
parameter.
+-*/+-*/+-*/+-*/SAXException e
SAXException
Encapsulate an XML error or warning. This class can contain basic error or
warning information from either the XML parser or the application: it can be
subclassed to provide additional functionality or to add localization. Note
that although the handlers defined in the :class:`ErrorHandler` interface
receive instances of this exception, it is not required to actually raise the
exception --- it is also useful as a container for information.
When instantiated, *msg* should be a human-readable description of the error.
The optional *exception* parameter, if given, should be ``None`` or an exception
that was caught by the parsing code and is being passed along as information.
This is the base class for the other SAX exception classes.
+-*/+-*/+-*/+-*/SAXParseException e
SAXParseException
Subclass of :exc:`SAXException` raised on parse errors. Instances of this class
are passed to the methods of the SAX :class:`ErrorHandler` interface to provide
information about the parse error. This class supports the SAX :class:`Locator`
interface as well as the :class:`SAXException` interface.
+-*/+-*/+-*/+-*/SAXNotSupportedException e
SAXNotSupportedException
Subclass of :exc:`SAXException` raised when a SAX :class:`XMLReader` is asked to
enable a feature that is not supported, or to set a property to a value that the
implementation does not support. SAX applications and extensions may use this
class for similar purposes.
+-*/+-*/+-*/+-*/SAXNotRecognizedException e
SAXNotRecognizedException
Subclass of :exc:`SAXException` raised when a SAX :class:`XMLReader` is
confronted with an unrecognized feature or property. SAX applications and
extensions may use this class for similar purposes.
+-*/+-*/+-*/+-*/SAXException _
+-*/+-*/+-*/+-*/+-*/getException m
getException()
Return an encapsulated exception object, or ``None``.
+-*/+-*/+-*/+-*/+-*/getMessage m
getMessage()
Return a human-readable message describing the error condition.
+-*/+-*/+-*/+-*/handler p Base classes for SAX event handlers.
+-*/+-*/+-*/+-*/+-*/property_dom_node d
property_dom_node
| value: ``"http://xml.org/sax/properties/dom-node"``
| data type: org.w3c.dom.Node (not supported in Python 2)
| description: When parsing, the current DOM node being visited if this is
a DOM iterator; when not parsing, the root DOM node for iteration.
| access: (parsing) read-only; (not parsing) read/write
+-*/+-*/+-*/+-*/+-*/feature_string_interning d
feature_string_interning
| value: ``"http://xml.org/sax/features/string-interning"``
| true: All element names, prefixes, attribute names, Namespace URIs, and
local names are interned using the built-in intern function.
| false: Names are not necessarily interned, although they may be (default).
| access: (parsing) read-only; (not parsing) read/write
+-*/+-*/+-*/+-*/+-*/property_declaration_handler d
property_declaration_handler
| value: ``"http://xml.org/sax/properties/declaration-handler"``
| data type: xml.sax.sax2lib.DeclHandler (not supported in Python 2)
| description: An optional extension handler for DTD-related events other
than notations and unparsed entities.
| access: read/write
+-*/+-*/+-*/+-*/+-*/all_properties d
all_properties
List of all known property names.
+-*/+-*/+-*/+-*/+-*/property_xml_string d
property_xml_string
| value: ``"http://xml.org/sax/properties/xml-string"``
| data type: String
| description: The literal string of characters that was the source for the
current event.
| access: read-only
+-*/+-*/+-*/+-*/+-*/feature_external_pes d
feature_external_pes
| value: ``"http://xml.org/sax/features/external-parameter-entities"``
| true: Include all external parameter entities, including the external DTD
subset.
| false: Do not include any external parameter entities, even the external
DTD subset.
| access: (parsing) read-only; (not parsing) read/write
+-*/+-*/+-*/+-*/+-*/property_lexical_handler d
property_lexical_handler
| value: ``"http://xml.org/sax/properties/lexical-handler"``
| data type: xml.sax.sax2lib.LexicalHandler (not supported in Python 2)
| description: An optional extension handler for lexical events like
comments.
| access: read/write
+-*/+-*/+-*/+-*/+-*/feature_external_ges d
feature_external_ges
| value: ``"http://xml.org/sax/features/external-general-entities"``
| true: Include all external general (text) entities.
| false: Do not include external general entities.
| access: (parsing) read-only; (not parsing) read/write
+-*/+-*/+-*/+-*/+-*/feature_namespace_prefixes d
feature_namespace_prefixes
| value: ``"http://xml.org/sax/features/namespace-prefixes"``
| true: Report the original prefixed names and attributes used for Namespace
declarations.
| false: Do not report attributes used for Namespace declarations, and
optionally do not report original prefixed names (default).
| access: (parsing) read-only; (not parsing) read/write
+-*/+-*/+-*/+-*/+-*/all_features d
all_features
List of all features.
+-*/+-*/+-*/+-*/+-*/feature_validation d
feature_validation
| value: ``"http://xml.org/sax/features/validation"``
| true: Report all validation errors (implies external-general-entities and
external-parameter-entities).
| false: Do not report validation errors.
| access: (parsing) read-only; (not parsing) read/write
+-*/+-*/+-*/+-*/+-*/feature_namespaces d
feature_namespaces
| value: ``"http://xml.org/sax/features/namespaces"``
| true: Perform Namespace processing.
| false: Optionally do not perform Namespace processing (implies
namespace-prefixes; default).
| access: (parsing) read-only; (not parsing) read/write
+-*/+-*/+-*/+-*/+-*/EntityResolver c
EntityResolver
Basic interface for resolving entities. If you create an object implementing
this interface, then register the object with your Parser, the parser will call
the method in your object to resolve all external entities.
+-*/+-*/+-*/+-*/+-*/+-*/resolveEntity m
resolveEntity(publicId, systemId)
Resolve the system identifier of an entity and return either the system
identifier to read from as a string, or an InputSource to read from. The default
implementation returns *systemId*.
+-*/+-*/+-*/+-*/+-*/DTDHandler c
DTDHandler
Handle DTD events.
This interface specifies only those DTD events required for basic parsing
(unparsed entities and attributes).
+-*/+-*/+-*/+-*/+-*/+-*/notationDecl m
notationDecl(name, publicId, systemId)
Handle a notation declaration event.
+-*/+-*/+-*/+-*/+-*/+-*/unparsedEntityDecl m
unparsedEntityDecl(name, publicId, systemId, ndata)
Handle an unparsed entity declaration event.
+-*/+-*/+-*/+-*/+-*/ErrorHandler c
ErrorHandler
Interface used by the parser to present error and warning messages to the
application. The methods of this object control whether errors are immediately
converted to exceptions or are handled in some other way.
+-*/+-*/+-*/+-*/+-*/+-*/warning m
warning(exception)
Called when the parser presents minor warning information to the application.
Parsing is expected to continue when this method returns, and document
information will continue to be passed to the application. Raising an exception
in this method will cause parsing to end.
+-*/+-*/+-*/+-*/+-*/+-*/fatalError m
fatalError(exception)
Called when the parser encounters an error it cannot recover from; parsing is
expected to terminate when this method returns.
+-*/+-*/+-*/+-*/+-*/+-*/error m
error(exception)
Called when the parser encounters a recoverable error. If this method does not
raise an exception, parsing may continue, but further document information
should not be expected by the application. Allowing the parser to continue may
allow additional errors to be discovered in the input document.
+-*/+-*/+-*/+-*/+-*/ContentHandler c
ContentHandler
This is the main callback interface in SAX, and the one most important to
applications. The order of events in this interface mirrors the order of the
information in the document.
+-*/+-*/+-*/+-*/+-*/+-*/startPrefixMapping m
startPrefixMapping(prefix, uri)
Begin the scope of a prefix-URI Namespace mapping.
The information from this event is not necessary for normal Namespace
processing: the SAX XML reader will automatically replace prefixes for element
and attribute names when the ``feature_namespaces`` feature is enabled (the
default).
There are cases, however, when applications need to use prefixes in character
data or in attribute values, where they cannot safely be expanded automatically;
the :meth:`startPrefixMapping` and :meth:`endPrefixMapping` events supply the
information to the application to expand prefixes in those contexts itself, if
necessary.
.. XXX This is not really the default, is it? MvL
Note that :meth:`startPrefixMapping` and :meth:`endPrefixMapping` events are not
guaranteed to be properly nested relative to each-other: all
:meth:`startPrefixMapping` events will occur before the corresponding
:meth:`startElement` event, and all :meth:`endPrefixMapping` events will occur
after the corresponding :meth:`endElement` event, but their order is not
guaranteed.
+-*/+-*/+-*/+-*/+-*/+-*/skippedEntity m
skippedEntity(name)
Receive notification of a skipped entity.
The Parser will invoke this method once for each entity skipped. Non-validating
processors may skip entities if they have not seen the declarations (because,
for example, the entity was declared in an external DTD subset). All processors
may skip external entities, depending on the values of the
``feature_external_ges`` and the ``feature_external_pes`` properties.
+-*/+-*/+-*/+-*/+-*/+-*/endPrefixMapping m
endPrefixMapping(prefix)
End the scope of a prefix-URI mapping.
See :meth:`startPrefixMapping` for details. This event will always occur after
the corresponding :meth:`endElement` event, but the order of
:meth:`endPrefixMapping` events is not otherwise guaranteed.
+-*/+-*/+-*/+-*/+-*/+-*/endElementNS m
endElementNS(name, qname)
Signals the end of an element in namespace mode.
The *name* parameter contains the name of the element type, just as with the
:meth:`startElementNS` method, likewise the *qname* parameter.
+-*/+-*/+-*/+-*/+-*/+-*/processingInstruction m
processingInstruction(target, data)
Receive notification of a processing instruction.
The Parser will invoke this method once for each processing instruction found:
note that processing instructions may occur before or after the main document
element.
A SAX parser should never report an XML declaration (XML 1.0, section 2.8) or a
text declaration (XML 1.0, section 4.3.1) using this method.
+-*/+-*/+-*/+-*/+-*/+-*/endElement m
endElement(name)
Signals the end of an element in non-namespace mode.
The *name* parameter contains the name of the element type, just as with the
:meth:`startElement` event.
+-*/+-*/+-*/+-*/+-*/+-*/startElement m
startElement(name, attrs)
Signals the start of an element in non-namespace mode.
The *name* parameter contains the raw XML 1.0 name of the element type as a
string and the *attrs* parameter holds an object of the :class:`Attributes`
interface (see :ref:`attributes-objects`) containing the attributes of
the element. The object passed as *attrs* may be re-used by the parser; holding
on to a reference to it is not a reliable way to keep a copy of the attributes.
To keep a copy of the attributes, use the :meth:`copy` method of the *attrs*
object.
+-*/+-*/+-*/+-*/+-*/+-*/setDocumentLocator m
setDocumentLocator(locator)
Called by the parser to give the application a locator for locating the origin
of document events.
SAX parsers are strongly encouraged (though not absolutely required) to supply a
locator: if it does so, it must supply the locator to the application by
invoking this method before invoking any of the other methods in the
DocumentHandler interface.
The locator allows the application to determine the end position of any
document-related event, even if the parser is not reporting an error. Typically,
the application will use this information for reporting its own errors (such as
character content that does not match an application's business rules). The
information returned by the locator is probably not sufficient for use with a
search engine.
Note that the locator will return correct information only during the invocation
of the events in this interface. The application should not attempt to use it at
any other time.
+-*/+-*/+-*/+-*/+-*/+-*/startDocument m
startDocument()
Receive notification of the beginning of a document.
The SAX parser will invoke this method only once, before any other methods in
this interface or in DTDHandler (except for :meth:`setDocumentLocator`).
+-*/+-*/+-*/+-*/+-*/+-*/startElementNS m
startElementNS(name, qname, attrs)
Signals the start of an element in namespace mode.
The *name* parameter contains the name of the element type as a ``(uri,
localname)`` tuple, the *qname* parameter contains the raw XML 1.0 name used in
the source document, and the *attrs* parameter holds an instance of the
:class:`AttributesNS` interface (see :ref:`attributes-ns-objects`)
containing the attributes of the element. If no namespace is associated with
the element, the *uri* component of *name* will be ``None``. The object passed
as *attrs* may be re-used by the parser; holding on to a reference to it is not
a reliable way to keep a copy of the attributes. To keep a copy of the
attributes, use the :meth:`copy` method of the *attrs* object.
Parsers may set the *qname* parameter to ``None``, unless the
``feature_namespace_prefixes`` feature is activated.
+-*/+-*/+-*/+-*/+-*/+-*/characters m
characters(content)
Receive notification of character data.
The Parser will call this method to report each chunk of character data. SAX
parsers may return all contiguous character data in a single chunk, or they may
split it into several chunks; however, all of the characters in any single event
must come from the same external entity so that the Locator provides useful
information.
*content* may be a string or bytes instance; the ``expat`` reader module
always produces strings.
.. note::
The earlier SAX 1 interface provided by the Python XML Special Interest Group
used a more Java-like interface for this method. Since most parsers used from
Python did not take advantage of the older interface, the simpler signature was
chosen to replace it. To convert old code to the new interface, use *content*
instead of slicing content with the old *offset* and *length* parameters.
+-*/+-*/+-*/+-*/+-*/+-*/endDocument m
endDocument()
Receive notification of the end of a document.
The SAX parser will invoke this method only once, and it will be the last method
invoked during the parse. The parser shall not invoke this method until it has
either abandoned parsing (because of an unrecoverable error) or reached the end
of input.
+-*/+-*/+-*/+-*/+-*/+-*/ignorableWhitespace m
ignorableWhitespace(whitespace)
Receive notification of ignorable whitespace in element content.
Validating Parsers must use this method to report each chunk of ignorable
whitespace (see the W3C XML 1.0 recommendation, section 2.10): non-validating
parsers may also use this method if they are capable of parsing and using
content models.
SAX parsers may return all contiguous whitespace in a single chunk, or they may
split it into several chunks; however, all of the characters in any single event
must come from the same external entity, so that the Locator provides useful
information.
+-*/+-*/+-*/+-*/saxutils p Convenience functions and classes for use with SAX.
+-*/+-*/+-*/+-*/+-*/quoteattr f
quoteattr(data, entities={})
Similar to :func:`escape`, but also prepares *data* to be used as an
attribute value. The return value is a quoted version of *data* with any
additional required replacements. :func:`quoteattr` will select a quote
character based on the content of *data*, attempting to avoid encoding any
quote characters in the string. If both single- and double-quote characters
are already in *data*, the double-quote characters will be encoded and *data*
will be wrapped in double-quotes. The resulting string can be used directly
as an attribute value::
>>> print("<element attr=%s>" % quoteattr("ab ' cd \" ef"))
<element attr="ab ' cd &quot; ef">
This function is useful when generating attribute values for HTML or any SGML
using the reference concrete syntax.
+-*/+-*/+-*/+-*/+-*/prepare_input_source f
prepare_input_source(source, base='')
This function takes an input source and an optional base URL and returns a fully
resolved :class:`InputSource` object ready for reading. The input source can be
given as a string, a file-like object, or an :class:`InputSource` object;
parsers will use this function to implement the polymorphic *source* argument to
their :meth:`parse` method.
+-*/+-*/+-*/+-*/+-*/unescape f 还原已转义的字符串为原始字符串
unescape(data, entities={})
entities: 可添加的自定义转义字符,默认的只包括<>&的转义
如{ '&quot;' : '"' ,
'&nbsp;' : ' ' ,
'&apos;' : "'" }
+-*/+-*/+-*/+-*/+-*/escape f 转义字符串内的特殊字符
escape(data, entities={})
entities: 可添加的自定义转义字符,默认的只包括<>&
如{ '"' : '&quot;' ,
' ' : '&nbsp;' ,
"'" : '&apos;' }
+-*/+-*/+-*/+-*/+-*/XMLGenerator c
XMLGenerator(out=None, encoding='iso-8859-1', short_empty_elements=False)
This class implements the :class:`ContentHandler` interface by writing SAX
events back into an XML document. In other words, using an :class:`XMLGenerator`
as the content handler will reproduce the original document being parsed. *out*
should be a file-like object which will default to *sys.stdout*. *encoding* is
the encoding of the output stream which defaults to ``'iso-8859-1'``.
*short_empty_elements* controls the formatting of elements that contain no
content: if *False* (the default) they are emitted as a pair of start/end
tags, if set to *True* they are emitted as a single self-closed tag.
.. versionadded:: 3.2
short_empty_elements
+-*/+-*/+-*/+-*/+-*/XMLFilterBase c
XMLFilterBase(base)
This class is designed to sit between an :class:`XMLReader` and the client
application's event handlers. By default, it does nothing but pass requests up
to the reader and events on to the handlers unmodified, but subclasses can
override specific methods to modify the event stream or the configuration
requests as they pass through.
+-*/+-*/+-*/+-*/xmlreader p Interface which SAX-compliant XML parsers must implement.
+-*/+-*/+-*/+-*/+-*/AttributesNSImpl c
AttributesNSImpl(attrs, qnames)
Namespace-aware variant of :class:`AttributesImpl`, which will be passed to
:meth:`startElementNS`. It is derived from :class:`AttributesImpl`, but
understands attribute names as two-tuples of *namespaceURI* and
*localname*. In addition, it provides a number of methods expecting qualified
names as they appear in the original document. This class implements the
:class:`AttributesNS` interface (see section :ref:`attributes-ns-objects`).
+-*/+-*/+-*/+-*/+-*/XMLReader c
XMLReader()
Base class which can be inherited by SAX parsers.
+-*/+-*/+-*/+-*/+-*/+-*/setFeature m
setFeature(featurename, value)
Set the *featurename* to *value*. If the feature is not recognized,
:exc:`SAXNotRecognizedException` is raised. If the feature or its setting is not
supported by the parser, *SAXNotSupportedException* is raised.
+-*/+-*/+-*/+-*/+-*/+-*/setContentHandler m
setContentHandler(handler)
Set the current :class:`ContentHandler`. If no :class:`ContentHandler` is set,
content events will be discarded.
+-*/+-*/+-*/+-*/+-*/+-*/getProperty m
getProperty(propertyname)
Return the current setting for property *propertyname*. If the property is not
recognized, a :exc:`SAXNotRecognizedException` is raised. The well-known
propertynames are listed in the module :mod:`xml.sax.handler`.
+-*/+-*/+-*/+-*/+-*/+-*/setEntityResolver m
setEntityResolver(handler)
Set the current :class:`EntityResolver`. If no :class:`EntityResolver` is set,
attempts to resolve an external entity will result in opening the system
identifier for the entity, and fail if it is not available.
+-*/+-*/+-*/+-*/+-*/+-*/setLocale m
setLocale(locale)
Allow an application to set the locale for errors and warnings.
SAX parsers are not required to provide localization for errors and warnings; if
they cannot support the requested locale, however, they must raise a SAX
exception. Applications may request a locale change in the middle of a parse.
+-*/+-*/+-*/+-*/+-*/+-*/getErrorHandler m
getErrorHandler()
Return the current :class:`ErrorHandler`.
+-*/+-*/+-*/+-*/+-*/+-*/setErrorHandler m
setErrorHandler(handler)
Set the current error handler. If no :class:`ErrorHandler` is set, errors will
be raised as exceptions, and warnings will be printed.
+-*/+-*/+-*/+-*/+-*/+-*/parse m
parse(source)
Process an input source, producing SAX events. The *source* object can be a
system identifier (a string identifying the input source -- typically a file
name or an URL), a file-like object, or an :class:`InputSource` object. When
:meth:`parse` returns, the input is completely processed, and the parser object
can be discarded or reset. As a limitation, the current implementation only
accepts byte streams; processing of character streams is for further study.
+-*/+-*/+-*/+-*/+-*/+-*/getEntityResolver m
getEntityResolver()
Return the current :class:`EntityResolver`.
+-*/+-*/+-*/+-*/+-*/+-*/getContentHandler m
getContentHandler()
Return the current :class:`ContentHandler`.
+-*/+-*/+-*/+-*/+-*/+-*/setDTDHandler m
setDTDHandler(handler)
Set the current :class:`DTDHandler`. If no :class:`DTDHandler` is set, DTD
events will be discarded.
+-*/+-*/+-*/+-*/+-*/+-*/getFeature m
getFeature(featurename)
Return the current setting for feature *featurename*. If the feature is not
recognized, :exc:`SAXNotRecognizedException` is raised. The well-known
featurenames are listed in the module :mod:`xml.sax.handler`.
+-*/+-*/+-*/+-*/+-*/+-*/setProperty m
setProperty(propertyname, value)
Set the *propertyname* to *value*. If the property is not recognized,
:exc:`SAXNotRecognizedException` is raised. If the property or its setting is
not supported by the parser, *SAXNotSupportedException* is raised.
+-*/+-*/+-*/+-*/+-*/+-*/getDTDHandler m
getDTDHandler()
Return the current :class:`DTDHandler`.
+-*/+-*/+-*/+-*/+-*/InputSource c
InputSource(system_id=None)
Encapsulation of the information needed by the :class:`XMLReader` to read
entities.
This class may include information about the public identifier, system
identifier, byte stream (possibly with character encoding information) and/or
the character stream of an entity.
Applications will create objects of this class for use in the
:meth:`XMLReader.parse` method and for returning from
EntityResolver.resolveEntity.
An :class:`InputSource` belongs to the application, the :class:`XMLReader` is
not allowed to modify :class:`InputSource` objects passed to it from the
application, although it may make copies and modify those.
+-*/+-*/+-*/+-*/+-*/+-*/setSystemId m
setSystemId(id)
Sets the system identifier of this :class:`InputSource`.
+-*/+-*/+-*/+-*/+-*/+-*/getCharacterStream m
getCharacterStream()
Get the character stream for this input source.
+-*/+-*/+-*/+-*/+-*/+-*/setEncoding m
setEncoding(encoding)
Sets the character encoding of this :class:`InputSource`.
The encoding must be a string acceptable for an XML encoding declaration (see
section 4.3.3 of the XML recommendation).
The encoding attribute of the :class:`InputSource` is ignored if the
:class:`InputSource` also contains a character stream.
+-*/+-*/+-*/+-*/+-*/+-*/setPublicId m
setPublicId(id)
Sets the public identifier of this :class:`InputSource`.
+-*/+-*/+-*/+-*/+-*/+-*/getEncoding m
getEncoding()
Get the character encoding of this InputSource.
+-*/+-*/+-*/+-*/+-*/+-*/getSystemId m
getSystemId()
Returns the system identifier of this :class:`InputSource`.
+-*/+-*/+-*/+-*/+-*/+-*/getPublicId m
getPublicId()
Returns the public identifier of this :class:`InputSource`.
+-*/+-*/+-*/+-*/+-*/+-*/setCharacterStream m
setCharacterStream(charfile)
Set the character stream for this input source. (The stream must be a Python 1.6
Unicode-wrapped file-like that performs conversion to strings.)
If there is a character stream specified, the SAX parser will ignore any byte
stream and will not attempt to open a URI connection to the system identifier.
+-*/+-*/+-*/+-*/+-*/+-*/setByteStream m
setByteStream(bytefile)
Set the byte stream (a Python file-like object which does not perform
byte-to-character conversion) for this input source.
The SAX parser will ignore this if there is also a character stream specified,
but it will use a byte stream in preference to opening a URI connection itself.
If the application knows the character encoding of the byte stream, it should
set it with the setEncoding method.
+-*/+-*/+-*/+-*/+-*/+-*/getByteStream m
getByteStream()
Get the byte stream for this input source.
The getEncoding method will return the character encoding for this byte stream,
or None if unknown.
+-*/+-*/+-*/+-*/+-*/Locator c
Locator()
Interface for associating a SAX event with a document location. A locator object
will return valid results only during calls to DocumentHandler methods; at any
other time, the results are unpredictable. If information is not available,
methods may return ``None``.
+-*/+-*/+-*/+-*/+-*/+-*/getSystemId m
getSystemId()
Return the system identifier for the current event.
+-*/+-*/+-*/+-*/+-*/+-*/getLineNumber m
getLineNumber()
Return the line number where the current event ends.
+-*/+-*/+-*/+-*/+-*/+-*/getColumnNumber m
getColumnNumber()
Return the column number where the current event ends.
+-*/+-*/+-*/+-*/+-*/+-*/getPublicId m
getPublicId()
Return the public identifier for the current event.
+-*/+-*/+-*/+-*/+-*/IncrementalParser c
IncrementalParser()
In some cases, it is desirable not to parse an input source at once, but to feed
chunks of the document as they get available. Note that the reader will normally
not read the entire file, but read it in chunks as well; still :meth:`parse`
won't return until the entire document is processed. So these interfaces should
be used if the blocking behaviour of :meth:`parse` is not desirable.
When the parser is instantiated it is ready to begin accepting data from the
feed method immediately. After parsing has been finished with a call to close
the reset method must be called to make the parser ready to accept new data,
either from feed or using the parse method.
Note that these methods must *not* be called during parsing, that is, after
parse has been called and before it returns.
By default, the class also implements the parse method of the XMLReader
interface using the feed, close and reset methods of the IncrementalParser
interface as a convenience to SAX 2.0 driver writers.
+-*/+-*/+-*/+-*/+-*/+-*/reset m
reset()
This method is called after close has been called to reset the parser so that it
is ready to parse new documents. The results of calling parse or feed after
close without calling reset are undefined.
+-*/+-*/+-*/+-*/+-*/+-*/close m
close()
Assume the end of the document. That will check well-formedness conditions that
can be checked only at the end, invoke handlers, and may clean up resources
allocated during parsing.
+-*/+-*/+-*/+-*/+-*/+-*/feed m
feed(data)
Process a chunk of *data*.
+-*/+-*/+-*/+-*/+-*/AttributesImpl c
AttributesImpl(attrs)
This is an implementation of the :class:`Attributes` interface (see section
:ref:`attributes-objects`). This is a dictionary-like object which
represents the element attributes in a :meth:`startElement` call. In addition
to the most useful dictionary operations, it supports a number of other
methods as described by the interface. Objects of this class should be
instantiated by readers; *attrs* must be a dictionary-like object containing
a mapping from attribute names to attribute values.
+-*/+-*/+-*/+-*/+-*/Attributes _
+-*/+-*/+-*/+-*/+-*/+-*/getLength m
getLength()
Return the number of attributes.
+-*/+-*/+-*/+-*/+-*/+-*/getType m
getType(name)
Returns the type of the attribute *name*, which is normally ``'CDATA'``.
+-*/+-*/+-*/+-*/+-*/+-*/getNames m
getNames()
Return the names of the attributes.
+-*/+-*/+-*/+-*/+-*/+-*/getValue m
getValue(name)
Return the value of attribute *name*.
+-*/+-*/+-*/+-*/+-*/AttributesNS _
+-*/+-*/+-*/+-*/+-*/+-*/getNameByQName m
getNameByQName(name)
Return the ``(namespace, localname)`` pair for a qualified *name*.
+-*/+-*/+-*/+-*/+-*/+-*/getQNameByName m
getQNameByName(name)
Return the qualified name for a ``(namespace, localname)`` pair.
+-*/+-*/+-*/+-*/+-*/+-*/getValueByQName m
getValueByQName(name)
Return the value for a qualified name.
+-*/+-*/+-*/+-*/+-*/+-*/getQNames m
getQNames()
Return the qualified names of all attributes.
+-*/mm _ Multimedia Services
+-*/+-*/aifc p Read and write audio files in AIFF or AIFC format.
+-*/+-*/+-*/open f
open(file, mode=None)
Open an AIFF or AIFF-C file and return an object instance with methods that are
described below. The argument *file* is either a string naming a file or a
:term:`file object`. *mode* must be ``'r'`` or ``'rb'`` when the file must be
opened for reading, or ``'w'`` or ``'wb'`` when the file must be opened for writing.
If omitted, ``file.mode`` is used if it exists, otherwise ``'rb'`` is used. When
used for writing, the file object should be seekable, unless you know ahead of
time how many samples you are going to write in total and use
:meth:`writeframesraw` and :meth:`setnframes`.
+-*/+-*/+-*/aifc _
+-*/+-*/+-*/+-*/getcompname m
getcompname()
Return a bytes array convertible to a human-readable description
of the type of compression used in the audio file. For AIFF files,
the returned value is ``b'not compressed'``.
+-*/+-*/+-*/+-*/getparams m
getparams()
Return a tuple consisting of all of the above values in the above order.
+-*/+-*/+-*/+-*/setpos m
setpos(pos)
Seek to the specified frame number.
+-*/+-*/+-*/+-*/aiff m
aiff()
Create an AIFF file. The default is that an AIFF-C file is created, unless the
name of the file ends in ``'.aiff'`` in which case the default is an AIFF file.
+-*/+-*/+-*/+-*/aifc m
aifc()
Create an AIFF-C file. The default is that an AIFF-C file is created, unless
the name of the file ends in ``'.aiff'`` in which case the default is an AIFF
file.
+-*/+-*/+-*/+-*/close m
close()
Close the AIFF file. The header of the file is updated to reflect the actual
size of the audio data. After calling this method, the object can no longer be
used.
+-*/+-*/+-*/+-*/setnframes m
setnframes(nframes)
Specify the number of frames that are to be written to the audio file. If this
parameter is not set, or not set correctly, the file needs to support seeking.
+-*/+-*/+-*/+-*/getsampwidth m
getsampwidth()
Return the size in bytes of individual samples.
+-*/+-*/+-*/+-*/setmark m
setmark(id, pos, name)
Add a mark with the given id (larger than 0), and the given name at the given
position. This method can be called at any time before :meth:`close`.
+-*/+-*/+-*/+-*/getcomptype m
getcomptype()
Return a bytes array of length 4 describing the type of compression
used in the audio file. For AIFF files, the returned value is
``b'NONE'``.
+-*/+-*/+-*/+-*/rewind m
rewind()
Rewind the read pointer. The next :meth:`readframes` will start from the
beginning.
+-*/+-*/+-*/+-*/readframes m
readframes(nframes)
Read and return the next *nframes* frames from the audio file. The returned
data is a string containing for each frame the uncompressed samples of all
channels.
+-*/+-*/+-*/+-*/setparams m
setparams(nchannels, sampwidth, framerate, comptype, compname)
Set all the above parameters at once. The argument is a tuple consisting of the
various parameters. This means that it is possible to use the result of a
:meth:`getparams` call as argument to :meth:`setparams`.
+-*/+-*/+-*/+-*/tell m
tell()
Return the current write position in the output file. Useful in combination
with :meth:`setmark`.
+-*/+-*/+-*/+-*/setsampwidth m
setsampwidth(width)
Specify the size in bytes of audio samples.
+-*/+-*/+-*/+-*/setnchannels m
setnchannels(nchannels)
Specify the number of channels in the audio file.
+-*/+-*/+-*/+-*/getnframes m
getnframes()
Return the number of audio frames in the file.
+-*/+-*/+-*/+-*/getframerate m
getframerate()
Return the sampling rate (number of audio frames per second).
+-*/+-*/+-*/+-*/writeframesraw m
writeframesraw(data)
Like :meth:`writeframes`, except that the header of the audio file is not
updated.
+-*/+-*/+-*/+-*/setframerate m
setframerate(rate)
Specify the sampling frequency in frames per second.
+-*/+-*/+-*/+-*/writeframes m
writeframes(data)
Write data to the output file. This method can only be called after the audio
file parameters have been set.
+-*/+-*/+-*/+-*/getmarkers m
getmarkers()
Return a list of markers in the audio file. A marker consists of a tuple of
three elements. The first is the mark ID (an integer), the second is the mark
position in frames from the beginning of the data (an integer), the third is the
name of the mark (a string).
+-*/+-*/+-*/+-*/getmark m
getmark(id)
Return the tuple as described in :meth:`getmarkers` for the mark with the given
*id*.
+-*/+-*/+-*/+-*/getnchannels m
getnchannels()
Return the number of audio channels (1 for mono, 2 for stereo).
+-*/+-*/+-*/+-*/setcomptype m
setcomptype(type, name)
.. index::
single: u-LAW
single: A-LAW
single: G.722
Specify the compression type. If not specified, the audio data will
not be compressed. In AIFF files, compression is not possible.
The name parameter should be a human-readable description of the
compression type as a bytes array, the type parameter should be a
bytes array of length 4. Currently the following compression types
are supported: ``b'NONE'``, ``b'ULAW'``, ``b'ALAW'``, ``b'G722'``.
+-*/+-*/audioop p Manipulate raw audio data.
+-*/+-*/+-*/rms f
rms(fragment, width)
Return the root-mean-square of the fragment, i.e. ``sqrt(sum(S_i^2)/n)``.
This is a measure of the power in an audio signal.
+-*/+-*/+-*/bias f
bias(fragment, width, bias)
Return a fragment that is the original fragment with a bias added to each
sample.
+-*/+-*/+-*/alaw2lin f
alaw2lin(fragment, width)
Convert sound fragments in a-LAW encoding to linearly encoded sound fragments.
a-LAW encoding always uses 8 bits samples, so *width* refers only to the sample
width of the output fragment here.
+-*/+-*/+-*/findfactor f
findfactor(fragment, reference)
Return a factor *F* such that ``rms(add(fragment, mul(reference, -F)))`` is
minimal, i.e., return the factor with which you should multiply *reference* to
make it match as well as possible to *fragment*. The fragments should both
contain 2-byte samples.
The time taken by this routine is proportional to ``len(fragment)``.
+-*/+-*/+-*/minmax f
minmax(fragment, width)
Return a tuple consisting of the minimum and maximum values of all samples in
the sound fragment.
+-*/+-*/+-*/avg f
avg(fragment, width)
Return the average over all samples in the fragment.
+-*/+-*/+-*/lin2adpcm f
lin2adpcm(fragment, width, state)
Convert samples to 4 bit Intel/DVI ADPCM encoding. ADPCM coding is an adaptive
coding scheme, whereby each 4 bit number is the difference between one sample
and the next, divided by a (varying) step. The Intel/DVI ADPCM algorithm has
been selected for use by the IMA, so it may well become a standard.
*state* is a tuple containing the state of the coder. The coder returns a tuple
``(adpcmfrag, newstate)``, and the *newstate* should be passed to the next call
of :func:`lin2adpcm`. In the initial call, ``None`` can be passed as the state.
*adpcmfrag* is the ADPCM coded fragment packed 2 4-bit values per byte.
+-*/+-*/+-*/tostereo f
tostereo(fragment, width, lfactor, rfactor)
Generate a stereo fragment from a mono fragment. Each pair of samples in the
stereo fragment are computed from the mono sample, whereby left channel samples
are multiplied by *lfactor* and right channel samples by *rfactor*.
+-*/+-*/+-*/findmax f
findmax(fragment, length)
Search *fragment* for a slice of length *length* samples (not bytes!) with
maximum energy, i.e., return *i* for which ``rms(fragment[i*2:(i+length)*2])``
is maximal. The fragments should both contain 2-byte samples.
The routine takes time proportional to ``len(fragment)``.
+-*/+-*/+-*/cross f
cross(fragment, width)
Return the number of zero crossings in the fragment passed as an argument.
+-*/+-*/+-*/add f
add(fragment1, fragment2, width)
Return a fragment which is the addition of the two samples passed as parameters.
*width* is the sample width in bytes, either ``1``, ``2`` or ``4``. Both
fragments should have the same length.
+-*/+-*/+-*/ulaw2lin f
ulaw2lin(fragment, width)
Convert sound fragments in u-LAW encoding to linearly encoded sound fragments.
u-LAW encoding always uses 8 bits samples, so *width* refers only to the sample
width of the output fragment here.
+-*/+-*/+-*/mul f
mul(fragment, width, factor)
Return a fragment that has all samples in the original fragment multiplied by
the floating-point value *factor*. Overflow is silently ignored.
+-*/+-*/+-*/lin2ulaw f
lin2ulaw(fragment, width)
Convert samples in the audio fragment to u-LAW encoding and return this as a
Python string. u-LAW is an audio encoding format whereby you get a dynamic
range of about 14 bits using only 8 bit samples. It is used by the Sun audio
hardware, among others.
+-*/+-*/+-*/max f
max(fragment, width)
Return the maximum of the *absolute value* of all samples in a fragment.
+-*/+-*/+-*/lin2alaw f
lin2alaw(fragment, width)
Convert samples in the audio fragment to a-LAW encoding and return this as a
Python string. a-LAW is an audio encoding format whereby you get a dynamic
range of about 13 bits using only 8 bit samples. It is used by the Sun audio
hardware, among others.
+-*/+-*/+-*/tomono f
tomono(fragment, width, lfactor, rfactor)
Convert a stereo fragment to a mono fragment. The left channel is multiplied by
*lfactor* and the right channel by *rfactor* before adding the two channels to
give a mono signal.
+-*/+-*/+-*/lin2lin f
lin2lin(fragment, width, newwidth)
Convert samples between 1-, 2- and 4-byte formats.
.. note::
In some audio formats, such as .WAV files, 16 and 32 bit samples are
signed, but 8 bit samples are unsigned. So when converting to 8 bit wide
samples for these formats, you need to also add 128 to the result::
new_frames = audioop.lin2lin(frames, old_width, 1)
new_frames = audioop.bias(new_frames, 1, 128)
The same, in reverse, has to be applied when converting from 8 to 16 or 32
bit width samples.
+-*/+-*/+-*/adpcm2lin f
adpcm2lin(adpcmfragment, width, state)
Decode an Intel/DVI ADPCM coded fragment to a linear fragment. See the
description of :func:`lin2adpcm` for details on ADPCM coding. Return a tuple
``(sample, newstate)`` where the sample has the width specified in *width*.
+-*/+-*/+-*/findfit f
findfit(fragment, reference)
Try to match *reference* as well as possible to a portion of *fragment* (which
should be the longer fragment). This is (conceptually) done by taking slices
out of *fragment*, using :func:`findfactor` to compute the best match, and
minimizing the result. The fragments should both contain 2-byte samples.
Return a tuple ``(offset, factor)`` where *offset* is the (integer) offset into
*fragment* where the optimal match started and *factor* is the (floating-point)
factor as per :func:`findfactor`.
+-*/+-*/+-*/getsample f
getsample(fragment, width, index)
Return the value of sample *index* from the fragment.
+-*/+-*/+-*/avgpp f
avgpp(fragment, width)
Return the average peak-peak value over all samples in the fragment. No
filtering is done, so the usefulness of this routine is questionable.
+-*/+-*/+-*/reverse f
reverse(fragment, width)
Reverse the samples in a fragment and returns the modified fragment.
+-*/+-*/+-*/ratecv f
ratecv(fragment, width, nchannels, inrate, outrate, state[, weightA[, weightB]])
Convert the frame rate of the input fragment.
*state* is a tuple containing the state of the converter. The converter returns
a tuple ``(newfragment, newstate)``, and *newstate* should be passed to the next
call of :func:`ratecv`. The initial call should pass ``None`` as the state.
The *weightA* and *weightB* arguments are parameters for a simple digital filter
and default to ``1`` and ``0`` respectively.
+-*/+-*/+-*/maxpp f
maxpp(fragment, width)
Return the maximum peak-peak value in the sound fragment.
+-*/+-*/+-*/error e
error
This exception is raised on all errors, such as unknown number of bytes per
sample, etc.
+-*/+-*/chunk p Module to read IFF chunks.
+-*/+-*/+-*/Chunk c
Chunk(file, align=True, bigendian=True, inclheader=False)
Class which represents a chunk. The *file* argument is expected to be a
file-like object. An instance of this class is specifically allowed. The
only method that is needed is :meth:`read`. If the methods :meth:`seek` and
:meth:`tell` are present and don't raise an exception, they are also used.
If these methods are present and raise an exception, they are expected to not
have altered the object. If the optional argument *align* is true, chunks
are assumed to be aligned on 2-byte boundaries. If *align* is false, no
alignment is assumed. The default value is true. If the optional argument
*bigendian* is false, the chunk size is assumed to be in little-endian order.
This is needed for WAVE audio files. The default value is true. If the
optional argument *inclheader* is true, the size given in the chunk header
includes the size of the header. The default value is false.
A :class:`Chunk` object supports the following methods:
+-*/+-*/+-*/+-*/isatty m
isatty()
Returns ``False``.
+-*/+-*/+-*/+-*/read m
read(size=-1)
Read at most *size* bytes from the chunk (less if the read hits the end of
the chunk before obtaining *size* bytes). If the *size* argument is
negative or omitted, read all data until the end of the chunk. The bytes
are returned as a string object. An empty string is returned when the end
of the chunk is encountered immediately.
+-*/+-*/+-*/+-*/skip m
skip()
Skip to the end of the chunk. All further calls to :meth:`read` for the
chunk will return ``''``. If you are not interested in the contents of
the chunk, this method should be called so that the file points to the
start of the next chunk.
+-*/+-*/+-*/+-*/getname m
getname()
Returns the name (ID) of the chunk. This is the first 4 bytes of the
chunk.
+-*/+-*/+-*/+-*/getsize m
getsize()
Returns the size of the chunk.
+-*/+-*/+-*/+-*/close m
close()
Close and skip to the end of the chunk. This does not close the
underlying file.
+-*/+-*/+-*/+-*/seek m
seek(pos, whence=0)
Set the chunk's current position. The *whence* argument is optional and
defaults to ``0`` (absolute file positioning); other values are ``1``
(seek relative to the current position) and ``2`` (seek relative to the
file's end). There is no return value. If the underlying file does not
allow seek, only forward seeks are allowed.
+-*/+-*/+-*/+-*/tell m
tell()
Return the current position into the chunk.
+-*/+-*/ossaudiodev p Access to OSS-compatible audio devices.
+-*/+-*/+-*/openmixer f
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 :envvar:`MIXERDEV` for a device to use. If not
found, it falls back to :file:`/dev/mixer`.
+-*/+-*/+-*/open f
open([device, ]mode)
Open an audio device and return an OSS audio device object. This object
supports many file-like methods, such as :meth:`read`, :meth:`write`, and
:meth:`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 :envvar:`AUDIODEV` for a device
to use. If not found, it falls back to :file:`/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 :mod:`linuxaudiodev` module which :mod:`ossaudiodev` supersedes.
.. XXX it might also be motivated
by my unfounded-but-still-possibly-true belief that the default
audio device varies unpredictably across operating systems. -GW
+-*/+-*/+-*/OSSAudioError e
OSSAudioError
This exception is raised on certain errors. The argument is a string describing
what went wrong.
(If :mod:`ossaudiodev` receives an error from a system call such as
:c:func:`open`, :c:func:`write`, or :c:func:`ioctl`, it raises :exc:`IOError`.
Errors detected directly by :mod:`ossaudiodev` result in :exc:`OSSAudioError`.)
(For backwards compatibility, the exception class is also available as
``ossaudiodev.error``.)
+-*/+-*/+-*/oss_mixer_device _
+-*/+-*/+-*/+-*/fileno m
fileno()
Returns the file handle number of the open mixer device file.
+-*/+-*/+-*/+-*/set m
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 :exc:`OSSAudioError` if an invalid mixer control was specified, or if the
specified volumes were out-of-range.
+-*/+-*/+-*/+-*/get m
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 :exc:`OSSAudioError` if an invalid control was is specified, or
:exc:`IOError` if an unsupported control is specified.
+-*/+-*/+-*/+-*/reccontrols m
reccontrols()
Returns a bitmask specifying the mixer controls that may be used to record. See
the code example for :meth:`controls` for an example of reading from a bitmask.
+-*/+-*/+-*/+-*/controls m
controls()
This method returns a bitmask specifying the available mixer controls ("Control"
being a specific mixable "channel", such as :const:`SOUND_MIXER_PCM` or
:const:`SOUND_MIXER_SYNTH`). This bitmask indicates a subset of all available
mixer controls---the :const:`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 :const:`SOUND_MIXER_VOLUME` (master volume) and
:const:`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, :const:`SOUND_MIXER_VOLUME` does not exist.
+-*/+-*/+-*/+-*/get_recsrc m
get_recsrc()
This method returns a bitmask indicating which control(s) are currently being
used as a recording source.
+-*/+-*/+-*/+-*/set_recsrc m
set_recsrc(bitmask)
Call this function to specify a recording source. Returns a bitmask indicating
the new recording source (or sources) if successful; raises :exc:`IOError` if an
invalid source was specified. To set the current recording source to the
microphone input::
mixer.setrecsrc (1 << ossaudiodev.SOUND_MIXER_MIC)
+-*/+-*/+-*/+-*/close m
close()
This method closes the open mixer device file. Any further attempts to use the
mixer after this file is closed will raise an :exc:`IOError`.
+-*/+-*/+-*/+-*/stereocontrols m
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
:meth:`controls` to determine which).
See the code example for the :meth:`controls` function for an example of getting
data from a bitmask.
+-*/+-*/+-*/oss_audio_device _
+-*/+-*/+-*/+-*/mode d
mode
The I/O mode for the file, either ``"r"``, ``"rw"``, or ``"w"``.
+-*/+-*/+-*/+-*/closed d
closed
Boolean indicating whether the device has been closed.
+-*/+-*/+-*/+-*/name d
name
String containing the name of the device file.
+-*/+-*/+-*/+-*/reset m
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 :meth:`reset`.
+-*/+-*/+-*/+-*/setparameters m
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 :meth:`setfmt`, :meth:`channels`, and
:meth:`speed` methods. If *strict* is true, :meth:`setparameters` checks to
see if each parameter was actually set to the requested value, and raises
:exc:`OSSAudioError` 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 :meth:`setfmt`,
:meth:`channels`, and :meth:`speed`).
For example, ::
(fmt, channels, rate) = dsp.setparameters(fmt, channels, rate)
is equivalent to ::
fmt = dsp.setfmt(fmt)
channels = dsp.channels(channels)
rate = dsp.rate(channels)
+-*/+-*/+-*/+-*/obufcount m
obufcount()
Returns the number of samples that are in the hardware buffer yet to be played.
+-*/+-*/+-*/+-*/writeall m
writeall(data)
Write the entire Python string *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 :meth:`write`; :meth:`writeall`
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.
+-*/+-*/+-*/+-*/fileno m
fileno()
Return the file descriptor associated with the device.
+-*/+-*/+-*/+-*/read m
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 :func:`read` until the entire requested amount of data is
available.
+-*/+-*/+-*/+-*/nonblock m
nonblock()
Put the device into non-blocking mode. Once in non-blocking mode, there is no
way to return it to blocking mode.
+-*/+-*/+-*/+-*/sync m
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 :meth:`sync`.
+-*/+-*/+-*/+-*/setfmt m
setfmt(format)
Try to set the current audio format to *format*---see :meth:`getfmts` 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 :const:`AFMT_QUERY`.
+-*/+-*/+-*/+-*/write m
write(data)
Write the Python string *data* to the audio device and return the number of
bytes written. If the audio device is in blocking mode (the default), the
entire string 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 :meth:`writeall`.
+-*/+-*/+-*/+-*/getfmts m
getfmts()
Return a bitmask of the audio output formats supported by the soundcard. Some
of the formats supported by OSS are:
+-------------------------+---------------------------------------------+
| Format | Description |
+=========================+=============================================+
| :const:`AFMT_MU_LAW` | a logarithmic encoding (used by Sun ``.au`` |
| | files and :file:`/dev/audio`) |
+-------------------------+---------------------------------------------+
| :const:`AFMT_A_LAW` | a logarithmic encoding |
+-------------------------+---------------------------------------------+
| :const:`AFMT_IMA_ADPCM` | a 4:1 compressed format defined by the |
| | Interactive Multimedia Association |
+-------------------------+---------------------------------------------+
| :const:`AFMT_U8` | Unsigned, 8-bit audio |
+-------------------------+---------------------------------------------+
| :const:`AFMT_S16_LE` | Signed, 16-bit audio, little-endian byte |
| | order (as used by Intel processors) |
+-------------------------+---------------------------------------------+
| :const:`AFMT_S16_BE` | Signed, 16-bit audio, big-endian byte order |
| | (as used by 68k, PowerPC, Sparc) |
+-------------------------+---------------------------------------------+
| :const:`AFMT_S8` | Signed, 8 bit audio |
+-------------------------+---------------------------------------------+
| :const:`AFMT_U16_LE` | Unsigned, 16-bit little-endian audio |
+-------------------------+---------------------------------------------+
| :const:`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 :const:`AFMT_U8`; the most common format used today is
:const:`AFMT_S16_LE`.
+-*/+-*/+-*/+-*/obuffree m
obuffree()
Returns the number of samples that could be queued into the hardware buffer to
be played without blocking.
+-*/+-*/+-*/+-*/close m
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.
+-*/+-*/+-*/+-*/post m
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.
+-*/+-*/+-*/+-*/bufsize m
bufsize()
Returns the size of the hardware buffer, in samples.
+-*/+-*/+-*/+-*/speed m
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:
+-------+-------------------------------------------+
| Rate | Description |
+=======+===========================================+
| 8000 | default rate for :file:`/dev/audio` |
+-------+-------------------------------------------+
| 11025 | speech recording |
+-------+-------------------------------------------+
| 22050 | |
+-------+-------------------------------------------+
| 44100 | CD quality audio (at 16 bits/sample and 2 |
| | channels) |
+-------+-------------------------------------------+
| 96000 | DVD quality audio (at 24 bits/sample) |
+-------+-------------------------------------------+
+-*/+-*/+-*/+-*/channels m
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.
+-*/+-*/sunau p Provide an interface to the Sun AU sound format.
+-*/+-*/+-*/openfp f
openfp(file, mode)
A synonym for :func:`.open`, maintained for backwards compatibility.
+-*/+-*/+-*/open f
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'``
Read only mode.
``'w'``
Write only mode.
Note that it does not allow read/write files.
A *mode* of ``'r'`` returns a :class:`AU_read` object, while a *mode* of ``'w'``
or ``'wb'`` returns a :class:`AU_write` object.
+-*/+-*/+-*/AUDIO_FILE_ENCODING_ADPCM_G722 d
AUDIO_FILE_ENCODING_ADPCM_G722
Additional known values of the encoding field from the AU header, but which are
not supported by this module.
+-*/+-*/+-*/AUDIO_FILE_ENCODING_LINEAR_8 d
AUDIO_FILE_ENCODING_LINEAR_8
Values of the encoding field from the AU header which are supported by this
module.
+-*/+-*/+-*/AUDIO_FILE_ENCODING_ADPCM_G723_5 d
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.
+-*/+-*/+-*/AUDIO_FILE_ENCODING_ADPCM_G723_3 d
AUDIO_FILE_ENCODING_ADPCM_G723_3
Additional known values of the encoding field from the AU header, but which are
not supported by this module.
+-*/+-*/+-*/AUDIO_FILE_MAGIC d
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.
+-*/+-*/+-*/AUDIO_FILE_ENCODING_ALAW_8 d
AUDIO_FILE_ENCODING_ALAW_8
Values of the encoding field from the AU header which are supported by this
module.
+-*/+-*/+-*/AUDIO_FILE_ENCODING_LINEAR_16 d
AUDIO_FILE_ENCODING_LINEAR_16
Values of the encoding field from the AU header which are supported by this
module.
+-*/+-*/+-*/AUDIO_FILE_ENCODING_LINEAR_32 d
AUDIO_FILE_ENCODING_LINEAR_32
Values of the encoding field from the AU header which are supported by this
module.
+-*/+-*/+-*/AUDIO_FILE_ENCODING_DOUBLE d
AUDIO_FILE_ENCODING_DOUBLE
Additional known values of the encoding field from the AU header, but which are
not supported by this module.
+-*/+-*/+-*/AUDIO_FILE_ENCODING_FLOAT d
AUDIO_FILE_ENCODING_FLOAT
Additional known values of the encoding field from the AU header, but which are
not supported by this module.
+-*/+-*/+-*/AUDIO_FILE_ENCODING_MULAW_8 d
AUDIO_FILE_ENCODING_MULAW_8
Values of the encoding field from the AU header which are supported by this
module.
+-*/+-*/+-*/AUDIO_FILE_ENCODING_LINEAR_24 d
AUDIO_FILE_ENCODING_LINEAR_24
Values of the encoding field from the AU header which are supported by this
module.
+-*/+-*/+-*/AUDIO_FILE_ENCODING_ADPCM_G721 d
AUDIO_FILE_ENCODING_ADPCM_G721
Additional known values of the encoding field from the AU header, but which are
not supported by this module.
+-*/+-*/+-*/Error e
Error
An error raised when something is impossible because of Sun AU specs or
implementation deficiency.
+-*/+-*/+-*/AU_read _
+-*/+-*/+-*/+-*/getcompname m
getcompname()
Human-readable version of :meth:`getcomptype`. The supported types have the
respective names ``'CCITT G.711 u-law'``, ``'CCITT G.711 A-law'`` and ``'not
compressed'``.
+-*/+-*/+-*/+-*/getframerate m
getframerate()
Returns sampling frequency.
+-*/+-*/+-*/+-*/getparams m
getparams()
Returns a tuple ``(nchannels, sampwidth, framerate, nframes, comptype,
compname)``, equivalent to output of the :meth:`get\*` methods.
+-*/+-*/+-*/+-*/setpos m
setpos(pos)
Set the file pointer to the specified position. Only values returned from
:meth:`tell` should be used for *pos*.
+-*/+-*/+-*/+-*/getnframes m
getnframes()
Returns number of audio frames.
+-*/+-*/+-*/+-*/getmarkers m
getmarkers()
Returns ``None``.
+-*/+-*/+-*/+-*/getmark m
getmark(id)
Raise an error.
+-*/+-*/+-*/+-*/getcomptype m
getcomptype()
Returns compression type. Supported compression types are ``'ULAW'``, ``'ALAW'``
and ``'NONE'``.
+-*/+-*/+-*/+-*/rewind m
rewind()
Rewind the file pointer to the beginning of the audio stream.
+-*/+-*/+-*/+-*/readframes m
readframes(n)
Reads and returns at most *n* frames of audio, as a string of bytes. The data
will be returned in linear format. If the original data is in u-LAW format, it
will be converted.
+-*/+-*/+-*/+-*/close m
close()
Close the stream, and make the instance unusable. (This is called automatically
on deletion.)
+-*/+-*/+-*/+-*/tell m
tell()
Return current file pointer position. Note that the returned value has nothing
to do with the actual position in the file.
+-*/+-*/+-*/+-*/getnchannels m
getnchannels()
Returns number of audio channels (1 for mone, 2 for stereo).
+-*/+-*/+-*/+-*/getsampwidth m
getsampwidth()
Returns sample width in bytes.
+-*/+-*/+-*/AU_write _
+-*/+-*/+-*/+-*/setsampwidth m
setsampwidth(n)
Set the sample width (in bytes.)
+-*/+-*/+-*/+-*/setnframes m
setnframes(n)
Set the number of frames. This can be later changed, when and if more frames
are written.
+-*/+-*/+-*/+-*/writeframesraw m
writeframesraw(data)
Write audio frames, without correcting *nframes*.
+-*/+-*/+-*/+-*/setframerate m
setframerate(n)
Set the frame rate.
+-*/+-*/+-*/+-*/writeframes m
writeframes(data)
Write audio frames and make sure *nframes* is correct.
+-*/+-*/+-*/+-*/setnchannels m
setnchannels(n)
Set the number of channels.
+-*/+-*/+-*/+-*/close m
close()
Make sure *nframes* is correct, and close the file.
This method is called upon deletion.
+-*/+-*/+-*/+-*/setparams m
setparams(tuple)
The *tuple* should be ``(nchannels, sampwidth, framerate, nframes, comptype,
compname)``, with values valid for the :meth:`set\*` methods. Set all
parameters.
+-*/+-*/+-*/+-*/tell m
tell()
Return current position in the file, with the same disclaimer for the
:meth:`AU_read.tell` and :meth:`AU_read.setpos` methods.
+-*/+-*/+-*/+-*/setcomptype m
setcomptype(type, name)
Set the compression type and description. Only ``'NONE'`` and ``'ULAW'`` are
supported on output.
+-*/+-*/wave p Provide an interface to the WAV sound format.
+-*/+-*/+-*/openfp f
openfp(file, mode)
A synonym for :func:`.open`, maintained for backwards compatibility.
+-*/+-*/+-*/open f
open(file, mode=None)
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'``, ``'rb'``
Read only mode.
``'w'``, ``'wb'``
Write only mode.
Note that it does not allow read/write WAV files.
A *mode* of ``'r'`` or ``'rb'`` returns a :class:`Wave_read` object, while a
*mode* of ``'w'`` or ``'wb'`` returns a :class:`Wave_write` object. If
*mode* is omitted and a file-like object is passed as *file*, ``file.mode``
is used as the default value for *mode* (the ``'b'`` flag is still added if
necessary).
If you pass in a file-like object, the wave object will not close it when its
:meth:`close` method is called; it is the caller's responsibility to close
the file object.
+-*/+-*/+-*/Error e
Error
An error raised when something is impossible because it violates the WAV
specification or hits an implementation deficiency.
+-*/+-*/+-*/Wave_write _
+-*/+-*/+-*/+-*/setsampwidth m
setsampwidth(n)
Set the sample width to *n* bytes.
+-*/+-*/+-*/+-*/setnchannels m
setnchannels(n)
Set the number of channels.
+-*/+-*/+-*/+-*/writeframesraw m
writeframesraw(data)
Write audio frames, without correcting *nframes*.
+-*/+-*/+-*/+-*/setframerate m
setframerate(n)
Set the frame rate to *n*.
.. versionchanged:: 3.2
A non-integral input to this method is rounded to the nearest
integer.
+-*/+-*/+-*/+-*/writeframes m
writeframes(data)
Write audio frames and make sure *nframes* is correct.
+-*/+-*/+-*/+-*/setnframes m
setnframes(n)
Set the number of frames to *n*. This will be changed later if more frames are
written.
+-*/+-*/+-*/+-*/close m
close()
Make sure *nframes* is correct, and close the file if it was opened by
:mod:`wave`. This method is called upon object collection.
+-*/+-*/+-*/+-*/setparams m
setparams(tuple)
The *tuple* should be ``(nchannels, sampwidth, framerate, nframes, comptype,
compname)``, with values valid for the :meth:`set\*` methods. Sets all
parameters.
+-*/+-*/+-*/+-*/tell m
tell()
Return current position in the file, with the same disclaimer for the
:meth:`Wave_read.tell` and :meth:`Wave_read.setpos` methods.
+-*/+-*/+-*/+-*/setcomptype m
setcomptype(type, name)
Set the compression type and description. At the moment, only compression type
``NONE`` is supported, meaning no compression.
+-*/+-*/+-*/Wave_read _
+-*/+-*/+-*/+-*/getcompname m
getcompname()
Human-readable version of :meth:`getcomptype`. Usually ``'not compressed'``
parallels ``'NONE'``.
+-*/+-*/+-*/+-*/getsampwidth m
getsampwidth()
Returns sample width in bytes.
+-*/+-*/+-*/+-*/getparams m
getparams()
Returns a tuple ``(nchannels, sampwidth, framerate, nframes, comptype,
compname)``, equivalent to output of the :meth:`get\*` methods.
+-*/+-*/+-*/+-*/setpos m
setpos(pos)
Set the file pointer to the specified position.
+-*/+-*/+-*/+-*/getnframes m
getnframes()
Returns number of audio frames.
+-*/+-*/+-*/+-*/getmarkers m
getmarkers()
Returns ``None``.
+-*/+-*/+-*/+-*/getmark m
getmark(id)
Raise an error.
+-*/+-*/+-*/+-*/getcomptype m
getcomptype()
Returns compression type (``'NONE'`` is the only supported type).
+-*/+-*/+-*/+-*/rewind m
rewind()
Rewind the file pointer to the beginning of the audio stream.
+-*/+-*/+-*/+-*/readframes m
readframes(n)
Reads and returns at most *n* frames of audio, as a string of bytes.
+-*/+-*/+-*/+-*/close m
close()
Close the stream if it was opened by :mod:`wave`, and make the instance
unusable. This is called automatically on object collection.
+-*/+-*/+-*/+-*/tell m
tell()
Return current file pointer position.
+-*/+-*/+-*/+-*/getnchannels m
getnchannels()
Returns number of audio channels (``1`` for mono, ``2`` for stereo).
+-*/+-*/+-*/+-*/getframerate m
getframerate()
Returns sampling frequency.
+-*/frameworks _ Program Frameworks
+-*/+-*/cmd p Build line-oriented command interpreters.
+-*/+-*/+-*/Cmd c
Cmd(completekey='tab', stdin=None, stdout=None)
A :class:`Cmd` instance or subclass instance is a line-oriented interpreter
framework. There is no good reason to instantiate :class:`Cmd` itself; rather,
it's useful as a superclass of an interpreter class you define yourself in order
to inherit :class:`Cmd`'s methods and encapsulate action methods.
The optional argument *completekey* is the :mod:`readline` name of a completion
key; it defaults to :kbd:`Tab`. If *completekey* is not :const:`None` and
:mod:`readline` is available, command completion is done automatically.
The optional arguments *stdin* and *stdout* specify the input and output file
objects that the Cmd instance or subclass instance will use for input and
output. If not specified, they will default to :data:`sys.stdin` and
:data:`sys.stdout`.
If you want a given *stdin* to be used, make sure to set the instance's
:attr:`use_rawinput` attribute to ``False``, otherwise *stdin* will be
ignored.
+-*/+-*/+-*/+-*/undoc_header d
undoc_header
The header to issue if the help output has a section for undocumented commands
(that is, there are :meth:`do_\*` methods without corresponding :meth:`help_\*`
methods).
+-*/+-*/+-*/+-*/prompt d
prompt
The prompt issued to solicit input.
+-*/+-*/+-*/+-*/ruler d
ruler
The character used to draw separator lines under the help-message headers. If
empty, no ruler line is drawn. It defaults to ``'='``.
+-*/+-*/+-*/+-*/misc_header d
misc_header
The header to issue if the help output has a section for miscellaneous help
topics (that is, there are :meth:`help_\*` methods without corresponding
:meth:`do_\*` methods).
+-*/+-*/+-*/+-*/lastcmd d
lastcmd
The last nonempty command prefix seen.
+-*/+-*/+-*/+-*/intro d
intro
A string to issue as an intro or banner. May be overridden by giving the
:meth:`cmdloop` method an argument.
+-*/+-*/+-*/+-*/use_rawinput d
use_rawinput
A flag, defaulting to true. If true, :meth:`cmdloop` uses :func:`input` to
display a prompt and read the next command; if false, :meth:`sys.stdout.write`
and :meth:`sys.stdin.readline` are used. (This means that by importing
:mod:`readline`, on systems that support it, the interpreter will automatically
support :program:`Emacs`\ -like line editing and command-history keystrokes.)
+-*/+-*/+-*/+-*/doc_header d
doc_header
The header to issue if the help output has a section for documented commands.
+-*/+-*/+-*/