use fileinput to read a specific line

Hrvoje Niksic hniksic at xemacs.org
Tue Jan 8 09:42:40 EST 2008


Fredrik Lundh <fredrik at pythonware.com> writes:

> From what I can tell, Java's GC automatically closes file streams,
> so Jython will behave pretty much like CPython in most cases.

The finalizer does close the reclaimed streams, but since it is
triggered by GC, you have to wait for GC to occur for the stream to
get closed.  That means that something like:

    open('foo', 'w').write(some_contents)

may leave 'foo' empty until the next GC.  Fortunately this pattern is
much rarer than open('foo').read(), but both work equally well in
CPython, and will continue to work, despite many people's dislike for
them.  (For the record, I don't use them in production code, but
open(...).read() is great for throwaway scripts and one-liners.)

> I sure haven't been able to make Jython run out by file handles by
> opening tons of files and discarding the file objects without
> closing them.

Java's generational GC is supposed to be quick to reclaim recently
discarded objects.  That might lead to swift finalization of open
files similar to what CPython's reference counting does in practice.

It could also be that Jython internally allocates so many Java objects
that the GC is triggered frequently, again resulting in swift
reclamation of file objects.  It would be interesting to monitor (at
the OS level) the number of open files maintained by the process at
any given time during the execution of such a loop.



More information about the Python-list mailing list