Taylor, Stuart Stuart.Taylor at
Fri Mar 16 11:27:48 CET 2007

for anyone who gets this same problem i managed to resolve the issue
using two threads.
The main program spawned a subprocess and used readlines to read the
output. The process spawned was a script which executes a command using
a thread. The thread reads the output from this command using readline.
Within the main loop of the script there is a while loop which checks
when the last output from the command was and if the time elapsed is
greater than timeout the script prints to the stdout a string called
In the main program the readline compares every output to see if it
matches this sting. if it does kill process :)
I'm sure this code could be implemented better but it works and got me
out of a hole
heres the thread script which contains the thread class and the time out
import datetime
import time
import threading
import subprocess
import os
import sys
class outputThread(threading.Thread):
    Thread is used to print the output of a command to the stdout
    def __init__(self,threadCommand, name="thread", *args, **kwargs):
        threading.Thread.__init__(self, *args, **kwargs)       = name
        self.killed     = 0
        self.counter    = 0
        self.command    = threadCommand
        self.retval     = None
    def run(self):
        self.Proc       = subprocess.Popen(self.command, cwd =
os.getcwd(),stdin=subprocess.PIPE, stdout = subprocess.PIPE, stderr =
        self.retval     = None
        while self.retval == None and not self.killed:   
            line = self.Proc.stdout.readline()
            print line.rstrip("\r\n")
    def Set_Hit(self):
        self.last_time =      
    def Get_Hit(self):
        return self.last_time    
if __name__ == "__main__":
    This script is designed to put a timeout loop over a thread.
    The intention of this thread is to perform a command and have a
timer loop over
    checking for the last text ouput from the command.
    If the loop exceeds the set time limit the command will stop reading
the output from the thread
    command     = []
    timeout     = 5
    maxCounter  = timeout
    curCounter  = 0
    strCounter  = 0
    if len(sys.argv) > 2:
            timeout   = int(sys.argv[1])
            print "time out value is not a float"
        for argPos in range(2,len(sys.argv)):
            print "arg = %s" % sys.argv[argPos]
        print "not enough arguments"
    thread1 = outputThread(command,name="thread1")
    while True:
        if not thread1.retval == None:
        #Get current time and when timeout should occur
        currentTime     =            
        elapsedTime     = thread1.Get_Hit() +
        #Check Elapsed time
        if elapsedTime < currentTime:
            print "timed out"


From: Taylor, Stuart [mailto:Stuart.Taylor at] 
Sent: 13 March 2007 09:50
To: Sick Monkey; Taylor, Stuart
Cc: python-list at
Subject: RE: Readline()

i have a thread class which should read the output from the procedure
line by line and finish when the thread is set to kill:
class KillableThread(threading.Thread):
    def __init__(self, name="thread", *args, **kwargs):
        threading.Thread.__init__(self, *args, **kwargs) = name
        self.killed = 0
    def kill(self):
        self.killed = 1
    def run(self): = threading._get_ident()
        self.Proc      =
subprocess.Popen(["python","-tt",""], cwd =
os.getcwd(),stdin=subprocess.PIPE, stdout = subprocess.PIPE, stderr =
        retval= None 
        while retval == None and not self.killed:
            line = self.Proc.stdout.readline()
to replicate my problem the requires a user input. i ask
for a user input as my thread will sit waiting on
self.Proc.stdout.readline(). This is the point i want to have a timeout
or be able to end my thread as there is no output from the output_file. 
The main approch i cannot implement is to be able to kill the thread as
it remains hung on readlines()


From: Sick Monkey [mailto:sickcodemonkey at] 
Sent: 13 March 2007 01:51
To: Taylor, Stuart
Cc: python-list at
Subject: Re: Readline()

Maybe if you show us your code we can better assist you.  

But maybe you can use a global variable or a try-catch method to keep
threads from staying alive and help better control your code.  

On 3/12/07, Taylor, Stuart <Stuart.Taylor at> wrote: 

	I have been working on running an external process using
subprocess.popen for a few days. 
	The process is ran over the network to another machine. 
	One thing I have found is that if I perform readline() on the
stdout it will hang if the process loses connection. 

	I have tried a few things in a test example: one is to use
stdin.write then stdin.flush() which send a string that readline() will
read and it ends correctly but doesn't work on the project I need it to
work on. Another is to try using threads and ignoar the thread when  the
process has lost connection but this still leaves the open thread alive
even when the main app has finished. 

	I am relatively new to python and I may be making a fundemantal
mistake in my implementation, can anyone please inform me of whether
sticking with subprocess.popen and readline() is the correct procedure
for this sort of task? 

	And if anyone can point me in the correct implementation of this
problem I would be gratefull. 

	Thank you 



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list