Created
August 12, 2017 19:01
-
-
Save junmakii/1bf3e73d8d2aa1a9973f57c37b73f7d0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, v in options.items(): | |
| if not isinstance(v, dict): | |
| 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_options.append({ | |
| u"args": ( | |
| ([option_string] if option_string else []) | |
| + [u'--%s' % k]), | |
| u"default": v, | |
| u"help": u"_", | |
| u"action": filter( | |
| None, | |
| [cond(v) for cond in conds])[0] | |
| }) | |
| else: | |
| command_options.append(v) | |
| 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