Search code examples
pythongetopt

Parsing command line arguments in a python script (getopt woes)


Can anyone spot why the following script is not printing the passed arguments?

import sys, getopt

def usage():
    print 'Unknown arguments'

def main(argv):
    try:
        opts, args = getopt.getopt(argv,'fdmse:d',['files=','data-source=','mode=','start','end'])

    except getopt.GetoptError:
        usage()
        sys.exit(999)

    for opt, arg in opts:
        # print opt,arg 
        if opt in('-f','--files'):
            print 'files: ', arg  #

if __name__ == "__main__":
    main(sys.argv[1:])

When I run the script at the command line and pass the arguments -f=dummy.csv, usage() seems to be invoked instead - WHY?

BTW, I find the logic of the program flow a bit weird (I copied it from here). Normally, I would have thought that the logic will be implemented in the try branch, and then AFTER that comes the exception handler.

Is this (as pasted in the code above) the 'Pythonic' way to write try/catch blocks?


Solution

  • Normally, I would have thought that the logic will be implemented in the try branch

    "Normally"? What does normally mean?

    What is the program supposed to do? What exceptions make sense? What does the program do in response to the exceptions.

    There's no "normally". Any more than there's a normal assignment statement or a normal function definition.

    Your program does what makes sense to achieve the required end-state. There's no "normally".