I don't think I understand popen2() behaviour

Siggy Brentrup bsb at winnegan.de
Mon Feb 12 13:48:35 EST 2001


Timothy Grant <tjg at exceptionalminds.com> writes:

> Hi,

> I need some enlightenment. For the first time ever, I'm playing with
> pipes in python and I must be missing something. I'll paste in a
> couple of examples to see if I can explain myself.

> >>> import os
> >>> x = os.popen('tail -f /var/log/messages')
> >>> tail: /var/log/messages: Permission denied
> tail: no files remaining
> 
> >>> 

> OK, so I'd expect that behaviour, as I'm logged in as me, not root.

> Now, my understanding of popen2() is that it gives me a file handle
> to both stdin and stderr, so since I don't want those error messages
> popping up on the screen I tried the following

> >>> import popen2
> >>> x,y = popen2.popen2('tail -f /var/log/messages')
> >>> tail: /var/log/messages: Permission denied
> tail: no files remaining
> 
> >>>

> Now that was unexpected, as I would have thought that the error
> messages should have been hidden away in my file object y, and that
> I wouldn't see them until I did a y.readlines() or something.

popen2 connects the command's stdin and stdout, but not to stderr.

> However, when I try to access y, I get the following:

> >>> y.readlines()
> Traceback (innermost last):
>   File "<stdin>", line 1, in ?
> IOError: [Errno 9] Bad file descriptor
> >>> 

>>> y
<open file '(fdopen)', mode 'w' at 807c4b0>

shows that you are reading from a file open for output, hence the
IOError.
 
> So, obviously I don't understand something, but I'm not even sure
> what it is I don't understand yet!

Try the following:

>>> cld = popen2.Popen3('tail -f /var/log/messages', 1)

For details cf.
http://www.python.org/doc/current/lib/popen3-objects.html

HIH
  Siggy





More information about the Python-list mailing list