我需要做StringIO.close()吗?

编程入门 行业动态 更新时间:2024-10-26 16:31:53
本文介绍了我需要做StringIO.close()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

一些代码:

import cStringIO def f(): buffer = cStringIO.StringIO() buffer.write('something') return buffer.getvalue()

文档说:

StringIO.close():释放内存缓冲区.尝试做进一步 关闭StringIO对象的操作将引发ValueError.

StringIO.close(): Free the memory buffer. Attempting to do further operations with a closed StringIO object will raise a ValueError.

我是否必须执行buffer.close(),否则当缓冲区超出范围并被垃圾回收时,它将自动发生?

Do I have to do buffer.close(), or it will happen automatically when buffer goes out of scope and is garbage collected?

更新:

我做了一个测试:

import StringIO, weakref def handler(ref): print 'Buffer died!' def f(): buffer = StringIO.StringIO() ref = weakref.ref(buffer, handler) buffer.write('something') return buffer.getvalue() print 'before f()' f() print 'after f()'

结果:

vic@wic:~/projects$ python test.py before f() Buffer died! after f() vic@wic:~/projects$

推荐答案

通常最好还是调用close()或使用with语句,因为在特殊情况下可能会出现某些意外行为.例如,expat- IncrementalParser似乎期望文件被关闭,否则在某些罕见情况下,除非发生超时,否则它不会返回已解析的xml的最后提示.

Generally it's still better to call close() or use the with statement, because there may be some unexpected behaviour in special circumstances. For example, the expat-IncrementalParser seems to expect a file to be closed, or it won't return the last tidbit of parsed xml until a timeout occurs in some rare circumstances.

但是对于要为您处理结账的with语句,您必须使用io -Modules中的StringIO类,如Ivc的注释所述.

But for the with-statement, which handles the closing for you, you have to use the StringIO class from the io-Modules, as stated in the comment of Ivc.

这对于我们通过手动关闭StringIO解决的某些旧式sax解析器脚本来说是一个严重的麻烦.

This was a major headache in some legacy sax-parser script we solved by closing the StringIO manually.

范围外"关闭无效.它只是在等待超时限制.

The "out-of-scope" close didn't work. It just waited for the timeout-limit.

更多推荐

我需要做StringIO.close()吗?

本文发布于:2023-10-24 13:23:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524069.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:StringIO   close

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!