l0b*_*0b0 5 python stringio iterparse
filterous被使用 iterparse来解析简单的XML StringIO对象中一个单元测试.但是,在尝试访问该StringIO对象之后,Python将以" ValueError: I/O operation on closed file"消息退出.根据iterparse文档,"从lxml 2.3开始,.close()方法也将在错误情况下被调用,"但我没有收到任何错误消息或Exception来自iterparse.我的IO-foo显然没有达到速度,所以有人有建议吗?
命令和(希望)相关代码:
$ python2.6 setup.py test
Run Code Online (Sandbox Code Playgroud)
setup.py:
from setuptools import setup
from filterous import filterous as package
setup(
...
test_suite = 'tests.tests',
Run Code Online (Sandbox Code Playgroud)
测试/ tests.py:
from cStringIO import StringIO
import unittest
from filterous import filterous
XML = '''<posts tag="" total="3" ...'''
class TestSearch(unittest.TestCase):
def setUp(self):
self.xml = StringIO(XML)
self.result = StringIO()
...
def test_empty_tag_not(self):
"""Empty tag; should get N results."""
filterous.search(
self.xml,
self.result,
{'ntag': [u'']},
['href'],
False)
self.assertEqual(
len(self.result.getvalue().splitlines()),
self.xml.getvalue().count('<post '))
Run Code Online (Sandbox Code Playgroud)
filterous/filterous.py:
from lxml import etree
...
def search(file_pointer, out, terms, includes, human_readable = True):
...
context = etree.iterparse(file_pointer, tag='posts')
Run Code Online (Sandbox Code Playgroud)
追溯:
ERROR: Empty tag; should get N results.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/victor/dev/filterous/tests/tests.py", line 149, in test_empty_tag_not
self.xml.getvalue().count('<post '))
ValueError: I/O operation on closed file
Run Code Online (Sandbox Code Playgroud)
PS:测试在2010-07-27都运行良好.
Docs-fu 是问题所在。您引用的“从 lxml 2.3 开始,在错误情况下也会调用 .close() 方法”与 iterparse 无关。它出现在链接页面上的iterparse 部分之前。它是目标解析器接口文档的一部分。它指的是目标(输出!)对象的 close() 方法,与 StringIO 无关。无论如何,你似乎也忽略了那个小词。在2.3之前,lxml仅在解析成功时才关闭目标对象。现在它也会在出错时关闭它。
为什么解析完成后要“访问”StringIO 对象?
更新通过之后尝试访问数据库,您的意思是测试中的所有 self.xml.getvalue() 调用吗?[在你的问题中显示 ferschlugginer 回溯,这样我们就不需要猜测!]如果这是导致问题的原因(它确实算作 IO 操作),请忘记 getvalue() ...如果它可以工作,不是吗?返回(非常规命名的)(不变的)XML?