Script to capture stderr of subprocess

Arnaud Delobelle arnodel at
Tue Oct 19 21:04:04 CEST 2010

"jslowery at" <jslowery at> writes:

> We have a lot of curses-based console applications running on linux. I
> would like to write a wrapper script that notifies us if the
> application terminates unexpectedly. With my first, obviously naive
> attempt, the subprocess dies instantly. STDIN and STDOUT will need to
> connect to the terminal of course, since these are complex keyboard-
> based applications. STDERR and the return code is what I would like to
> capture. Actually, if it was possible, it would be nice to capture all
> the bytes going between stdin and stdout in a file as well for
> debugging purposes.
> Could someone point me in the right direction here? I have a feeling
> I"m missing something fundamental about how the Unix processes and
> file descriptors work.
> import os
> import subprocess
> import sys
> cmd = ['/usr/local/bin/runcobol'] + sys.argv[1:]
> proc = subprocess.Popen(cmd, stderr=subprocess.PIPE)
> proc.communicate()

If you want to capture what was sent to stderr, (which you probably do,
as you opened the process with stderr=subprocess.PIPE) you need to do

stdoutdata, stderrdata = proc.communicate()

> if proc.returncode:
>     f = file('/tmp/boom.txt', 'w')
>     f.write(" ".join(cmd) + " returned unexpectedly.\n")
>     f.write(

Now use this instead:


>     f.close()
> sys.exit(proc.returncode)

Now it should work.  After you use proc.communicate(), proc.stderr has
been read and there is nothing left on it!  Its content has been put in
the data returned by proc.communicate as shown above.



More information about the Python-list mailing list