Re: popen and error handling

Steven D. Majewski (sdm7g@elvis.med.virginia.edu)
Tue, 9 Nov 1993 15:51:04 -0500

On Nov 9, 17:09, Gerry Stringer wrote:
> Subject: popen and error handling
>
>
> eg. fh = popen('rubbish','r') doesn't raise an exception so how can I
> tell the difference between failed execution and no output ?
>
> What's the standard Unix trick for doing this, I can think of a couple
> of ways but they don't inspire me at the moment.
>

The aix manpage for the popen routine says that result of
popen to a non-functional command is unpredictable. The SunOS
man page makes it look as if it *should* return Null, and therefore,
( I looks to me ) posixmodule *ought* to signal an exception
( "if (FP == NULL) return posix_error()" ), but in fact,
posix.popen on both systems returns an open file that doesn't
give any output.

You *COULD* redirect stderr to stdout, but THEN you would have to
figure which lines where output and which were error messages.

But you can tell when you CLOSE the pipe. pclose is supposed to
return -1. ( again, according to the manpage) On both aix and sunos,
*python*.close() returns 256 in that case.
Close of a properly opened pipe returns None.

So a signaling version of readline would be something like:

line = p.readline()
if line: return line
elif p.close() : raise SomeError

It has the side effect of closing the open pipe, but only
when it's empty, so that may be acceptable. ( and unfortunately,
a posix.close( posix.dup( p.fileno() ) ) give the same answer! )

- Steve Majewski (804-982-0831) <sdm7g@Virginia.EDU>
- UVA Department of Molecular Physiology and Biological Physics