Skip to content

Instantly share code, notes, and snippets.

@ddickstein
Last active December 19, 2015 16:48
Show Gist options
  • Save ddickstein/5986448 to your computer and use it in GitHub Desktop.
Save ddickstein/5986448 to your computer and use it in GitHub Desktop.
Often it is useful to run some function that tries to do something, then run a check to see if it was done, and if not, try again and keep trying for some amount of time t. These functions can help.
import time
#
# Often it is useful to run some function that tries to do something,
# then run a check to see if it was done, and if not, try again and
# keep trying for some amount of time t. This function is designed
# to accomplish that.
#
def loop_func1_until_func2_or_timeout(func1,func2,args1=None,args2=None,
message=None,pause=10,timeout=120):
"""
Continue to call func1 until func2 returns True, and then return True. If
the loop times out, return False.
Parameters
==========
func1 - The action function to loop
args1 - Arguments to pass to the action function
func2 - The query function to check after each call to func1
args2 - Arguments to pass to the query function
message - A message to print to the screen on each iteration
pause - How long to puase between each iteration (seconds)
timeout - How long to allow this loop to run before terminating (seconds)
"""
timeout_time = time.time() + timeout
while time.time() < timeout_time:
if message: print(message)
func1() if not args1 else func1(*args1)
if (func2() if not args2 else func2(*args2)):
return True
time.sleep(pause)
return False
#
# This is basically a common case of the previous function - often you
# just have one function that does stuff and returns True if successful
# and False if failed. Say you want to keep looping that function until
# it returns True. Enter this guy:
#
def loop_func_until_true_or_timeout(func,args=None,message=None,pause=10,
timeout=120):
"""
Continue to call the given function until it returns True, and then return
True. If the loop times out, return False.
Parameters
==========
func - The function
args - Arguments to pass to the function
message - A message to print to the screen on each iteration
pause - How long to puase between each iteration (seconds)
timeout - How long to allow this loop to run before terminating (seconds)
"""
#
# Split up func into action and query methods:
# execute() calls func() and then stores its result in self.result
# check() checks result of execute() by returning self.result
#
class FuncSplitter(object):
def __init__(self,func,args):
self.func = func
self.args = args
def execute(self):
if not self.args:
self.result = func()
else:
self.result = func(*args)
def check(self):
return self.result
split = FuncSplitter(func,args)
execute = split.execute
check = split.check
return loop_func1_until_func2_or_timeout(execute,check,message=message,
pause=pause,timeout=timeout)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment