[Python-Dev] PEP 389: argparse - new command line parsing module (original) (raw)

Brett Cannon brett at python.org
Tue Sep 29 08:34:24 CEST 2009


On Mon, Sep 28, 2009 at 20:44, "Martin v. Löwis" <martin at v.loewis.de> wrote:

Let's take getopt.getopt(sys.argv[1:], "a:b", ["alpha=", "beta"]) as an example and simply assume that 'alpha' takes a string as an argument and that it's required and that 'beta' is a boolean flag. To pull everything out you could do::

options, args = getopt.getopt(sys.argv[1:], "a:b", ["alpha=", "beta"]) optionsdict = dict(options) alpha = optionsdict.get('-a', optionsdict.get('--alpha', '')) beta = '-b' in optionsdict or '--beta' in optionsdict main(alpha, beta, args) Obviously if one of the getopt supporters has a better way of doing this then please speak up. As Yuvgoog Greenle says, the canonical getopt way is to write alpha = None beta = False options, args = getopt.getopt(sys.argv[1:],"a:b",['alpha=','beta']): for opt, val in options:  if arg in ('-a','--alpha'):  alpha = val  elif arg in ('-b','--beta'):  beta = True main(alpha, beta, args) Even though this is many more lines, I prefer it over optparse/argparse: this code has only a single function call, whereas the argparse version has three function calls to remember. The actual processing uses standard Python data structures which I don't need to look up in the documentation. Now, Steven, can you show how best to do this in argparse? This demonstrates my point: you were able to use getopt right away (even though not in the traditional way), whereas you need to ask for help on using argparse properly.

Actually, I had to read the docs for getopt. And I chose to not even try argparse when the creator of the module is cc'ed on the email and can obviously do a better example using his own code then I could.

-Brett



More information about the Python-Dev mailing list