Script to capture stderr of subprocess

jslowery at gmail.com jslowery at gmail.com
Tue Oct 19 20:21:49 CEST 2010


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 proc.returncode:
    f = file('/tmp/boom.txt', 'w')
    f.write(" ".join(cmd) + " returned unexpectedly.\n")
    f.write(proc.stderr.read(-1))
    f.close()
sys.exit(proc.returncode)



More information about the Python-list mailing list