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