Should I close after popen??
François Pinard
pinard at iro.umontreal.ca
Thu Mar 29 21:32:35 EST 2001
[David Allen]
> In article <m38zm6r8ih.fsf at master.athome>, "Andrew Markebo"
> <flognat at flognat.myip.org> wrote:
> > I am hacking away a small background program, using popen to call
> > commands, should I close the file in some way when done or it is taken
> > care of automagically??
> IIRC when garbage collected, all file handles are closed automagically
> by python. But that doesn't mean that it's OK to do it, that's just for
> safety. You should ALWAYS close your own handles, so you can keep track of
> where they're good and where they're no good. [...] It's good practice.
Explicit closing is probably not always good practice, and is not necessarily
safer. I would completely agree with the above for someone who wants to
write Jython, or write Python that could be quickly turned into Jython.
But if you stick with Python, you can safely rely on the fact that a file
is automagically close as soon as you do not refer to it anymore.
[Donn Cave]
> That's the party line, since the Java implementation can't finalize on
> reference counts and for that matter there's no guarantee that the C
> implementation always will. But at present it does. In C Python, you
> may rely on destructor timing if you want, it will happen exactly when
> it should. The garbage collection option that was introduced in 2.0
> does not change that. You have to understand that it's not official,
> but it's so useful that it's hard to pretend it isn't there.
In fact, if I remember well, Tim Peters confirmed (on this list) that
Python, the C implementation, is very not likely to change on this.
Code like:
open(logfile, 'a').write('Done!\n')
or maybe:
for line in open(logfile).readlines():
process(line)
is very legible, and would rather be uselessly encumbered with explicit
closes and intermediate variables. It is not worth writing these in the
style of other languages where closes are explicitely needed.
Of course, there are also cases where explicit closes are welcome and useful.
Yet, in my experience so far, this does not happen frequently.
--
François Pinard http://www.iro.umontreal.ca/~pinard
More information about the Python-list
mailing list