using subprocess for non-terminating command

zacherates zacherates at gmail.com
Wed Jul 4 22:19:34 CEST 2007


> Only when the program has executed and the output available, subprocess can
> read through PIPE's stdout it seems ( not at any other time).
> With killing, I loose the output.

This is untrue.
>>> process.stdout.read() # Blocks until end of stream.
>>> process.stdout.read(1) # Reads one character, only blocks if that character is unavailable.

As such you can read the needed chars from the child's STDOUT one at a
time. For example:

import os
import signal
import subprocess
import threading
import sys

stop = False
ping = subprocess.Popen('ping 127.0.0.1', shell = True, stdout =
subprocess.PIPE)

def kill():
    global stop
    stop = True
    os.kill(ping.pid, signal.SIGTERM)

threading.Timer(5, kill).start()

while not stop:
     sys.stdout.write(ping.stdout.read(1))

This solution let's you read from the stdout of a program that may
never terminate and time out after a certain amount of time but it's
not pretty.  It's unix specific and introduces threads into a program
that doesn't need them.  I'd go with trying to limit the time the
child runs through command line options if at all possible.

Cheers,
   Aaron





More information about the Python-list mailing list