Should I close after popen??

Donn Cave donn at oz.net
Fri Mar 16 20:37:12 EST 2001


Quoth Andrew Markebo <flognat at flognat.myip.org>:
| Ahh hmm yep.. the scripts are running in 1.5.2, so what I do is to
| remove the waits, (hmm are ther any possibility of doing something
| similar??? am I supposed to use select/poll?)

Depends on what you want to do.  For sure, select has the potential
to solve some programming problems with pipes.  One thing that you
should bear in mind, though, is that the file object returned by
popen() buffers input, and select() can't see the buffered data,
so you may have "no data" yet have more to read from the file object.
You can ignore the file object, use the fileno() method to obtain 
the pipe file descriptor and use os.read() on it, for example.

Anyway, it would be easier to say what you ought to use, if it were
clear what problem you're trying to solve.  It's probably simpler
than you think.  If you just read the pipes until they return an
empty string, like any file, there's no reason to expect problems.

| Uhm how do I get the exit-code of stuff from popen? Looking at popen2
| it forks and does waitpid.. 

Did I mention that you could find some relevant documentation in
the pclose man page?

  fp = popen('echo OK; exit 9')
  data = fp.read()
  status = fp.close()

You might have to shift the result down 8, on UNIX, I forget.

One unrelated advantage of popen2 is that if you supply a list of
arguments, it will use them directly instead of a shell command
line.  That is much safer.  A command line constructed at run
time can have much more surprising effects if it's wrong, because
the shell is a much more powerful and general purpose program.

	Donn Cave, donn at oz.net



More information about the Python-list mailing list