简体   繁体   English

来自文件的Python ElementTree.parse()不会关闭该文件

[英]Python ElementTree.parse() from file does not close the file

I have a xml file - kind of template to fill within the parameters and make a request (create some data). 我有一个xml文件 - 一种模板,用于填充参数并发出请求(创建一些数据)。

I open this file with 我打开这个文件

tree = ET.parse(path_to_file)

and I make loop to get the xml from file, fill with the parameters and send a request. 然后我循环从文件中获取xml,填充参数并发送请求。 But after 2555 requests I get an error message: 但在2555次请求后,我收到一条错误消息:

IOError: [Errno 24] Too many open files: 'resources/cmr/skeletons/man/CreateLiveEvent.xml'

Is there a way to close file after ET.parse() opens it? 有没有办法在ET.parse()打开它之后关闭文件?

Thanks 谢谢

Upgrade your 2.7 installation. 升级2.7安装。 This supposedly was fixed in issue #7334 , and was included in 2.7.3. 这应该在问题#7334中得到修复 ,并包含在2.7.3中。 It does look like there is a bug in the way the cElementTree implementation closes files however (eg it doesn't close them). 看起来cElementTree实现关闭文件的方式确实有一个错误(例如它不会关闭它们)。

The alternative is to open the file yourself: 另一种方法是自己打开文件:

with open(path_to_file, 'rb') as xml_file:
    tree = ET.parse(xml_file)

and leave it to the with statement to close the file object. 并将其留给with语句来关闭文件对象。 Open the file as binary ; 将文件打开为二进制文件 ; it is the job of the XML parser to handle line endings and encodings. XML解析器的工作是处理行结尾和编码。

You could open the file yourself and close it: 您可以自己打开文件并关闭它:

source = open(path_to_file)
tree = ET.parse(source)
... do your work ...
source.close()

This is not an answer but a possible solution or work-around. 这不是一个答案,而是一个可能的解决方案或解决方案。

I was working on a large xml file, 240 Meg, just parsing and searching with no other file activity just to measure the time to search the data. 我正在处理一个大的xml文件,240 Meg,只是解析和搜索没有其他文件活动只是为了测量搜索数据的时间。 The script did not even print any info. 该脚本甚至没有打印任何信息。 I had just one print('Done.') as the last statement at the end. 我只有一个印刷品('完成。')作为最后的最后一个陈述。 When my script was done Python printed the "Done." 当我的脚本完成后,Python打印出“完成”。 and then hung for awhile while Python took care GC cleanup. 然后挂起一段时间,而Python负责GC清理。 I then saw a noticeable Python exit speed-improvement when I did: 然后,当我这样做时,我看到了一个明显的Python退出速度提升:

def search(elem):
    """Recursive"""
    # check for lots of elements

tree = ET.parse(source)
root = tree.getroot() # a large and deep element
search(root) # time it

print('Deleting tree')
del tree

# root still usable after del tree.
# You can still process the in-memory root
# at this point but I suspect not tree.write().
process(root)

print('Deleting root')
del root  # not necessary but seemed to improve exit
print('Done')

Perhaps del tree closes the file. 也许del tree关闭文件。 I do not know if this is true. 我不知道这是不是真的。 I used cPython. 我用过cPython。 I do not know if this is implementation independent. 我不知道这是否与实现无关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM