我需要做StringIO.close()吗? [英] Do I have to do StringIO.close()?

查看:134
本文介绍了我需要做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()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆