Python unclosed resource: is it safe to delete the file?

巧了我就是萌 提交于 2019-11-30 03:17:56

问题


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'))

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.

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.


回答1:


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).

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)


来源:https://stackoverflow.com/questions/21057942/python-unclosed-resource-is-it-safe-to-delete-the-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!