何时/如何匿名文件对象关闭? [英] When/How does an anonymous file object close?

查看:115
本文介绍了何时/如何匿名文件对象关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题关于一个python单线程,它发生在我身上我不知道python如何处理匿名文件对象。从问题:

pre $ open(to_file,'w')。write(open(from_file).read())

有两个调用打开而不使用关键字(这通常是我如何处理文件)。过去我曾使用过这种未命名的文件。 IIRC,似乎有一个剩余的操作系统级别的文件锁定,将在一两分钟后过期。



那么这些文件句柄会发生什么?他们是通过垃圾收集清理吗?由操作系统?当 close()被调用时,Python机器和文件会发生什么情况,当脚本结束并经过一段时间后,它会发生什么?

$ b $在Linux上(通过检查/ proc / $$ / fds)和Windows上的File Handle(使用SysInternals工具)来监视文件描述符,看起来文件在语句后立即关闭。

但是,由于垃圾收集器必须执行,所以无法保证。在测试中,我已经做过,每次都会一次关闭。



语句的推荐为与打开一起使用,但实际需要的场合很少见。很难证明你必须使用的情况,但是安全可能是个好主意。

所以,你的单行程式变成:

  with open(to_file ,'w')作为tof,打开(from_file)作为fof:
tof.write(fof.read())



的优点在于,特殊的方法(在io类中)称为 __ exit __()

*除非你像 os._exit()那样做。

In the comments of this question about a python one-liner, it occurred to me I have no idea how python handles anonymous file objects. From the question:

open(to_file, 'w').write(open(from_file).read())

There are two calls to open without using the with keyword (which is usually how I handle files). I have, in the past, used this kind of unnamed file. IIRC, it seemed there was a leftover OS-level lock on the file that would expire after a minute or two.

So what happens to these file handles? Are they cleaned up by garbage collection? By the OS? What happens to the Python machine and file when close() is called, and will it all happen anyway when the script finishes and some time passes?

解决方案

Monitoring the file descriptor on Linux (by checking /proc/$$/fds) and the File Handle on Windows (using SysInternals tools) it appears that the file is closed immediately after the statement.

This cannot be guarenteed however, since the garbage collector has to execute. In the testing I have done it does get closed at once every time.

The with statement is recommended to be used with open, however the occasions when it is actually needed are rare. It is difficult to demonstrate a scenario where you must use with, but it is probably a good idea to be safe.

So your one-liner becomes:

with open(to_file, 'w') as tof, open(from_file) as fof:
    tof.write(fof.read())

The advantage of with is that the special method (in the io class) called __exit__() is guaranteed* to be called.

* Unless you do something like os._exit().

这篇关于何时/如何匿名文件对象关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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