Re: trying to read from pipe

Kenneth Manheimer (klm@NIST.GOV)
Thu, 01 Sep 1994 02:02:08 -0400 (EDT)

> Why is this failing?
>
> >>> from posix import *
> >>> fd = popen('ls', 'r')
> >>> s = read(fd, 4)
> Traceback (innermost last):
> File "<stdin>", line 1
> TypeError: bad argument list (format '(ii)')

This is one where you hit yourself on the forehead and say "i knew
that!", once you see it...

The standard builtin 'read' function expects two ints (as indicated by
the '(ii)' format string), the first one of which would be a file
descriptor, not a file object. posix.popen() produces a file object,
not a file descriptor. The file object has an intrinsic read method:

>>> s = fd.read(4) # Get 4 bytes from the the fd pipe

or maybe

>>> s = fd.readline() # Get the next line from fd, including \n

and to close it:

>>> fd.close()

(This sort of simple, tidy thing appealed to me, and reassured me,
when i first started using python, that it is a good way to go!)

One more thing - i often see advice (eg, in the manuals) to use 'os'
instead of 'posix', so your code is more portable. I'm not sure
whether all pipes are implemented for all supported platforms, but the
os module for the ones that do will have popen, and it basically costs
nothing to go with 'os' instead of the OS-specific modules...

Ken
ken.manheimer@nist.gov, 301 975-3539