Search code examples
pythongetopt

Why does the getopt method have getopt(args, options[, long_options]) not getopt(args, options,[ long_options]) as its signature?


I'm writing some code for a command line program and I'm using the getopt() function. Can someone explain the options / long_options syntax?

getopt.getopt(args, options[, long_options])

My question is this:

Why does is the list fragmented between arguments? why is it options[ not options?


Solution

  • The function has 2 required arguments (args and options) and one option that is not required (long_options). The exact meaning of args, options and long_options can all be found in the documentation

    Basically, if you want the commandline to be parsed as:

    myprogram --foo=bar
    

    Then you need to have a long_options list which looks something like ['--foo='], but if you want to parse it as:

    myprogram -f bar
    

    then you would have options set to 'f:'. Of course, you can mix and match as much as you want.

    For what its worth, I would never recommend anyone use getopt in favor of optparse or (even better) argparse. These later two modules make working with getopt feel like trying to use a hammer to build yourself a new computer ...