Per Erik Strandberg /cv /kurser /blog

This little python example runs nicely in python 2 and 3 (see also Nyheter Med Python 3 for more on the news in python 3). It parses command line options in do_parse(), and has an extremely simple method, count, that does the real magic. Download it from here: [1]

from optparse import OptionParser

try:
    yrange = xrange # python 2
except:
    yrange = range # python 3 fix

def do_parse():

    usage = """Usage:
        %(name)s -b B -e E    --  where B, and E are integers

Example:
        %(name)s -b 1 -e 10   --  Counts from 1 to 10
""" % {"name": "my-python-template"}

    parser = OptionParser(usage=usage)
    parser.add_option('-b', dest='b', help="Beginning")
    parser.add_option('-e', dest='e', help="Ending.")
    (options, args) = parser.parse_args()

    try:
        options.b = int(options.b)
    except:
        parser.error("Bad parameter b.")

    try:
        options.e = int(options.e)
    except:
        parser.error("Bad parameter e.")

    if options.e < options.b:
        parser.error("Ending is before beginning.")

    return (options, args)


def count(a, d):
    results = list()
    for i in yrange(a, d):
        results.append(str(i))

    if results:
        print (" ".join(results))

if __name__ == '__main__':
    (options, args) = do_parse()
    count(options.b, options.e)


This page belong to Kategori Mallar