Monday, March 21, 2011

Running one function while waiting for another to finish

 import sys
 import threading

 #  
 # this function does a cool spinny thing  
 #  
 def draw_ascii_spinner(delay=0.2):  
  for char in '/-\|': # there should be a backslash in here.  
   sys.stdout.write(char)  
   sys.stdout.flush()  
   time.sleep(delay)  
   sys.stdout.write('\r') # this should be backslash r.  
 #  
 # the below two functions   
 # do the work of backgrounding a process  
 # so we can print a progress indicator  
 #  
 def backGround(func,args,job):  
   job.append(func(*args))  
   
 def whileWeWait(func,arg):  
  job = []  
  t = threading.Thread(target=backGround, args=(func, (arg,), job))  
  t.start()  
  while t.is_alive():  
   draw_ascii_spinner()  
   t.join(0.2)  
   
  return job[0]  

## this is how we run it ..
## assuming we have a function named findCluster that needs a companyid
print whileWeWait(findCluster, companyid)
   

No comments: