gpt4 book ai didi

python - lxml.etree.iterparse 关闭输入文件处理程序?

转载 作者:太空狗 更新时间:2023-10-30 01:35:15 26 4
gpt4 key购买 nike

过滤器是 using iterparse 解析一个简单的 XML StringIO objectunit test .但是,当之后尝试访问 StringIO 对象时,Python 会退出并显示“ValueError: I/O operation on closed file”消息。根据iterparse documentation ,“从 lxml 2.3 开始,在错误情况下也会调用 .close() 方法,”但是我没有从 iterparse 收到错误消息或 Exception。我的 IO-foo 显然跟不上速度,所以有人有建议吗?

命令和(希望)相关代码:

$ python2.6 setup.py test

设置.py:

from setuptools import setup
from filterous import filterous as package

setup(
...
test_suite = 'tests.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 '))

filterous/filterous.py:

from lxml import etree
...
def search(file_pointer, out, terms, includes, human_readable = True):
...
context = etree.iterparse(file_pointer, tag='posts')

回溯:

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

PS:所有测试都在 2010-07-27 上运行良好.

最佳答案

似乎可以与 StringIO 配合使用,请尝试使用它代替 cStringIO。不知道为什么要关闭。

关于python - lxml.etree.iterparse 关闭输入文件处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6806760/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com