[Tutor] Repeat function until...

Steven D'Aprano steve at pearwood.info
Wed Jun 23 15:51:25 CEST 2010


On Wed, 23 Jun 2010 10:29:11 pm Nethirlon . wrote:
> Hello everyone,
>
> I'm new at programming with python and have a question about how I
> can solve my problem the correct way. Please forgive my grammar,
> English is not my primary language.
>
> I'm looking for a way to repeat my function every 30 seconds.


The easiest way is to just run forever, and stop when the user 
interrupts it with ctrl-D (or ctrl-Z on Windows):

# untested
def call_again(n, func, *args):
    """call func(*args) every n seconds until ctrl-D"""
    import time
    try:
        while 1:
            start = time.time()
            func(*args)
            time.sleep(n - (time.time()-start))
    except KeyboardInterrupt:
        pass

Of course, that wastes a lot of time sleeping.

As an alternative, you need to look at threads. That's a big topic, you 
probably need to read a How To or three on threads.

In the meantime, here are a couple of recipes I found by googling. I 
have no idea of they are good or not.

http://code.activestate.com/recipes/576726-interval-execute-a-function/
http://code.activestate.com/recipes/65222-run-a-task-every-few-seconds/



> As an example I have written a ping function. But I would like this
> function to repeat itself every 30 seconds, without stopping until I
> give it a STOP command (if such a thing exists.)
>
> Code:
> import os, sys
>
> def check(host):
>     try:
>         output = os.popen('ping -ns 1 %s' % host).read()
>         alive = output.find('Reply from')
>         print alive
>         if alive is -1:
>             print '%s \t\t DOWN ' % host
>         else:
>             print '%s \t\t OK' % host
>     except OSError, e:
>         print e
>         sys.exit()

Why are you catching the exception, only to print it and exit? Python 
does that automatically. This much easier, and doesn't throw away 
useful information:

def check(host):
    output = os.popen('ping -ns 1 %s' % host).read()
    alive = output.find('Reply from')
    print alive
    if alive is -1:
        print '%s \t\t DOWN ' % host
    else:
        print '%s \t\t OK' % host





-- 
Steven D'Aprano


More information about the Tutor mailing list