[Tutor] script hangs when attempting to read Popen3 output
David Clymer
david at zettazebra.com
Wed Nov 10 03:28:30 CET 2004
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)
More information about the Tutor
mailing list