popen(2) wierdness - help!

Eric Brunel eric.brunel at pragmadev.com
Tue May 21 05:50:52 EDT 2002


professor ned wrote:

> Hi all,
> 
> this seems like it should be awfully simple, but the only answer I can
> get from anyone seems to be "use Expect!" which, somehow, isn't very
> satisfying.
> 
> Consider the following snippet of code (Python 2.2 running on RedHat
> 7.2, although Solaris 8 exhibits similar behavior):
> 
> ---
> 
>    #!/usr/local/bin/python
> 
>    import os
> 
>    cmd = "cat -"
>    stuff = "Hello, hello, hello...\n"
> 
>    writeHandle = os.popen( cmd, 'w')
>    print "writeHandle is %s" % writeHandle
>    print "stuff is %s" % stuff
> 
>    writeHandle.write( stuff )
>    writeHandle.close()
> 
>    writeHandle, readHandle = os.popen2( cmd )
> 
>    print "\nwriteHandle is %s " % writeHandle
>    print "readHandle is %s " % readHandle
>    print "stuff is %s " % stuff
> 
>    writeHandle.write( stuff )
> 
>    writeHandle.close()
>    readHandle.close()
> 
> ---
> 
> Now, consider the output:
> 
>    [ned at nmi-redhat72-dev ned]$ ./ptest.py
>    writeHandle is <open file 'cat -', mode 'w' at 0x810e9f0>
>    stuff is Hello, hello, hello...
> 
>    Hello, hello, hello...
> 
>    writeHandle is <open file '(fdopen)', mode 'w' at 0x8145138>
>    readHandle is <open file '(fdopen)', mode 'r' at 0x810d140>
>    stuff is Hello, hello, hello...
>  
>    [ned at nmi-redhat72-dev ned]$ cat: write error: Broken pipe
[snip]

I can't reproduce that problem on my Mandrake 8.0 box, but my guess is as 
follows: popen2 returns a handle on the command's stantard input and a 
handle on its standard output. Since your command is just a "cat -", 
everything you write to it is (more or less) immediatly sent back as its 
output. But just after writing something to it (writeHandle.write), you 
close the command's standard output (readHandle.close). I think this is the 
meaning of the "broken pipe" error: the command still had something on its 
output, but the listening process stopped listening.

Try to put a few prints between your statements. If I'm right, the error 
should occur during the "readHandle.close()" stuff. And don't get confused 
by the printed form of the file handles. I don't think they were intended 
to be human-readable...

BTW, to solve the problem, just add a line like "print readHandle.read()" 
just before the "readHandle.close()": you should get another "Hello, hello, 
hello..." and the error shouldn't occur again.

HTH
-- 
- Eric Brunel <eric.brunel at pragmadev.com> -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com




More information about the Python-list mailing list