using subprocess for non-terminating command

zacherates zacherates at
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.
>>> # Blocks until end of stream.
>>> # 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', shell = True, stdout =

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

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

while not stop:

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.


More information about the Python-list mailing list