On Apr 24, 12:32 pm, sophie_newbie <[EMAIL PROTECTED]> wrote: > On Apr 22, 3:10 pm,sophie_newbie<[EMAIL PROTECTED]> wrote: > > > > > Hi, I'm trying to write a piece of code that spawns a thread and > > prints dots every half second until the thread spawned is finished. > > Code is > > something like this: > > > import threading > > class MyThread ( threading.Thread ): > > def run ( self ): > > myLongCommand()... > > > import time > > > t = MyThread() > > t.start() > > > while t.isAlive(): > > print "." > > time.sleep(.5) > > > print "OK" > > > The thing is this doesn't print a dot every half second. It just > > pauses for ages until the thread is finished and prints prints ".OK". > > But if I take out the "time.sleep(.5)" line it will keep printing dots > > really fast until the thread is finished. So it looks like its the > > time.sleep(.5) bit that is messing this up somehow? > > > Any ideas? > > > Thanks! > > As it happens I've managed to come up with a solution to this problem > using a subprocess rather than a thread. Its not exactly rocket > science but I thought I'd post it anyway. There are 3 files: > > ########## dots.py ####################### > # a script to print a dot every half second until it is terminated > > import time > import sys > > while 1 == 1: > > sys.stdout.write(".") > sys.stdout.flush() > > time.sleep(.5) > > ######### PrintDots.py ###################### > > # This is a simple class to spawn off another process that prints dots > repeatedly on screen > # when printDots() is called and stops when stopDots is called. It is > useful in cgi-scripts > # where you may want to let the user know that something is happening, > rather than looking > # at a blank screen for a couple of minutes. > > import time > import subprocess > import os > from signal import SIGTERM > > class PrintDots: > > # the constructor, called when an object is created. > def __init__(self): > > self.pid = 0 > > # the location of the script that prints the dots > self.dotsScript = "dots.py" > > def printDots(self): > > self.pid = subprocess.Popen( [ "python", self.dotsScript] > ).pid > > def stopDots(self): > > os.kill(self.pid, SIGTERM) > > ############ mainFile.py ############################## > # The above can then be called from any cgi-script as follows > > from PrintDots import PrintDots > p = PrintDots() > p.printDots() > print "Doing R Stuff" > my_Call_To_R_That_Takes_A_Long_Time() > p.stopDots() > print "OK" > > ############ > > And low and behold dots are printed on screen every half second while > python is talking to R, with an output like this: > > Doing R Stuff.................................OK
Whoops that last bit of code should read as follows: from PrintDots import PrintDots p = PrintDots() print "Doing R Stuff" p.printDots() my_Call_To_R_That_Takes_A_Long_Time() p.stopDots() print "OK" -- http://mail.python.org/mailman/listinfo/python-list