Set a default choice for optionparser when the option is given

一个人想着一个人 提交于 2019-12-11 06:24:54

问题


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.


回答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.




回答2:


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.



来源:https://stackoverflow.com/questions/12898153/set-a-default-choice-for-optionparser-when-the-option-is-given

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!