[Tutor] Difficulty with the subprocess module

Dhiraj Sharma dhirajsharma at optonline.net
Fri Mar 2 06:16:00 CET 2007

I am using the subprocess module to capture the 
input/output of a process on a Windows machine 
with Python 2.5 and ran into a puzzling problem.

The following works well:
   p = subprocess.Popen("cat", buffer=0, stdin=subprocess.PIPE,
       stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
   # "cat" is installed as a cygwin program, but this script is running
   # in a Command.com windows. I am not on Linux.

   fdata = open('input');
   for l in fdata:
      m = p.stdout.readline()

If I replace the "cat" process by "sed -e s/a/x/g", the 
script hangs on the readline() call -- as indicated by 
the following messages obtained after entering Ctl-C:
Traceback (most recent call last):
  File "x.py", line 39, in <module>
  File "x.py", line 34, in pipe_ex2
    m = p.stdout.readline()

Finally, if I replace "cat" by "python cat.py", the 
script hangs so badly that even Ctl-C does not work,
and I have to close the Command.com window. All by
itseld the cat.py script works fine and is given below:
import sys, os

fin = sys.stdin; fout = sys.stdout;
for l in fin:

I would appreciate guidance regarding:
1. Why is the script behaving differently for cat and sed?
2. Why the python subprocess "kills" the parent script?
3. What is the right way to write the above scripts?

Thanks very much
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070302/5d08304c/attachment.html 

More information about the Tutor mailing list