subprocess exiting in an incomprehensible fashion

Will wholcomb at gmail.com
Fri Oct 21 13:33:25 EDT 2005


I have this bit of code:

#!/usr/bin/python

import subprocess

calc = subprocess.Popen("dc", stdin=subprocess.PIPE,
                              stdout=subprocess.PIPE,
                              stderr=subprocess.STDOUT)
max = 5
for value in range(1, max):
    calcout, calcerr = calc.communicate("%d\n" % value)
    print("Post Communicate Value %d: %s (%s) [%d]" %
          (value, calcout, calcerr, calc.returncode))
    if value > 1:
        calcout, calcerr = calc.communicate("*\n")
calcout, calerr = calc.communicate("p\n")
print("Value: %d = %d" %
      (calcout, reduce(lambda x,y: x * y, range(1, max))))
calc.communicate("q\n")
status = calc.wait()
print "Exited with: %d" % status

### End Code

After the first number is input, the subprocess is exiting after the
first communicate. I do not understand why. I have tried to accomplish
the same thing with os.popen and popen2.Popen. I can't get anything to
work and I am having a difficult time finding examples that include
both redirected input and output from a subprocess. I am wanting to do
work with a more complicated program, but was looking to get something
simple working first.

Any help would be much appreciated. I have been hunting quite a bit for
he answer to no avail.

Will Holcomb




More information about the Python-list mailing list