【问题标题】:lxml.etree.iterparse closes input file handler?lxml.etree.iterparse 关闭输入文件处理程序?
【发布时间】:2011-07-24 12:21:58
【问题描述】:

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

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

$ python2.6 setup.py test

setup.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 上的测试都运行良好。

【问题讨论】:

    标签: python stringio iterparse


    【解决方案1】:

    似乎与StringIO 一起工作正常,请尝试使用它而不是cStringIO。不知道为什么要关闭。

    【讨论】:

      【解决方案2】:

      Docs-fu 是问题所在。您引用的“从 lxml 2.3 开始,在错误情况下也会调用 .close() 方法”与 iterparse 无关。它出现在您的链接页面上 iterparse 部分之前。它是目标解析器接口文档的一部分。它指的是目标(输出!)对象的 close() 方法,与您的 StringIO 无关。无论如何,您似乎也忽略了那个小词also。 2.3之前,lxml只有解析成功才会关闭目标对象。现在它在出错时关闭它。

      为什么要在解析完成后“访问”StringIO对象?

      更新 之后尝试访问数据库是指测试中的所有 self.xml.getvalue() 调用吗? [在您的问题中显示 ferschlugginer 回溯,因此我们无需猜测!] 如果这是导致问题的原因(它确实算作 IO 操作),请忘记 getvalue() ...如果它可以工作,不是吗返回(非常规命名的)(不变的)XML?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-11-25
        • 1970-01-01
        • 2015-02-12
        • 2021-11-18
        • 2015-08-24
        • 2023-04-01
        • 1970-01-01
        相关资源
        最近更新 更多