Should I close after popen??

Ken Seehof kens at sightreader.com
Thu Mar 15 16:02:05 EST 2001


----- Original Message -----
From: "Sean 'Shaleh' Perry" <shaleh at valinux.com>
To: "Andrew Markebo" <flognat at flognat.myip.org>
Cc: <python-list at python.org>
Sent: Thursday, March 15, 2001 4:27 PM
Subject: RE: Should I close after popen??


>
> On 15-Mar-2001 Andrew Markebo 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??
> >
> > I do something like this once every 10 mins..
> >
> >         fd1=os.popen("command")
> >         fd2=os.popen("command")
> >         os.wait(fd1)
> >         os.wait(fd2)
> >         values=fd1.read()+fd2.read()
> >
> > And.. anything to worry about, nesting popen/wait like this??
> > (Linux/Solaris)
> >
>
> if that is in a loop, it should be fine:
>
>   while 1:
>      f = open(file) # every time the loop repeats, f gets closed and
opened
>                     # again
>      # do things to f
>
I don't think that's reliable in general.  I'm pretty sure the file gets
closed when
the file object gets finalized, but you aren't supposed to count on garbage
collection to do its job at any particular time.  The while loop above could
in
theory be equivalent to the folowing:

f0 = open(file)
f0.close()
f1 = open(file)
f2 = open(file)
f3 = open(file)
f1.close
f4 = open(file)
f3.close()
f2.close()
f4.close()

...because the objects can be deleted whenever the interpreter feels
like it.  In practice, you'll probably get by with it, but you are setting
yourself up for nasty bugs later.

In other words, you are better off closing files explicitly.

In the case of popen, it seems to me like it wouldn't matter if you
leave a few open streams lying around, but it just seems sloppy,
like not washing your dishes after dinner.

Your usage of wait is fine, (assuming that the fd1 process is never
dependent on the fd2 process).

> --
> http://mail.python.org/mailman/listinfo/python-list
>





More information about the Python-list mailing list