Recently I wrote a driver program in python on windows that needed to run once or if given a command line switch, would run indefinitely. Could have done this with a while loop, but started to wonder whether any of the operations in the itertools package could this cleaner.

Here’s what I landed on.

import itertools
import argparse

def parseArguments():
    parser = argparse.ArgumentParser(description='go once or many')
    parser.add_argument("--repeat", action="store_true")
    return(parser.parse_args())

def main():
    opts = parseArguments()

    if opts.repeat:
        outer = itertools.count(0)
    else:
        outer = iter(range(1,2))

    for i in outer:
        ##lots of stuff to do here or only one thing to do.
        print(i)

if __name__ == "__main__":
    main()

For example

If run without the command line switch “–repeat” the program only produces one loop:

python commandline_infinite.py
1

However when run with the command line switch, the program will iterate infinitely.

python commandline_infinite.py --repeat | head
0
1
2
3
4
5
...

I like this approach because the body of the loop is does not contain any of the control logic related to the infinite loop.