git.net

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

FDs will be closed after exception automatically in python2.7?


On 2019-06-10 18:18:07 +0800, lampahome wrote:
> as title,
> 
> I confused will fd will be close after exception automatically?
> 
> Like:
> try:
> fd=open("file","w+")
> fd.get() //any useless function of fd
> except Exception:
> print 'hi'

Please try to preserve indentation when sending code to the list.
Indentation is part of the Python syntax and if you smash everything to
the left margin your program is not only hard to read but syntactically
wrong.

To answer your question:

No, an exception will not automatically close open file descriptors
(which file descriptors should it close and why?).

However, while handling an exception the variable holding the file
descriptor may go out of scope (for example if you leave a "with"
block[1] or return from a function). In that case the file descriptor
will be closed (in the case of a with block immediately, otherwise when
the garbage collector gets around to it).

        hp

[1] Don't know if those exist in Python 2.x. You should upgrade to 3.x
    anyway.
-- 
   _  | Peter J. Holzer    | we build much bigger, better disasters now
|_|_) |                    | because we have much more sophisticated
| |   | hjp at hjp.at         | management tools.
__/   | http://www.hjp.at/ | -- Ross Anderson <https://www.edge.org/>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20190610/6270b851/attachment.sig>