Python未关闭资源:删除文件是否安全? [英] Python unclosed resource: is it safe to delete the file?

查看:43
本文介绍了Python未关闭资源:删除文件是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在谷歌上搜索了这个问题,但没有找到任何解决方案.我正在使用 Eclipse 和 PyDev 插件运行 Python 3.3,当我运行任何 Python 项目时,我收到以下消息:

Googled my way around this issue, but didn't find any solutions. I'm running Python 3.3 with Eclipse and PyDev plugin, and when I run any Python project, I get the following message:

/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/update_checker.py:37: ResourceWarning: unclosed file <_io.BufferedReader name='/var/folders/x4/st67yr0x6qg7znh7sdfr94kh0000gn/T/update_checker_cache.pkl'>
  permacache = pickle.load(open(filename, 'rb'))

我对 Python 有点陌生,我不知道这意味着什么.我想在删除之前询问以确保可以安全删除.这到底是什么意思?我得到一个打开的文件……但是为什么 Python 向我抱怨?我正在使用 PRAW 库,如果这有什么不同的话.

I'm kind of new to Python, and I have no idea what this means. I wanted to ask before deleting this to make sure it's safe to delete. What does this even mean? I get there's an open file... but why is Python complaining to me? I'm using the PRAW library, if that makes any difference.

更新:我的代码是在sourceforge上,罢工> 但它没有可靠地提出错误(在 2 台不同的计算机上尝试过).一旦出现错误,它就永远不会消失.

Update: My code is here on sourceforge, but it doens't reliably come up with the error (tried on 2 different computers). Once the error comes up, it never goes away.

推荐答案

这个 ResourceWarning 意味着您打开了一个文件,使用了它,但忘记了关闭该文件.当 Python 注意到文件对象已死时,它会为您关闭它,但这只会在某个未知时间过去后发生.因此,在最近的版本中,Python 在执行此操作时也会打印 ResourceWarning.这是一种让您快速识别未关闭文件所在位置并正确关闭它们的方法.在某些不能同时打开超过 N 个文件的平台上,这可能很重要(例如 1024).此外,特别是在 Windows 上,如果文件仍处于打开状态(例如删除它),您将无法对其进行某些操作.

This ResourceWarning means that you opened a file, used it, but then forgot to close the file. Python closes it for you when it notices that the file object is dead, but this only occurs after some unknown time has elapsed. Thus in recent versions, Python also prints a ResourceWarning when it does that. It is a way for you to quickly identify where the unclosed files are, and properly close them. It might be important on some platforms which cannot have more than N files opened at the same time (e.g. 1024). Also, specifically on Windows, you cannot do some operations with a file if it's still open (e.g. deleting it).

在这种情况下,文件 update_checker.py 中的行需要固定为:

In this case, the line in the file update_checker.py needs to be fixed to say:

with open(filename, 'rb') as f:   # will close() when we leave this block
    permacache = pickle.load(f)

这篇关于Python未关闭资源:删除文件是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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