#!/usr/bin/env python
import sys
from lxml import etree

class XMLWriter():

  def __init__(self):

    self.Output = XMLWriter.FileLikeOutput()

    self.Writer = self.__OuterXMLSerialiserCoRoutine()
    self.Writer.next()

  class FileLikeOutput():

    def write(self, String):
      # This exception is masked by lxml, which
      # generates a lxml.etree.SerialisationError in stead.
      sys.stderr.write('<OOPS!>')
      raise ValueError('Just a random exception, for testing.')

  def __OuterXMLSerialiserCoRoutine(self):
    with etree.xmlfile(self.Output, encoding='utf-8') as Writer:
      Writer.write_declaration()
      with Writer.element('outer'):
        # This triggers a call to FileLikeOutput.write(), but the
        # exception is eaten by lxml. We will just happily continue.
        Writer.flush()
        try:
          while True:
            Element = (yield)
            # This write will trigger lxml.etree.SerialisationError: IO_FLUSH
            Writer.write(Element, pretty_print=True)
            Writer.flush()
        except GeneratorExit:
          pass

  def RunTest(self):
    self.Writer.send(etree.Element('inner', {}))

MyWriter = XMLWriter()
MyWriter.RunTest()