1

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.

dan1st
  • 12,568
  • 8
  • 34
  • 67
Jens Timmerman
  • 9,316
  • 1
  • 42
  • 48
  • I think this is easy to do with `argparse`. I've used `argparse` with python2.6 -- I'm not sure how far back it will work though ... – mgilson Oct 15 '12 at 14:51
  • Thank you for that suggestion, however I'm unable to use any external dependencies, so I updated my question that I would like it to work out of the box on python 2.4-3.0 – Jens Timmerman Oct 15 '12 at 14:59

2 Answers2

1

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.

AFoglia
  • 7,968
  • 3
  • 35
  • 51
  • A custom callback was the solution, I also found a similar question which answered mine: http://stackoverflow.com/questions/1229146/parsing-empty-options-in-python – Jens Timmerman Oct 23 '12 at 07:45
0

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.

Gilad Sharaby
  • 910
  • 9
  • 12