相关疑难解决方法(0)

防止TextIOWrapper以Py2/Py3兼容的方式关闭GC

我需要完成的事情:

给定二进制文件,以提供TextIOBaseAPI 的几种不同方式对其进行解码.理想情况下,这些后续文件可以在不需要明确跟踪其生命周期的情况下传递.

不幸的是,包含一个BufferedReader将导致该读取器在TextIOWrapper超出范围时被关闭.

这是一个简单的演示:

In [1]: import io

In [2]: def mangle(x):
   ...:     io.TextIOWrapper(x) # Will get GCed causing __del__ to call close
   ...:     

In [3]: f = io.open('example', mode='rb')

In [4]: f.closed
Out[4]: False

In [5]: mangle(f)

In [6]: f.closed
Out[6]: True
Run Code Online (Sandbox Code Playgroud)

我可以通过覆盖在Python 3中解决这个问题__del__(这对我的用例来说是一个合理的解决方案,因为我可以完全控制解码过程,我只需要在最后公开一个非常统一的API):

In [1]: import io

In [2]: class MyTextIOWrapper(io.TextIOWrapper):
   ...:     def __del__(self):
   ...:         print("I've been GC'ed")
   ...:         

In [3]: def mangle2(x):
   ...:     MyTextIOWrapper(x)
   ...:     

In [4]: f2 …
Run Code Online (Sandbox Code Playgroud)

python garbage-collection python-2.7 python-3.x

8
推荐指数
1
解决办法
374
查看次数