views:

60

answers:

2

I want to allow arbitrary command line arguments. If the user provides me with a command line that looks like this

myscript.py --a valueofa --b valueofb posarg1 posarg2

I know that a was passed with valueofa, b passed with valueofb and that I have these last two positional arguments.

I've always used optparse, for which you specify exactly which arguments to look for. But I want the user to be able to define arbitrary "macros" from the command line. Surely there's a python module that does it more elegantly than anything I'd write. What is?

+2  A: 

Sadly, you can't. If you have to support this, you'll need to write your own option parser =(.

katrielalex
A: 

Will argparse do what you want? It was recently added to the standard library. Specifically, you might want to look at this section of the documentation.

Forest
I think it doesn't: "The parse_args method attempts to give errors whenever the user has clearly made a mistake" means that undefined arguments will cause errors. In fact, I think this is deliberate behaviour -- it's not often that you want to allow e.g. spelling mistakes.
katrielalex