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): 9 '''Allows defining custom help actions. 10 11 Help actions can run even when the parser would otherwise fail on missing 12 arguments. The first help or custom help command mentioned on the command 13 line will have its help text displayed. 14 15 Usage: 16 parser = argparse.ArgumentParser(...) 17 CustomHelpAction.EnableFor(parser) 18 parser.add_argument('--foo-help', 19 action='custom_help', 20 custom_help_text='this is the help message', 21 help='What this helps with') 22 ''' 23 # Derived from argparse._HelpAction from 24 # https://github.com/python/cpython/blob/master/Lib/argparse.py 25 26 # pylint: disable=redefined-builtin 27 # (complains about 'help' being redefined) 28 def __init__(self, 29 option_strings, 30 dest=argparse.SUPPRESS, 31 default=argparse.SUPPRESS, 32 custom_help_text=None, 33 help=None): 34 super(CustomHelpAction, self).__init__(option_strings=option_strings, 35 dest=dest, 36 default=default, 37 nargs=0, 38 help=help) 39 40 if not custom_help_text: 41 raise ValueError('custom_help_text is required') 42 self._help_text = custom_help_text 43 44 def __call__(self, parser, namespace, values, option_string=None): 45 print self._help_text 46 parser.exit() 47 48 @staticmethod 49 def EnableFor(parser): 50 parser.register('action', 'custom_help', CustomHelpAction) 51