ContentHandler 未定义
我正在尝试从 O'Reilly 的 Python 和 XML 学习 Python 的 SAX 模块。我正在尝试运行以下示例代码,但我不断收到错误,但我不明白为什么。
第一个文件是 handlers.py:
class ArticleHandler(ContentHandler):
"""
A handler to deal with articles in XML
"""
def startElement(self, name, attrs):
print "Start element:", name
第二个文件是 art.py,它导入第一个文件:
#!/usr/bin/env python
# art.py
import sys
from xml.sax import make_parser
from handlers import ArticleHandler
ch = ArticleHandler( )
saxparser = make_parser( )
saxparser.setContentHandler(ch)
saxparser.parse(sys.stdin)
当我尝试运行 art.py 时>,我得到以下信息:
% python art.py < article.xml
Traceback (most recent call last):
File "art.py", line 7, in <module>
from handlers import ArticleHandler
File "~/handlers.py", line 1, in <module>
class ArticleHandler(ContentHandler):
NameError: name 'ContentHandler' is not defined
我可能遗漏了一些明显的东西。有人可以帮忙吗?
谢谢!
I'm trying to learn Python's SAX module from O'Reilly's Python and XML. I'm trying to run the following sample code, but I keep getting an error and I can't figure out why.
The first file is handlers.py
:
class ArticleHandler(ContentHandler):
"""
A handler to deal with articles in XML
"""
def startElement(self, name, attrs):
print "Start element:", name
The second file is art.py
, which imports the first file:
#!/usr/bin/env python
# art.py
import sys
from xml.sax import make_parser
from handlers import ArticleHandler
ch = ArticleHandler( )
saxparser = make_parser( )
saxparser.setContentHandler(ch)
saxparser.parse(sys.stdin)
When I try to run art.py
, I get the following:
% python art.py < article.xml
Traceback (most recent call last):
File "art.py", line 7, in <module>
from handlers import ArticleHandler
File "~/handlers.py", line 1, in <module>
class ArticleHandler(ContentHandler):
NameError: name 'ContentHandler' is not defined
I'm probably missing something obvious. Can anybody help?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须在 handlers.py 中导入 ContentHandler,如下所示:
这应该可以做到。
You have to import ContentHandler in handlers.py as follows:
This should do it.