[Tutor] Repeat function until...

Adam Bark adam.jtm30 at gmail.com
Wed Jun 23 15:38:49 CEST 2010


On 23 June 2010 13:29, Nethirlon . <nethirlon at gmail.com> 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.
>
> 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()
>
> check('www.google.com')
>
> Let me know if anything is unclear or if there are other
> recommendations about doing some parts different.
>
> Kind regards,
> Nethirlon
>

You should probably take a look at the time module
http://docs.python.org/library/time.html for waiting (maybe time.sleep)

If you want to call a function an unspecified number of times you probably
want a while loop:

while True:
    pass

loops infinitely unless you quit the program though, to leave the loop you
will need to use "break", you will probably want an if statement and change
the value of some variable when you want to stop calling the function and
break out of the loop.

HTH,
Adam.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100623/eaad4ac3/attachment.html>


More information about the Tutor mailing list