Chromium Code Reviews| OLD | NEW |
|---|---|
| (Empty) | |
| 1 # Copyright 2015 The Chromium Authors. All rights reserved. | |
| 2 # Use of this source code is governed by a BSD-style license that can be | |
| 3 # found in the LICENSE file. | |
| 4 | |
| 5 import argparse | |
| 6 | |
| 7 | |
| 8 class CustomHelpAction(argparse.Action): | |
|
jbudorick
2015/12/10 14:16:31
Sweet!
| |
| 9 ''' | |
| 10 Allows defining custom help actions. Help actions can run even when the | |
|
jbudorick
2015/12/10 14:16:31
nit: docstrings should be
'''Summary sentence.
M
dgn
2015/12/10 21:12:57
Done.
| |
| 11 parser would otherwise fail on missing arguments. The first help or custom | |
| 12 help command mentioned on the command line will have its help text displayed. | |
| 13 | |
| 14 Usage: | |
| 15 parser = argparse.ArgumentParser(...) | |
| 16 CustomHelpAction.EnableFor(parser) | |
| 17 parser.add_argument('--foo-help', | |
| 18 action='custom_help', | |
| 19 custom_help_text='this is the help message', | |
| 20 help='What this helps with') | |
| 21 ''' | |
| 22 # Derived from argparse._HelpAction from | |
| 23 # https://github.com/python/cpython/blob/master/Lib/argparse.py | |
| 24 | |
| 25 # pylint: disable=redefined-builtin | |
| 26 # (complains about 'help' being redefined) | |
| 27 def __init__(self, | |
| 28 option_strings, | |
| 29 dest=argparse.SUPPRESS, | |
| 30 default=argparse.SUPPRESS, | |
| 31 custom_help_text=None, | |
| 32 help=None): | |
| 33 super(CustomHelpAction, self).__init__(option_strings=option_strings, | |
| 34 dest=dest, | |
| 35 default=default, | |
| 36 nargs=0, | |
| 37 help=help) | |
| 38 | |
| 39 if not custom_help_text: | |
| 40 raise ValueError('custom_help_text is required') | |
| 41 self._help_text = custom_help_text | |
| 42 | |
| 43 def __call__(self, parser, namespace, values, option_string=None): | |
| 44 print self._help_text | |
| 45 parser.exit() | |
| 46 | |
| 47 @staticmethod | |
| 48 def EnableFor(parser): | |
| 49 parser.register('action', 'custom_help', CustomHelpAction) | |
| OLD | NEW |