desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Constructor. When called without arguments, create an unconnected instance. With a hostname argument, it connects the instance; port number and timeout are optional.'
def __init__(self, host=None, port=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
self.debuglevel = DEBUGLEVEL self.host = host self.port = port self.timeout = timeout self.sock = None self.rawq = '' self.irawq = 0 self.cookedq = '' self.eof = 0 self.iacseq = '' self.sb = 0 self.sbdataq = '' self.option_callback = None self._has_poll = hasattr(select, 'poll') if (host is not None): self.open(host, port, timeout)
'Connect to a host. The optional second argument is the port number, which defaults to the standard telnet port (23). Don\'t try to reopen an already connected instance.'
def open(self, host, port=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
self.eof = 0 if (not port): port = TELNET_PORT self.host = host self.port = port self.timeout = timeout self.sock = socket.create_connection((host, port), timeout)
'Destructor -- close the connection.'
def __del__(self):
self.close()
'Print a debug message, when the debug level is > 0. If extra arguments are present, they are substituted in the message using the standard string formatting operator.'
def msg(self, msg, *args):
if (self.debuglevel > 0): print ('Telnet(%s,%s):' % (self.host, self.port)), if args: print (msg % args) else: print msg
'Set the debug level. The higher it is, the more debug output you get (on sys.stdout).'
def set_debuglevel(self, debuglevel):
self.debuglevel = debuglevel
'Close the connection.'
def close(self):
sock = self.sock self.sock = 0 self.eof = 1 self.iacseq = '' self.sb = 0 if sock: sock.close()
'Return the socket object used internally.'
def get_socket(self):
return self.sock
'Return the fileno() of the socket object used internally.'
def fileno(self):
return self.sock.fileno()
'Write a string to the socket, doubling any IAC characters. Can block if the connection is blocked. May raise socket.error if the connection is closed.'
def write(self, buffer):
if (IAC in buffer): buffer = buffer.replace(IAC, (IAC + IAC)) self.msg('send %r', buffer) self.sock.sendall(buffer)
'Read until a given string is encountered or until timeout. When no match is found, return whatever is available instead, possibly the empty string. Raise EOFError if the connection is closed and no cooked data is available.'
def read_until(self, match, timeout=None):
if self._has_poll: return self._read_until_with_poll(match, timeout) else: return self._read_until_with_select(match, timeout)
'Read until a given string is encountered or until timeout. This method uses select.poll() to implement the timeout.'
def _read_until_with_poll(self, match, timeout):
n = len(match) call_timeout = timeout if (timeout is not None): from time import time time_start = time() self.process_rawq() i = self.cookedq.find(match) if (i < 0): poller = select.poll() poll_in_or_priority_flags = (select.POLLIN | select.POLLPRI) poller.register(self, poll_in_or_priority_flags) while ((i < 0) and (not self.eof)): try: ready = poller.poll((None if (timeout is None) else (1000 * call_timeout))) except select.error as e: if (e.errno == errno.EINTR): if (timeout is not None): elapsed = (time() - time_start) call_timeout = (timeout - elapsed) continue raise for (fd, mode) in ready: if (mode & poll_in_or_priority_flags): i = max(0, (len(self.cookedq) - n)) self.fill_rawq() self.process_rawq() i = self.cookedq.find(match, i) if (timeout is not None): elapsed = (time() - time_start) if (elapsed >= timeout): break call_timeout = (timeout - elapsed) poller.unregister(self) if (i >= 0): i = (i + n) buf = self.cookedq[:i] self.cookedq = self.cookedq[i:] return buf return self.read_very_lazy()
'Read until a given string is encountered or until timeout. The timeout is implemented using select.select().'
def _read_until_with_select(self, match, timeout=None):
n = len(match) self.process_rawq() i = self.cookedq.find(match) if (i >= 0): i = (i + n) buf = self.cookedq[:i] self.cookedq = self.cookedq[i:] return buf s_reply = ([self], [], []) s_args = s_reply if (timeout is not None): s_args = (s_args + (timeout,)) from time import time time_start = time() while ((not self.eof) and (select.select(*s_args) == s_reply)): i = max(0, (len(self.cookedq) - n)) self.fill_rawq() self.process_rawq() i = self.cookedq.find(match, i) if (i >= 0): i = (i + n) buf = self.cookedq[:i] self.cookedq = self.cookedq[i:] return buf if (timeout is not None): elapsed = (time() - time_start) if (elapsed >= timeout): break s_args = (s_reply + ((timeout - elapsed),)) return self.read_very_lazy()
'Read all data until EOF; block until connection closed.'
def read_all(self):
self.process_rawq() while (not self.eof): self.fill_rawq() self.process_rawq() buf = self.cookedq self.cookedq = '' return buf
'Read at least one byte of cooked data unless EOF is hit. Return \'\' if EOF is hit. Block if no data is immediately available.'
def read_some(self):
self.process_rawq() while ((not self.cookedq) and (not self.eof)): self.fill_rawq() self.process_rawq() buf = self.cookedq self.cookedq = '' return buf
'Read everything that\'s possible without blocking in I/O (eager). Raise EOFError if connection closed and no cooked data available. Return \'\' if no cooked data available otherwise. Don\'t block unless in the midst of an IAC sequence.'
def read_very_eager(self):
self.process_rawq() while ((not self.eof) and self.sock_avail()): self.fill_rawq() self.process_rawq() return self.read_very_lazy()
'Read readily available data. Raise EOFError if connection closed and no cooked data available. Return \'\' if no cooked data available otherwise. Don\'t block unless in the midst of an IAC sequence.'
def read_eager(self):
self.process_rawq() while ((not self.cookedq) and (not self.eof) and self.sock_avail()): self.fill_rawq() self.process_rawq() return self.read_very_lazy()
'Process and return data that\'s already in the queues (lazy). Raise EOFError if connection closed and no data available. Return \'\' if no cooked data available otherwise. Don\'t block unless in the midst of an IAC sequence.'
def read_lazy(self):
self.process_rawq() return self.read_very_lazy()
'Return any data available in the cooked queue (very lazy). Raise EOFError if connection closed and no data available. Return \'\' if no cooked data available otherwise. Don\'t block.'
def read_very_lazy(self):
buf = self.cookedq self.cookedq = '' if ((not buf) and self.eof and (not self.rawq)): raise EOFError, 'telnet connection closed' return buf
'Return any data available in the SB ... SE queue. Return \'\' if no SB ... SE available. Should only be called after seeing a SB or SE command. When a new SB command is found, old unread SB data will be discarded. Don\'t block.'
def read_sb_data(self):
buf = self.sbdataq self.sbdataq = '' return buf
'Provide a callback function called after each receipt of a telnet option.'
def set_option_negotiation_callback(self, callback):
self.option_callback = callback
'Transfer from raw queue to cooked queue. Set self.eof when connection is closed. Don\'t block unless in the midst of an IAC sequence.'
def process_rawq(self):
buf = ['', ''] try: while self.rawq: c = self.rawq_getchar() if (not self.iacseq): if (c == theNULL): continue if (c == '\x11'): continue if (c != IAC): buf[self.sb] = (buf[self.sb] + c) continue else: self.iacseq += c elif (len(self.iacseq) == 1): if (c in (DO, DONT, WILL, WONT)): self.iacseq += c continue self.iacseq = '' if (c == IAC): buf[self.sb] = (buf[self.sb] + c) else: if (c == SB): self.sb = 1 self.sbdataq = '' elif (c == SE): self.sb = 0 self.sbdataq = (self.sbdataq + buf[1]) buf[1] = '' if self.option_callback: self.option_callback(self.sock, c, NOOPT) else: self.msg(('IAC %d not recognized' % ord(c))) elif (len(self.iacseq) == 2): cmd = self.iacseq[1] self.iacseq = '' opt = c if (cmd in (DO, DONT)): self.msg('IAC %s %d', (((cmd == DO) and 'DO') or 'DONT'), ord(opt)) if self.option_callback: self.option_callback(self.sock, cmd, opt) else: self.sock.sendall(((IAC + WONT) + opt)) elif (cmd in (WILL, WONT)): self.msg('IAC %s %d', (((cmd == WILL) and 'WILL') or 'WONT'), ord(opt)) if self.option_callback: self.option_callback(self.sock, cmd, opt) else: self.sock.sendall(((IAC + DONT) + opt)) except EOFError: self.iacseq = '' self.sb = 0 pass self.cookedq = (self.cookedq + buf[0]) self.sbdataq = (self.sbdataq + buf[1])
'Get next char from raw queue. Block if no data is immediately available. Raise EOFError when connection is closed.'
def rawq_getchar(self):
if (not self.rawq): self.fill_rawq() if self.eof: raise EOFError c = self.rawq[self.irawq] self.irawq = (self.irawq + 1) if (self.irawq >= len(self.rawq)): self.rawq = '' self.irawq = 0 return c
'Fill raw queue from exactly one recv() system call. Block if no data is immediately available. Set self.eof when connection is closed.'
def fill_rawq(self):
if (self.irawq >= len(self.rawq)): self.rawq = '' self.irawq = 0 buf = self.sock.recv(50) self.msg('recv %r', buf) self.eof = (not buf) self.rawq = (self.rawq + buf)
'Test whether data is available on the socket.'
def sock_avail(self):
return (select.select([self], [], [], 0) == ([self], [], []))
'Interaction function, emulates a very dumb telnet client.'
def interact(self):
if (sys.platform == 'win32'): self.mt_interact() return while 1: (rfd, wfd, xfd) = select.select([self, sys.stdin], [], []) if (self in rfd): try: text = self.read_eager() except EOFError: print '*** Connection closed by remote host ***' break if text: sys.stdout.write(text) sys.stdout.flush() if (sys.stdin in rfd): line = sys.stdin.readline() if (not line): break self.write(line)
'Multithreaded version of interact().'
def mt_interact(self):
import thread thread.start_new_thread(self.listener, ()) while 1: line = sys.stdin.readline() if (not line): break self.write(line)
'Helper for mt_interact() -- this executes in the other thread.'
def listener(self):
while 1: try: data = self.read_eager() except EOFError: print '*** Connection closed by remote host ***' return if data: sys.stdout.write(data) else: sys.stdout.flush()
'Read until one from a list of a regular expressions matches. The first argument is a list of regular expressions, either compiled (re.RegexObject instances) or uncompiled (strings). The optional second argument is a timeout, in seconds; default is no timeout. Return a tuple of three items: the index in the list of the first regular expression that matches; the match object returned; and the text read up till and including the match. If EOF is read and no text was read, raise EOFError. Otherwise, when nothing matches, return (-1, None, text) where text is the text received so far (may be the empty string if a timeout happened). If a regular expression ends with a greedy match (e.g. \'.*\') or if more than one expression can match the same input, the results are undeterministic, and may depend on the I/O timing.'
def expect(self, list, timeout=None):
if self._has_poll: return self._expect_with_poll(list, timeout) else: return self._expect_with_select(list, timeout)
'Read until one from a list of a regular expressions matches. This method uses select.poll() to implement the timeout.'
def _expect_with_poll(self, expect_list, timeout=None):
re = None expect_list = expect_list[:] indices = range(len(expect_list)) for i in indices: if (not hasattr(expect_list[i], 'search')): if (not re): import re expect_list[i] = re.compile(expect_list[i]) call_timeout = timeout if (timeout is not None): from time import time time_start = time() self.process_rawq() m = None for i in indices: m = expect_list[i].search(self.cookedq) if m: e = m.end() text = self.cookedq[:e] self.cookedq = self.cookedq[e:] break if (not m): poller = select.poll() poll_in_or_priority_flags = (select.POLLIN | select.POLLPRI) poller.register(self, poll_in_or_priority_flags) while ((not m) and (not self.eof)): try: ready = poller.poll((None if (timeout is None) else (1000 * call_timeout))) except select.error as e: if (e.errno == errno.EINTR): if (timeout is not None): elapsed = (time() - time_start) call_timeout = (timeout - elapsed) continue raise for (fd, mode) in ready: if (mode & poll_in_or_priority_flags): self.fill_rawq() self.process_rawq() for i in indices: m = expect_list[i].search(self.cookedq) if m: e = m.end() text = self.cookedq[:e] self.cookedq = self.cookedq[e:] break if (timeout is not None): elapsed = (time() - time_start) if (elapsed >= timeout): break call_timeout = (timeout - elapsed) poller.unregister(self) if m: return (i, m, text) text = self.read_very_lazy() if ((not text) and self.eof): raise EOFError return ((-1), None, text)
'Read until one from a list of a regular expressions matches. The timeout is implemented using select.select().'
def _expect_with_select(self, list, timeout=None):
re = None list = list[:] indices = range(len(list)) for i in indices: if (not hasattr(list[i], 'search')): if (not re): import re list[i] = re.compile(list[i]) if (timeout is not None): from time import time time_start = time() while 1: self.process_rawq() for i in indices: m = list[i].search(self.cookedq) if m: e = m.end() text = self.cookedq[:e] self.cookedq = self.cookedq[e:] return (i, m, text) if self.eof: break if (timeout is not None): elapsed = (time() - time_start) if (elapsed >= timeout): break s_args = ([self.fileno()], [], [], (timeout - elapsed)) (r, w, x) = select.select(*s_args) if (not r): break self.fill_rawq() text = self.read_very_lazy() if ((not text) and self.eof): raise EOFError return ((-1), None, text)
'Builds a qualified name from a (ns_url, localname) pair'
def _qname(self, name):
if name[0]: if ('http://www.w3.org/XML/1998/namespace' == name[0]): return ('xml:' + name[1]) prefix = self._current_context[name[0]] if prefix: return ((prefix + ':') + name[1]) return name[1]
'Parse an XML document from a URL or an InputSource.'
def parse(self, source):
source = saxutils.prepare_input_source(source) self._source = source self.reset() self._cont_handler.setDocumentLocator(ExpatLocator(self)) xmlreader.IncrementalParser.parse(self, source)
'Creates an exception. The message is required, but the exception is optional.'
def __init__(self, msg, exception=None):
self._msg = msg self._exception = exception Exception.__init__(self, msg)
'Return a message for this exception.'
def getMessage(self):
return self._msg
'Return the embedded exception, or None if there was none.'
def getException(self):
return self._exception
'Create a string representation of the exception.'
def __str__(self):
return self._msg
'Avoids weird error messages if someone does exception[ix] by mistake, since Exception has __getitem__ defined.'
def __getitem__(self, ix):
raise AttributeError('__getitem__')
'Creates the exception. The exception parameter is allowed to be None.'
def __init__(self, msg, exception, locator):
SAXException.__init__(self, msg, exception) self._locator = locator self._systemId = self._locator.getSystemId() self._colnum = self._locator.getColumnNumber() self._linenum = self._locator.getLineNumber()
'The column number of the end of the text where the exception occurred.'
def getColumnNumber(self):
return self._colnum
'The line number of the end of the text where the exception occurred.'
def getLineNumber(self):
return self._linenum
'Get the public identifier of the entity where the exception occurred.'
def getPublicId(self):
return self._locator.getPublicId()
'Get the system identifier of the entity where the exception occurred.'
def getSystemId(self):
return self._systemId
'Create a string representation of the exception.'
def __str__(self):
sysid = self.getSystemId() if (sysid is None): sysid = '<unknown>' linenum = self.getLineNumber() if (linenum is None): linenum = '?' colnum = self.getColumnNumber() if (colnum is None): colnum = '?' return ('%s:%s:%s: %s' % (sysid, linenum, colnum, self._msg))
'Parse an XML document from a system identifier or an InputSource.'
def parse(self, source):
raise NotImplementedError('This method must be implemented!')
'Returns the current ContentHandler.'
def getContentHandler(self):
return self._cont_handler
'Registers a new object to receive document content events.'
def setContentHandler(self, handler):
self._cont_handler = handler
'Returns the current DTD handler.'
def getDTDHandler(self):
return self._dtd_handler
'Register an object to receive basic DTD-related events.'
def setDTDHandler(self, handler):
self._dtd_handler = handler
'Returns the current EntityResolver.'
def getEntityResolver(self):
return self._ent_handler
'Register an object to resolve external entities.'
def setEntityResolver(self, resolver):
self._ent_handler = resolver
'Returns the current ErrorHandler.'
def getErrorHandler(self):
return self._err_handler
'Register an object to receive error-message events.'
def setErrorHandler(self, handler):
self._err_handler = handler
'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.'
def setLocale(self, locale):
raise SAXNotSupportedException('Locale support not implemented')
'Looks up and returns the state of a SAX2 feature.'
def getFeature(self, name):
raise SAXNotRecognizedException(("Feature '%s' not recognized" % name))
'Sets the state of a SAX2 feature.'
def setFeature(self, name, state):
raise SAXNotRecognizedException(("Feature '%s' not recognized" % name))
'Looks up and returns the value of a SAX2 property.'
def getProperty(self, name):
raise SAXNotRecognizedException(("Property '%s' not recognized" % name))
'Sets the value of a SAX2 property.'
def setProperty(self, name, value):
raise SAXNotRecognizedException(("Property '%s' not recognized" % name))
'This method gives the raw XML data in the data parameter to the parser and makes it parse the data, emitting the corresponding events. It is allowed for XML constructs to be split across several calls to feed. feed may raise SAXException.'
def feed(self, data):
raise NotImplementedError('This method must be implemented!')
'This method is called by the parse implementation to allow the SAX 2.0 driver to prepare itself for parsing.'
def prepareParser(self, source):
raise NotImplementedError('prepareParser must be overridden!')
'This method is called when the entire XML document has been passed to the parser through the feed method, to notify the parser that there are no more data. This allows the parser to do the final checks on the document and empty the internal data buffer. The parser will not be ready to parse another document until the reset method has been called. close may raise SAXException.'
def close(self):
raise NotImplementedError('This method must be implemented!')
'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.'
def reset(self):
raise NotImplementedError('This method must be implemented!')
'Return the column number where the current event ends.'
def getColumnNumber(self):
return (-1)
'Return the line number where the current event ends.'
def getLineNumber(self):
return (-1)
'Return the public identifier for the current event.'
def getPublicId(self):
return None
'Return the system identifier for the current event.'
def getSystemId(self):
return None
'Sets the public identifier of this InputSource.'
def setPublicId(self, public_id):
self.__public_id = public_id
'Returns the public identifier of this InputSource.'
def getPublicId(self):
return self.__public_id
'Sets the system identifier of this InputSource.'
def setSystemId(self, system_id):
self.__system_id = system_id
'Returns the system identifier of this InputSource.'
def getSystemId(self):
return self.__system_id
'Sets the character encoding of this 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 InputSource is ignored if the InputSource also contains a character stream.'
def setEncoding(self, encoding):
self.__encoding = encoding
'Get the character encoding of this InputSource.'
def getEncoding(self):
return self.__encoding
'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.'
def setByteStream(self, bytefile):
self.__bytefile = bytefile
'Get the byte stream for this input source. The getEncoding method will return the character encoding for this byte stream, or None if unknown.'
def getByteStream(self):
return self.__bytefile
'Set the character stream for this input source. (The stream must be a Python 2.0 Unicode-wrapped file-like that performs conversion to Unicode 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.'
def setCharacterStream(self, charfile):
self.__charfile = charfile
'Get the character stream for this input source.'
def getCharacterStream(self):
return self.__charfile
'Non-NS-aware implementation. attrs should be of the form {name : value}.'
def __init__(self, attrs):
self._attrs = attrs
'NS-aware implementation. attrs should be of the form {(ns_uri, lname): value, ...}. qnames of the form {(ns_uri, lname): qname, ...}.'
def __init__(self, attrs, qnames):
self._attrs = attrs self._qnames = qnames
'Handle a recoverable error.'
def error(self, exception):
raise exception
'Handle a non-recoverable error.'
def fatalError(self, exception):
raise exception
'Handle a warning.'
def warning(self, exception):
print exception
'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.'
def setDocumentLocator(self, locator):
self._locator = locator
'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.'
def resolveEntity(self, publicId, systemId):
return systemId
'Create a new parser object.'
def createParser(self):
return expat.ParserCreate()
'Return the parser object, creating a new one if needed.'
def getParser(self):
if (not self._parser): self._parser = self.createParser() self._intern_setdefault = self._parser.intern.setdefault self._parser.buffer_text = True self._parser.ordered_attributes = True self._parser.specified_attributes = True self.install(self._parser) return self._parser
'Free all data structures used during DOM construction.'
def reset(self):
self.document = theDOMImplementation.createDocument(EMPTY_NAMESPACE, None, None) self.curNode = self.document self._elem_info = self.document._elem_info self._cdata = False
'Install the callbacks needed to build the DOM into the parser.'
def install(self, parser):
parser.StartDoctypeDeclHandler = self.start_doctype_decl_handler parser.StartElementHandler = self.first_element_handler parser.EndElementHandler = self.end_element_handler parser.ProcessingInstructionHandler = self.pi_handler if self._options.entities: parser.EntityDeclHandler = self.entity_decl_handler parser.NotationDeclHandler = self.notation_decl_handler if self._options.comments: parser.CommentHandler = self.comment_handler if self._options.cdata_sections: parser.StartCdataSectionHandler = self.start_cdata_section_handler parser.EndCdataSectionHandler = self.end_cdata_section_handler parser.CharacterDataHandler = self.character_data_handler_cdata else: parser.CharacterDataHandler = self.character_data_handler parser.ExternalEntityRefHandler = self.external_entity_ref_handler parser.XmlDeclHandler = self.xml_decl_handler parser.ElementDeclHandler = self.element_decl_handler parser.AttlistDeclHandler = self.attlist_decl_handler
'Parse a document from a file object, returning the document node.'
def parseFile(self, file):
parser = self.getParser() first_buffer = True try: while 1: buffer = file.read((16 * 1024)) if (not buffer): break parser.Parse(buffer, 0) if (first_buffer and self.document.documentElement): self._setup_subset(buffer) first_buffer = False parser.Parse('', True) except ParseEscape: pass doc = self.document self.reset() self._parser = None return doc
'Parse a document from a string, returning the document node.'
def parseString(self, string):
parser = self.getParser() try: parser.Parse(string, True) self._setup_subset(string) except ParseEscape: pass doc = self.document self.reset() self._parser = None return doc
'Load the internal subset if there might be one.'
def _setup_subset(self, buffer):
if self.document.doctype: extractor = InternalSubsetExtractor() extractor.parseString(buffer) subset = extractor.getSubset() self.document.doctype.internalSubset = subset
'Parse a document fragment from a file object, returning the fragment node.'
def parseFile(self, file):
return self.parseString(file.read())
'Parse a document fragment from a string, returning the fragment node.'
def parseString(self, string):
self._source = string parser = self.getParser() doctype = self.originalDocument.doctype ident = '' if doctype: subset = (doctype.internalSubset or self._getDeclarations()) if doctype.publicId: ident = ('PUBLIC "%s" "%s"' % (doctype.publicId, doctype.systemId)) elif doctype.systemId: ident = ('SYSTEM "%s"' % doctype.systemId) else: subset = '' nsattrs = self._getNSattrs() document = (_FRAGMENT_BUILDER_TEMPLATE % (ident, subset, nsattrs)) try: parser.Parse(document, 1) except: self.reset() raise fragment = self.fragment self.reset() return fragment
'Re-create the internal subset from the DocumentType node. This is only needed if we don\'t already have the internalSubset as a string.'
def _getDeclarations(self):
doctype = self.context.ownerDocument.doctype s = '' if doctype: for i in range(doctype.notations.length): notation = doctype.notations.item(i) if s: s = (s + '\n ') s = ('%s<!NOTATION %s' % (s, notation.nodeName)) if notation.publicId: s = ('%s PUBLIC "%s"\n "%s">' % (s, notation.publicId, notation.systemId)) else: s = ('%s SYSTEM "%s">' % (s, notation.systemId)) for i in range(doctype.entities.length): entity = doctype.entities.item(i) if s: s = (s + '\n ') s = ('%s<!ENTITY %s' % (s, entity.nodeName)) if entity.publicId: s = ('%s PUBLIC "%s"\n "%s"' % (s, entity.publicId, entity.systemId)) elif entity.systemId: s = ('%s SYSTEM "%s"' % (s, entity.systemId)) else: s = ('%s "%s"' % (s, entity.firstChild.data)) if entity.notationName: s = ('%s NOTATION %s' % (s, entity.notationName)) s = (s + '>') return s
'Create a new namespace-handling parser.'
def createParser(self):
parser = expat.ParserCreate(namespace_separator=' ') parser.namespace_prefixes = True return parser
'Insert the namespace-handlers onto the parser.'
def install(self, parser):
ExpatBuilder.install(self, parser) if self._options.namespace_declarations: parser.StartNamespaceDeclHandler = self.start_namespace_decl_handler
'Push this namespace declaration on our storage.'
def start_namespace_decl_handler(self, prefix, uri):
self._ns_ordered_prefixes.append((prefix, uri))
'Return string of namespace attributes from this element and ancestors.'
def _getNSattrs(self):
attrs = '' context = self.context L = [] while context: if hasattr(context, '_ns_prefix_uri'): for (prefix, uri) in context._ns_prefix_uri.items(): if (prefix in L): continue L.append(prefix) if prefix: declname = ('xmlns:' + prefix) else: declname = 'xmlns' if attrs: attrs = ("%s\n %s='%s'" % (attrs, declname, uri)) else: attrs = (" %s='%s'" % (declname, uri)) context = context.parentNode return attrs
'Return the internal subset as a string.'
def getSubset(self):
return self.subset
'clear(): Explicitly release parsing structures'
def clear(self):
self.document = None
'Fallback replacement for getEvent() using the standard SAX2 interface, which means we slurp the SAX events into memory (no performance gain, but we are compatible to all SAX parsers).'
def _slurp(self):
self.parser.parse(self.stream) self.getEvent = self._emit return self._emit()
'Fallback replacement for getEvent() that emits the events that _slurp() read previously.'
def _emit(self):
rc = self.pulldom.firstEvent[1][0] self.pulldom.firstEvent[1] = self.pulldom.firstEvent[1][1] return rc