Set a default choice for optionparser when the option is given

Question:

I have a python option parsers that parses an optional –list-something option.
I also want the –list-something option to have an optional argument (an option)

Using the argument default="simple" does not work here, otherwise simple will always
be the default, not only when –list-something was given.

from optparse import OptionParser, OptionGroup
parser = OptionParser()
options = OptionGroup(parser, "options")
options.add_option("--list-something",
                   type="choice",
                   choices=["simple", "detailed"],
                   help="show list of available things"
                  )
parser.add_option_group(options)
opts, args = parser.parse_args()
print opts, args

The above code is producing this:

[jens@ca60c173 ~]$ python main.py --list-something simple
{'list_something': 'simple'} []
[jens@ca60c173 ~]$ python main.py --list-something 
Usage: main.py [options]

main.py: error: --list-something option requires an argument
[jens@ca60c173 ~]$ python main.py 
{'list_something': None} []

But I want this to hapen:

[jens@ca60c173 ~]$ python main.py --list-something simple
{'list_something': 'simple'} []
[jens@ca60c173 ~]$ python main.py --list-something 
{'list_something': 'simple'} []
[jens@ca60c173 ~]$ python main.py 
{'list_something': None} []

I would like something that works out of the box in python 2.4 up till 3.0 (3.0 not included)

Since argparse is only introduced in python 2.7 this is not something I could use.

Asked By: Jens Timmerman

||

Answers:

Optparse does not have any options for doing this easily. Instead you’ll have to create a custom callback for your option. The callback is triggered when your option is parsed, at which point, you can check the remaining args to see if the user put an argument for the option.

Check out the custom callback section of the docs, in particular Callback example 6: variable arguments.

Answered By: AFoglia

There is no default for the Optparser in python.
However, you can use the follwing –

# show help as default
if len(sys.argv) == 1:
  os.system(sys.argv[0] + " -h")
  exit()

This will run the same script with the -h option, and exit.
please notice – you will need to import the sys module.

Answered By: Gilad Sharaby