[Tutor] script hangs when attempting to read Popen3 output

Kent Johnson kent37 at tds.net
Wed Nov 10 03:56:08 CET 2004


I think there are deadlock issues with popen. The new subprocess module 
in Python 2.4 is supposed to help with this, you might want to check it 
out: http://www.python.org/peps/pep-0324.html

Kent

David Clymer wrote:
> Are python's popen* commands/classes really supposed to work like pipes?
> When I try to do somthing that works like this:
> 
> continuing input >> popen3('cat') >> read output
> 
> the script hangs when I try to read the command output. It seems I can
> provide multi-line input, but I cant read any lines from the output of a
> command that is still recieving input. I have to close the input before
> reading any output. That doesnt seem very "pipe-ish" to me. Am I doing
> something wrong, or just expecting the wrong behavior?
> 
> The script that I am working on is below.
> 
> TIA for any enlightenment you can provide me.
> 
> -davidc
> 
> 
> david at gorilla:~/dev/debian/packages/userutils/experimental$ cat
> shellcommands.py
> 
> """
>   Utilities & wrappers for running shell commands
> """
> 
> import sys, os
> from debug import debug
> from popen2 import Popen3
> 
> def cmd(command,input=None, dbg=False):
>   pcmd = Popen3(command)
> 
>   # dont bother writing if no input is available
>   if input != None:
>     debug('input >> ' + input, dbg)
>     try:
>       pcmd.tochild.write(input + "\n")
>       pcmd.tochild.flush()
>       if pcmd.poll():
>         print "still running"
>     except IOError, e:
>       print e
> 
>   # this magical line allows me to read
>   pcmd.tochild.close()
> 
>   output=''
>   while True:
>     try:
>       output += pcmd.fromchild.next()
>       print 'output: %s' % output
>     except StopIteration:
>       break
>     except IOError, e:
>       print e
>       break
> 
>   debug('output << ' + output, dbg)
> 
>   return output
> 
> 
> # -- try it out -- #
> 
> input=''
> 
> # if input is provided from the cmd line, lets use it
> if len(sys.argv) > 1:
>   input = sys.argv[1]
> 
> print cmd("cat", input, dbg=True)
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


More information about the Tutor mailing list