I l@ve RuBoard Previous Section Next Section

7.2 Running a Command Repeatedly

Credit: Philip Nunez

7.2.1 Problem

You need to run a command repeatedly, with arbitrary periodicity.

7.2.2 Solution

The time.sleep function offers a simple approach to this task:

import time, os, sys, string

def main(cmd, inc=60):
    while 1:
        os.system(cmd)
        time.sleep(inc)

if _ _name_ _ == '_ _main_ _' :
    if len(sys.argv) < 2 or len(sys.argv) > 3:
        print "usage: " + sys.argv[0] + " command [seconds_delay]"
        sys.exit(1)

    cmd = sys.argv[1]
    if len(sys.argv) < 3:
        main(cmd)
    else:
        inc = string.atoi(sys.argv[2])
        main(cmd, inc)

7.2.3 Discussion

You can use this recipe with a command that periodically checks for something (e.g., polling) or performs an endlessly-repeating action, such as telling a browser to reload a URL whose contents change often, so you always have a recent version of that URL up for viewing. The recipe is structured into a function called main and a body that is preceded by the usual if _ _name_ _=='_ _main_ _': idiom, which ensures that the body executes only if the script runs as a main script. The body examines the command-line arguments you used with the script and calls main appropriately (or gives a usage message if there are too many or too few arguments). This is always the best way to structure a script, so its key functionality is also available to other scripts that may import it as a module.

The main function accepts a cmd string, which is a command you should pass periodically to the operating system's shell, and, optionally, a period of time in seconds, with a default value of 60 (one minute). main loops forever, alternating between executing the command with os.system and waiting (without consuming resources) with time.sleep.

The script's body looks at the command-line arguments you used with the script, which are found in sys.argv. The first, sys.argv[0], is the name of the script, often useful when the script identifies itself as it prints out messages. The body checks that there are one or two other arguments in addition to this name. The first (mandatory) is the command to be run. The second (optional) is the delay in seconds between two runs of the command. If the second argument is missing, the body calls main just with the command argument, accepting the default delay (of 60 seconds). Note that if there is a second argument, the body must transform it from a string (all items in sys.argv are always strings) into an integer. In modern Python, you would do this with the int built-in function:

inc = int(sys.argv[2])

But the recipe is coded in such a way as to work even with old versions of Python that did not allow you to use int in this way.

7.2.4 See Also

Documentation of the standard library modules os and time in the Library Reference.

    I l@ve RuBoard Previous Section Next Section