TypeError: setDocumentLocator() missing 1 required positional argument: 'locator'

TypeError: setDocumentLocator() missing 1 required positional argument: 'locator'

我得到一个错误运行以下代码:

#!/usr/bin/env python

from xml import sax
import sys


class MySaxHandler(sax.ContentHandler, object):

    def startElement(self, name, attrs):
        print(name, attrs)

if __name__ == '__main__':
    sax.parse(sys.stdin, MySaxHandler)

这是追溯:

Traceback (most recent call last):
  File "/tmp/a.py", line 13, in <module>
    sax.parse(sys.stdin, MySaxHandler)
  File "/usr/lib/python3.6/xml/sax/__init__.py", line 33, in parse
    parser.parse(source)
  File "/usr/lib/python3.6/xml/sax/expatreader.py", line 110, in parse
    self._cont_handler.setDocumentLocator(ExpatLocator(self))
TypeError: setDocumentLocator() missing 1 required positional argument: 'locator'

这是为什么?

这很微妙,但您需要将实例传递给处理程序,而不是 class。看到这一行:

sax.parse(sys.stdin, MySaxHandler)

应该改为:

sax.parse(sys.stdin, MySaxHandler())