Skip to content

Instantly share code, notes, and snippets.

@junmakii
Created August 12, 2017 19:30
Show Gist options
  • Select an option

  • Save junmakii/0017db353729ac8f4296a02da5738bca to your computer and use it in GitHub Desktop.

Select an option

Save junmakii/0017db353729ac8f4296a02da5738bca to your computer and use it in GitHub Desktop.
import argparse
import string
def get_command_options(
options={},
exclude_letters=[u'h'],
conds=[
(lambda v: u'store'
if isinstance(v, (int, float, str, unicode))
else None),
(lambda v: (u'store_false' if v else u'store_true')
if isinstance(v, bool)
else None),
(lambda v: u'append'
if isinstance(v, list)
else None),
(lambda v: u'store'),
]
):
""""
:rtype: [dict]
>>> options = {
... "name": "DEFAULT_NAME",
... "number": 1,
... "notification": False}
>>> get_command_options(options)
[{u'default': False, u'action': u'store', u'args': [u'-n', u'--notification'], u'help': u'_'}, {u'default': 'DEFAULT_NAME', u'action': u'store', u'args': [u'-N', u'--name'], u'help': u'_'}, {u'default': 1, u'action': u'store', u'args': [u'-a', u'--number'], u'help': u'_'}]
"""
option_strings = []
command_options = []
for k, item in options.items():
if not isinstance(item, dict):
item = {u"default": item}
option_string = ([
i for i in [
u'-%s' % l for l in (
[k[0], k[0].upper()]
+ list(string.ascii_letters))
if l not in exclude_letters
] if i not in option_strings
] or [None])[0]
option_strings.append(option_string)
command_option_strings = (
([option_string] if option_string else [])
+ [u'--%s' % k])
command_options.append({
u"args": command_option_strings,
u"default": item.get(u'default', None),
u"help": item.get(u'help', u'_'),
u"action": (
item.get('action')
if item.get('action', None)
else filter(None,
[cond(item.get(u'default', ''))
for cond in conds])[0])
})
return command_options
def parse_args(
argv,
options={},
parser=None,
subparsers=None,
):
"""
:rtype: dict
>>> parse_args(['-n', '1', '-N', '4'],
... {"number": 0, "numbers": ['1', '2', '3']})
{'number': '1', 'numbers': ['1', '2', '3', '4']}
"""
argument_options = get_command_options(options)
parser = (
parser
if parser
else argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
# formatter_class=argparse.RawDescriptionHelpFormatter,
))
for argument in argument_options:
_args = argument.get('args', [])
del argument['args']
parser.add_argument(*_args, **argument)
parsed_options = vars(parser.parse_args(argv))
return parsed_options
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment