Search code examples
pythonxmllibxml2

How can I turn off error printing in libxml2.parseDoc?


When using the library, I expect an exception for bad input, but I do not want it to start printing things to stderr. How can I configure it to not print anything?

Here's an example from the REPL of what I am talking about:

>>> import libxml2
>>> try:
...     libxml2.parseDoc('junk')
... except:
...     pass
... 
Entity: line 1: parser error : Start tag expected, '<' not found
junk
^
>>> 

With that code I expect to see nothing printed out. I found this SO post about a similar issue with the c++ xmllib2, but I don't see a way to do that with the python version.


Solution

  • You can disable error logging for libxml2 by registering a silent error handler:

    def noerr(ctx, str):
        pass
    
    libxml2.registerErrorHandler(noerr, None)
    

    Source: http://xmlsoft.org/python.html