Python argparse.HelpFormatter() Examples

The following are code examples for showing how to use argparse.HelpFormatter(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: python-bileanclient   Author: openstack   File: shell.py    (license) View Source Project 6 votes vote down vote up
def _find_actions(self, subparsers, actions_module):
        for attr in (a for a in dir(actions_module) if a.startswith('do_')):
            # Replace underscores with hyphens in the commands
            # displayed to the user
            command = attr[3:].replace('_', '-')
            callback = getattr(actions_module, attr)
            desc = callback.__doc__ or ''
            help = desc.strip().split('\n')[0]
            arguments = getattr(callback, 'arguments', [])

            subparser = subparsers.add_parser(command,
                                              help=help,
                                              description=desc,
                                              add_help=False,
                                              formatter_class=HelpFormatter
                                              )
            subparser.add_argument('-h', '--help',
                                   action='help',
                                   help=argparse.SUPPRESS,
                                   )
            self.subcommands[command] = subparser
            for (args, kwargs) in arguments:
                subparser.add_argument(*args, **kwargs)
            subparser.set_defaults(func=callback) 
Example 2
Project: python-karborclient   Author: openstack   File: shell.py    (license) View Source Project 6 votes vote down vote up
def _find_actions(self, subparsers, actions_module):
        for attr in (a for a in dir(actions_module) if a.startswith('do_')):
            # I prefer to be hypen-separated instead of underscores.
            command = attr[3:].replace('_', '-')
            callback = getattr(actions_module, attr)
            desc = callback.__doc__ or ''
            help = desc.strip().split('\n')[0]
            arguments = getattr(callback, 'arguments', [])

            subparser = subparsers.add_parser(command, help=help,
                                              description=desc,
                                              add_help=False,
                                              formatter_class=HelpFormatter)
            subparser.add_argument('-h', '--help', action='help',
                                   help=argparse.SUPPRESS)
            self.subcommands[command] = subparser
            for (args, kwargs) in arguments:
                subparser.add_argument(*args, **kwargs)
            subparser.set_defaults(func=callback) 
Example 3
Project: eclcli   Author: nttcom   File: shell.py    (license) View Source Project 6 votes vote down vote up
def _find_actions(self, subparsers, actions_module):
        for attr in (a for a in dir(actions_module) if a.startswith('do_')):
            # I prefer to be hyphen-separated instead of underscores.
            command = attr[3:].replace('_', '-')
            callback = getattr(actions_module, attr)
            desc = callback.__doc__ or ''
            help = desc.strip().split('\n')[0]
            arguments = getattr(callback, 'arguments', [])

            subparser = subparsers.add_parser(command,
                                              help=help,
                                              description=desc,
                                              add_help=False,
                                              formatter_class=HelpFormatter)
            subparser.add_argument('-h', '--help',
                                   action='help',
                                   help=argparse.SUPPRESS)
            self.subcommands[command] = subparser
            for (args, kwargs) in arguments:
                subparser.add_argument(*args, **kwargs)
            subparser.set_defaults(func=callback) 
Example 4
Project: python-cratonclient   Author: openstack   File: main.py    (license) View Source Project 6 votes vote down vote up
def _find_subparsers(self, subparsers, actions_module):
        """Find subparsers by looking at *_shell files."""
        help_formatter = argparse.HelpFormatter
        for attr in (a for a in dir(actions_module) if a.startswith('do_')):
            command = attr[3:].replace('_', '-')
            callback = getattr(actions_module, attr)
            desc = callback.__doc__ or ''
            action_help = desc.strip()
            arguments = getattr(callback, 'arguments', [])
            subparser = (subparsers.add_parser(command,
                                               help=action_help,
                                               description=desc,
                                               add_help=False,
                                               formatter_class=help_formatter)
                         )
            subparser.add_argument('-h', '--help',
                                   action='help',
                                   help=argparse.SUPPRESS)
            self.subcommands[command] = subparser
            for (args, kwargs) in arguments:
                subparser.add_argument(*args, **kwargs)
            subparser.set_defaults(func=callback) 
Example 5
Project: zaqar-demo   Author: openstacker   File: zaqar_demo.py    (license) View Source Project 6 votes vote down vote up
def _find_actions(self, subparsers, actions_module):
        for attr in (a for a in dir(actions_module) if a.startswith('do_')):
            command = attr[3:].replace('_', '-')
            callback = getattr(actions_module, attr)
            desc = callback.__doc__ or ''
            help = desc.strip().split('\n')[0]
            arguments = getattr(callback, 'arguments', [])

            subparser = subparsers.add_parser(command,
                                              help=help,
                                              description=desc,
                                              add_help=False,
                                              formatter_class=HelpFormatter
                                              )
            subparser.add_argument('-h', '--help',
                                   action='help',
                                   help=argparse.SUPPRESS,
                                   )
            self.subcommands[command] = subparser
            for (args, kwargs) in arguments:
                subparser.add_argument(*args, **kwargs)
            subparser.set_defaults(func=callback) 
Example 6
Project: python-masakariclient   Author: openstack   File: shell.py    (license) View Source Project 6 votes vote down vote up
def _find_actions(self, subparsers, actions_module):
        for attr in (a for a in dir(actions_module) if a.startswith('do_')):
            command = attr[3:].replace('_', '-')
            callback = getattr(actions_module, attr)

            desc = callback.__doc__ or ''
            help = desc.strip().split('\n')[0]
            arguments = getattr(callback, 'arguments', [])

            subparser = subparsers.add_parser(command,
                                              help=help,
                                              description=desc,
                                              add_help=False,
                                              formatter_class=HelpFormatter)

            subparser.add_argument('-h', '--help',
                                   action='help',
                                   help=argparse.SUPPRESS)

            for (args, kwargs) in arguments:
                subparser.add_argument(*args, **kwargs)
            subparser.set_defaults(func=callback)

            self.subcommands[command] = subparser 
Example 7
Project: hostapd-mana   Author: adde88   File: config.py    (license) View Source Project 5 votes vote down vote up
def _format_action_invocation(self, action):
        orgstr = argparse.HelpFormatter._format_action_invocation(self, action)
        if orgstr and orgstr[0] != '-': # only optional arguments
            return orgstr
        res = getattr(action, '_formatted_action_invocation', None)
        if res:
            return res
        options = orgstr.split(', ')
        if len(options) == 2 and (len(options[0]) == 2 or len(options[1]) == 2):
            # a shortcut for '-h, --help' or '--abc', '-a'
            action._formatted_action_invocation = orgstr
            return orgstr
        return_list = []
        option_map =  getattr(action, 'map_long_option', {})
        if option_map is None:
            option_map = {}
        short_long = {}
        for option in options:
            if len(option) == 2 or option[2] == ' ':
                continue
            if not option.startswith('--'):
                raise ArgumentError('long optional argument without "--": [%s]'
                                    % (option), self)
            xxoption = option[2:]
            if xxoption.split()[0] not in option_map:
                shortened = xxoption.replace('-', '')
                if shortened not in short_long or \
                   len(short_long[shortened]) < len(xxoption):
                    short_long[shortened] = xxoption
        # now short_long has been filled out to the longest with dashes
        # **and** we keep the right option ordering from add_argument
        for option in options: #
            if len(option) == 2 or option[2] == ' ':
                return_list.append(option)
            if option[2:] == short_long.get(option.replace('-', '')):
                return_list.append(option.replace(' ', '='))
        action._formatted_action_invocation = ', '.join(return_list)
        return action._formatted_action_invocation 
Example 8
Project: argparseinator   Author: ellethee   File: __init__.py    (license) View Source Project 5 votes vote down vote up
def _split_lines(self, text, width):
        if fun_check(text):
            return [l for l in text.splitlines(True) if not fun_comment(l)]
        return [
            l for l in argparse.HelpFormatter._split_lines(self, text, width)
            if not fun_comment(l)] 
Example 9
Project: python-bileanclient   Author: openstack   File: shell.py    (license) View Source Project 5 votes vote down vote up
def _add_bash_completion_subparser(self, subparsers):
        subparser = subparsers.add_parser('bash_completion',
                                          add_help=False,
                                          formatter_class=HelpFormatter)
        self.subcommands['bash_completion'] = subparser
        subparser.set_defaults(func=self.do_bash_completion) 
Example 10
Project: python-bileanclient   Author: openstack   File: shell.py    (license) View Source Project 5 votes vote down vote up
def start_section(self, heading):
        # Title-case the headings
        heading = '%s%s' % (heading[0].upper(), heading[1:])
        super(HelpFormatter, self).start_section(heading) 
Example 11
Project: cheribuild   Author: CTSRD-CHERI   File: loader.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, option_cls):
        self.__option_cls = option_cls
        self._parser = argparse.ArgumentParser(formatter_class=
                                      lambda prog: argparse.HelpFormatter(prog, width=shutil.get_terminal_size()[0])) 
Example 12
Project: coquery   Author: gkunter   File: options.py    (license) View Source Project 5 votes vote down vote up
def optionxform(self, strOut):
        return strOut


# Define a HelpFormatter class that works with Unicode corpus names both in
# Python 2.7 and Python 3.x: 
Example 13
Project: notebook-molecular-visualization   Author: Autodesk   File: __main__.py    (license) View Source Project 5 votes vote down vote up
def _split_lines(self, text, width):
        if text.startswith('R|'):
            return text[2:].splitlines()
        # this is the RawTextHelpFormatter._split_lines
        return argparse.HelpFormatter._split_lines(self, text, width) 
Example 14
Project: vickitrix   Author: nellore   File: __init__.py    (license) View Source Project 5 votes vote down vote up
def help_formatter(prog):
    """ So formatter_class's max_help_position can be changed. """
    return argparse.HelpFormatter(prog, max_help_position=40) 
Example 15
Project: zippy   Author: securesystemslab   File: test_argparse.py    (license) View Source Project 5 votes vote down vote up
def test_parser(self):
        parser = argparse.ArgumentParser(prog='PROG')
        string = (
            "ArgumentParser(prog='PROG', usage=None, description=None, "
            "version=None, formatter_class=%r, conflict_handler='error', "
            "add_help=True)" % argparse.HelpFormatter)
        self.assertStringEqual(parser, string)

# ===============
# Namespace tests
# =============== 
Example 16
Project: snap-plugin-lib-py   Author: intelsdi-x   File: plugin.py    (license) View Source Project 5 votes vote down vote up
def __init__(self):
        self.meta = None
        self.proxy = None
        self.server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
        self._port = 0
        self._last_ping = time.time()
        self._shutting_down = False
        self._monitor = None
        self._mode = PluginMode.normal
        self._config = {}
        self._flags = _Flags()
        self.standalone_server = None

        # init argparse module and add arguments
        self._parser = argparse.ArgumentParser(description="%(prog)s - a Snap framework plugin.",
                                               usage="%(prog)s [options]",
                                               formatter_class=lambda prog:
                                               argparse.HelpFormatter(prog, max_help_position=30))
        self._parser.add_argument("framework_config", nargs="?", default=None, help=argparse.SUPPRESS)

        flags = [
            ("config", FlagType.value, "JSON Snap global config"),
            ("port", FlagType.value, "GRPC server port"),
            ("stand-alone", FlagType.toggle, "enable stand alone mode"),
            ("stand-alone-port", FlagType.value, "http port for stand alone mode", 8182),
            Flag("log-level", FlagType.value, "logging level 0:panic - 5:debug", 3, json_name="LogLevel"),
            Flag("tls", FlagType.toggle, "enable tls", json_name="TLSEnabled"),
            Flag("root-cert-paths", FlagType.value, "paths to root certificate; delimited by ':'", json_name="RootCertPaths"),
            Flag("key-path", FlagType.value, "path to server private key", json_name="KeyPath"),
            Flag("cert-path", FlagType.value, "path to server certificate", json_name="CertPath"),
        ]
        self._flags.add_multiple(flags) 
Example 17
Project: keras_experiments   Author: avolkov1   File: resnet50_tfrecord_horovod.py    (license) View Source Project 5 votes vote down vote up
def _split_lines(self, text, width):
        # this is the RawTextHelpFormatter._split_lines
        if text.startswith('S|'):
            return text[2:].splitlines()
        return ap.HelpFormatter._split_lines(self, text, width) 
Example 18
Project: oil   Author: oilshell   File: test_argparse.py    (license) View Source Project 5 votes vote down vote up
def test_parser(self):
        parser = argparse.ArgumentParser(prog='PROG')
        string = (
            "ArgumentParser(prog='PROG', usage=None, description=None, "
            "version=None, formatter_class=%r, conflict_handler='error', "
            "add_help=True)" % argparse.HelpFormatter)
        self.assertStringEqual(parser, string)

# ===============
# Namespace tests
# =============== 
Example 19
Project: python2-tracer   Author: extremecoders-re   File: test_argparse.py    (license) View Source Project 5 votes vote down vote up
def test_parser(self):
        parser = argparse.ArgumentParser(prog='PROG')
        string = (
            "ArgumentParser(prog='PROG', usage=None, description=None, "
            "version=None, formatter_class=%r, conflict_handler='error', "
            "add_help=True)" % argparse.HelpFormatter)
        self.assertStringEqual(parser, string)

# ===============
# Namespace tests
# =============== 
Example 20
Project: sslstrip-hsts-openwrt   Author: adde88   File: config.py    (license) View Source Project 5 votes vote down vote up
def _format_action_invocation(self, action):
        orgstr = argparse.HelpFormatter._format_action_invocation(self, action)
        if orgstr and orgstr[0] != '-': # only optional arguments
            return orgstr
        res = getattr(action, '_formatted_action_invocation', None)
        if res:
            return res
        options = orgstr.split(', ')
        if len(options) == 2 and (len(options[0]) == 2 or len(options[1]) == 2):
            # a shortcut for '-h, --help' or '--abc', '-a'
            action._formatted_action_invocation = orgstr
            return orgstr
        return_list = []
        option_map =  getattr(action, 'map_long_option', {})
        if option_map is None:
            option_map = {}
        short_long = {}
        for option in options:
            if len(option) == 2 or option[2] == ' ':
                continue
            if not option.startswith('--'):
                raise ArgumentError('long optional argument without "--": [%s]'
                                    % (option), self)
            xxoption = option[2:]
            if xxoption.split()[0] not in option_map:
                shortened = xxoption.replace('-', '')
                if shortened not in short_long or \
                   len(short_long[shortened]) < len(xxoption):
                    short_long[shortened] = xxoption
        # now short_long has been filled out to the longest with dashes
        # **and** we keep the right option ordering from add_argument
        for option in options: #
            if len(option) == 2 or option[2] == ' ':
                return_list.append(option)
            if option[2:] == short_long.get(option.replace('-', '')):
                return_list.append(option.replace(' ', '='))
        action._formatted_action_invocation = ', '.join(return_list)
        return action._formatted_action_invocation 
Example 21
Project: python-karborclient   Author: openstack   File: shell.py    (license) View Source Project 5 votes vote down vote up
def start_section(self, heading):
        # Title-case the headings
        heading = '%s%s' % (heading[0].upper(), heading[1:])
        super(HelpFormatter, self).start_section(heading) 
Example 22
Project: ansible-role   Author: mattvonrocketstein   File: __init__.py    (license) View Source Project 5 votes vote down vote up
def get_parser():
    """ creates the parser for the ansible-role command line utility """
    parser = argparse.ArgumentParser(
        prog=os.path.split(sys.argv[0])[-1],
        formatter_class=HelpFormatter,)
    parser.add_argument('rolename', type=str, nargs=1,)
    parser.add_argument('host', type=str, nargs='?', default='localhost',)
    parser.add_argument('--module-path', '-M',)
    return parser 
Example 23
Project: Linkedin_profiles   Author: wpentester   File: linkedin_profiles.py    (license) View Source Project 5 votes vote down vote up
def _split_lines(self, text, width):
        if text.startswith('R|'):
            return text[2:].splitlines()
        # this is the RawTextHelpFormatter._split_lines
        return argparse.HelpFormatter._split_lines(self, text, width) 
Example 24
Project: web_ctp   Author: molebot   File: test_argparse.py    (license) View Source Project 5 votes vote down vote up
def test_parser(self):
        parser = argparse.ArgumentParser(prog='PROG')
        string = (
            "ArgumentParser(prog='PROG', usage=None, description=None, "
            "formatter_class=%r, conflict_handler='error', "
            "add_help=True)" % argparse.HelpFormatter)
        self.assertStringEqual(parser, string)

# ===============
# Namespace tests
# =============== 
Example 25
Project: godot-python   Author: touilleMan   File: config.py    (license) View Source Project 5 votes vote down vote up
def _format_action_invocation(self, action):
        orgstr = argparse.HelpFormatter._format_action_invocation(self, action)
        if orgstr and orgstr[0] != '-': # only optional arguments
            return orgstr
        res = getattr(action, '_formatted_action_invocation', None)
        if res:
            return res
        options = orgstr.split(', ')
        if len(options) == 2 and (len(options[0]) == 2 or len(options[1]) == 2):
            # a shortcut for '-h, --help' or '--abc', '-a'
            action._formatted_action_invocation = orgstr
            return orgstr
        return_list = []
        option_map =  getattr(action, 'map_long_option', {})
        if option_map is None:
            option_map = {}
        short_long = {}
        for option in options:
            if len(option) == 2 or option[2] == ' ':
                continue
            if not option.startswith('--'):
                raise ArgumentError('long optional argument without "--": [%s]'
                                    % (option), self)
            xxoption = option[2:]
            if xxoption.split()[0] not in option_map:
                shortened = xxoption.replace('-', '')
                if shortened not in short_long or \
                   len(short_long[shortened]) < len(xxoption):
                    short_long[shortened] = xxoption
        # now short_long has been filled out to the longest with dashes
        # **and** we keep the right option ordering from add_argument
        for option in options: #
            if len(option) == 2 or option[2] == ' ':
                return_list.append(option)
            if option[2:] == short_long.get(option.replace('-', '')):
                return_list.append(option.replace(' ', '=', 1))
        action._formatted_action_invocation = ', '.join(return_list)
        return action._formatted_action_invocation 
Example 26
Project: godot-python   Author: touilleMan   File: config.py    (license) View Source Project 5 votes vote down vote up
def _format_action_invocation(self, action):
        orgstr = argparse.HelpFormatter._format_action_invocation(self, action)
        if orgstr and orgstr[0] != '-': # only optional arguments
            return orgstr
        res = getattr(action, '_formatted_action_invocation', None)
        if res:
            return res
        options = orgstr.split(', ')
        if len(options) == 2 and (len(options[0]) == 2 or len(options[1]) == 2):
            # a shortcut for '-h, --help' or '--abc', '-a'
            action._formatted_action_invocation = orgstr
            return orgstr
        return_list = []
        option_map =  getattr(action, 'map_long_option', {})
        if option_map is None:
            option_map = {}
        short_long = {}
        for option in options:
            if len(option) == 2 or option[2] == ' ':
                continue
            if not option.startswith('--'):
                raise ArgumentError('long optional argument without "--": [%s]'
                                    % (option), self)
            xxoption = option[2:]
            if xxoption.split()[0] not in option_map:
                shortened = xxoption.replace('-', '')
                if shortened not in short_long or \
                   len(short_long[shortened]) < len(xxoption):
                    short_long[shortened] = xxoption
        # now short_long has been filled out to the longest with dashes
        # **and** we keep the right option ordering from add_argument
        for option in options: #
            if len(option) == 2 or option[2] == ' ':
                return_list.append(option)
            if option[2:] == short_long.get(option.replace('-', '')):
                return_list.append(option.replace(' ', '=', 1))
        action._formatted_action_invocation = ', '.join(return_list)
        return action._formatted_action_invocation 
Example 27
Project: pyekaboo   Author: SafeBreach-Labs   File: mkpyekaboo.py    (license) View Source Project 5 votes vote down vote up
def _split_lines(self, text, width):
        if text.startswith('ML|'):
            return text[3:].splitlines()
        # this is the RawTextHelpFormatter._split_lines
        return argparse.HelpFormatter._split_lines(self, text, width)


#############
# Functions #
############# 
Example 28
Project: eclcli   Author: nttcom   File: shell.py    (license) View Source Project 5 votes vote down vote up
def _add_bash_completion_subparser(self, subparsers):
        subparser = subparsers.add_parser(
            'bash_completion',
            add_help=False,
            formatter_class=HelpFormatter
        )
        self.subcommands['bash_completion'] = subparser
        subparser.set_defaults(func=self.do_bash_completion) 
Example 29
Project: eclcli   Author: nttcom   File: shell.py    (license) View Source Project 5 votes vote down vote up
def start_section(self, heading):
        # Title-case the headings
        heading = '%s%s' % (heading[0].upper(), heading[1:])
        super(HelpFormatter, self).start_section(heading) 
Example 30
Project: eclcli   Author: nttcom   File: shell.py    (license) View Source Project 5 votes vote down vote up
def _add_bash_completion_subparser(self, subparsers):
        subparser = subparsers.add_parser(
            'bash_completion',
            add_help=False,
            formatter_class=HelpFormatter
        )
        self.subcommands['bash_completion'] = subparser
        subparser.set_defaults(func=self.do_bash_completion) 
Example 31
Project: eclcli   Author: nttcom   File: shell.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, prog, indent_increment=2, max_help_position=32,
                 width=None):
        super(HelpFormatter, self).__init__(prog, indent_increment,
                                            max_help_position, width) 
Example 32
Project: eclcli   Author: nttcom   File: shell.py    (license) View Source Project 5 votes vote down vote up
def start_section(self, heading):
        # Title-case the headings
        heading = '%s%s' % (heading[0].upper(), heading[1:])
        super(HelpFormatter, self).start_section(heading) 
Example 33
Project: devpi   Author: devpi   File: main.py    (license) View Source Project 5 votes vote down vote up
def error(self, error):
        """raise errors instead of printing and raising SystemExit"""
        raise self.ArgumentError(error)

    #def __init__(self, *args, **kwargs):
    #    kwargs["formatter_class"] = MyHelpFormatter
    #    argparse.ArgumentParser.__init__(self, *args, **kwargs)

#class MyHelpFormatter(argparse.HelpFormatter):
#    pass 
Example 34
Project: python-cratonclient   Author: openstack   File: test_main.py    (license) View Source Project 5 votes vote down vote up
def test_get_base_parser(self):
        """Verify how we construct our basic Argument Parser."""
        with mock.patch('argparse.ArgumentParser') as ArgumentParser:
            parser = self.shell.get_base_parser()

        self.assertEqual(ArgumentParser.return_value, parser)
        ArgumentParser.assert_called_once_with(
            prog='craton',
            description=('Main shell for parsing arguments directed toward '
                         'Craton.'),
            epilog='See "craton help COMMAND" for help on a specific command.',
            add_help=False,
            formatter_class=argparse.HelpFormatter,
        ) 
Example 35
Project: builds   Author: open-power-host-os   File: config.py    (license) View Source Project 5 votes vote down vote up
def _split_lines(self, text, width):
        if text.startswith(RAW_TEXT_ID):
            return text[len(RAW_TEXT_ID):].splitlines()
        # this is the RawTextHelpFormatter._split_lines
        return argparse.HelpFormatter._split_lines(self, text, width) 
Example 36
Project: signet-python   Author: signet-org   File: signet.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        argparse.HelpFormatter.__init__(self, *args, **kwargs)
        self._action_max_length = 18 
Example 37
Project: matam   Author: bonsai-team   File: compute_contigs_compatibility.py    (license) View Source Project 5 votes vote down vote up
def parse_arguments():
    """
    Parse the command line, and check if arguments are correct
    """
    # Initiate argument parser
    parser = DefaultHelpParser(description='Program description',
                               # to precisely format help display
                               formatter_class=lambda prog: argparse.HelpFormatter(prog, width=120, max_help_position=80))

    # Main parameters
    group_main = parser.add_argument_group('Main parameters')
    # -i / --input_sam
    group_main.add_argument('-i', '--input_sam',
                            action = 'store',
                            metavar = 'INSAM',
                            type = argparse.FileType('r'),
                            default = '-',
                            help = 'Input sam file, sorted by subject and position')
    # -o / --output_sam
    group_main.add_argument('-o', '--output_sam',
                            action = 'store',
                            metavar = 'OUTSAM',
                            type = argparse.FileType('w'),
                            default = '-',
                            help = 'Output sam file')
    # -v / --verbose
    group_main.add_argument('-v', '--verbose',
                            action = 'store_true',
                            help = 'Increase verbosity')

    # Debug
    group_debug = parser.add_argument_group('Debug parameters')
    # --debug
    group_debug.add_argument('--debug',
                             action = 'store_true',
                             help = 'Output debug infos')

    args = parser.parse_args()

    #
    return args 
Example 38
Project: skaff   Author: jhxie   File: clitools.py    (license) View Source Project 5 votes vote down vote up
def _split_lines(self, text, width):
        if text.startswith('D|'):
            self._add_defaults = True
            text = text[2:]
        elif text.startswith('*|'):
            text = text[2:]
        if text.startswith('R|'):
            return text[2:].splitlines()
        return argparse.HelpFormatter._split_lines(self, text, width) 
Example 39
Project: skaff   Author: jhxie   File: clitools.py    (license) View Source Project 5 votes vote down vote up
def _get_help_string(self, action):
        if self._add_defaults is None:
            return argparse.HelpFormatter._get_help_string(self, action)
        help = action.help
        if '%(default)' not in action.help:
            if action.default is not argparse.SUPPRESS:
                defaulting_nargs = [argparse.OPTIONAL, argparse.ZERO_OR_MORE]
                if action.option_strings or action.nargs in defaulting_nargs:
                    help += ' (default: %(default)s)'
        return help 
Example 40
Project: zaqar-demo   Author: openstacker   File: zaqar_demo.py    (license) View Source Project 5 votes vote down vote up
def start_section(self, heading):
        # Title-case the headings
        heading = '%s%s' % (heading[0].upper(), heading[1:])
        super(HelpFormatter, self).start_section(heading) 
Example 41
Project: pefile.pypy   Author: cloudtracer   File: test_argparse.py    (license) View Source Project 5 votes vote down vote up
def test_parser(self):
        parser = argparse.ArgumentParser(prog='PROG')
        string = (
            "ArgumentParser(prog='PROG', usage=None, description=None, "
            "version=None, formatter_class=%r, conflict_handler='error', "
            "add_help=True)" % argparse.HelpFormatter)
        self.assertStringEqual(parser, string)

# ===============
# Namespace tests
# =============== 
Example 42
Project: geoDL   Author: jduc   File: geoDL.py    (license) View Source Project 5 votes vote down vote up
def _split_lines(self, text, width):
        if text.startswith('R|'):
            return text[2:].splitlines()
        # this is the RawTextHelpFormatter._split_lines
        return argparse.HelpFormatter._split_lines(self, text, width) 
Example 43
Project: ouroboros   Author: pybee   File: test_argparse.py    (license) View Source Project 5 votes vote down vote up
def test_parser(self):
        parser = argparse.ArgumentParser(prog='PROG')
        string = (
            "ArgumentParser(prog='PROG', usage=None, description=None, "
            "formatter_class=%r, conflict_handler='error', "
            "add_help=True)" % argparse.HelpFormatter)
        self.assertStringEqual(parser, string)

# ===============
# Namespace tests
# =============== 
Example 44
Project: ndk-python   Author: gittor   File: test_argparse.py    (license) View Source Project 5 votes vote down vote up
def test_parser(self):
        parser = argparse.ArgumentParser(prog='PROG')
        string = (
            "ArgumentParser(prog='PROG', usage=None, description=None, "
            "version=None, formatter_class=%r, conflict_handler='error', "
            "add_help=True)" % argparse.HelpFormatter)
        self.assertStringEqual(parser, string)

# ===============
# Namespace tests
# =============== 
Example 45
Project: Protector   Author: trivago   File: smart_formatter.py    (license) View Source Project 5 votes vote down vote up
def _split_lines(self, text, width):
        # this is the RawTextHelpFormatter._split_lines
        if text.startswith('R|'):
            return text[2:].splitlines()
        return argparse.HelpFormatter._split_lines(self, text, width) 
Example 46
Project: teras   Author: chantera   File: argparse.py    (license) View Source Project 5 votes vote down vote up
def __init__(self,
                 prog=None,
                 usage=None,
                 description=None,
                 epilog=None,
                 parents=[],
                 formatter_class=argparse.HelpFormatter,
                 prefix_chars='-',
                 fromfile_prefix_chars=None,
                 argument_default=None,
                 conflict_handler='error',
                 add_help=True,
                 allow_abbrev=True):
        super(ArgumentParser, self).__init__(
            prog,
            usage,
            description,
            epilog,
            parents,
            formatter_class,
            prefix_chars,
            fromfile_prefix_chars,
            argument_default,
            conflict_handler,
            add_help,
            allow_abbrev)
        self.register('action', 'store_dict', _StoreDictAction)
        self.register('action', 'store_dict_const', _StoreDictConstAction) 
Example 47
Project: teras   Author: chantera   File: argparse.py    (license) View Source Project 5 votes vote down vote up
def _init_parser(self, **kwargs):
        _def = self._def
        num_groups = len(_def.groups)
        if num_groups == 0:
            raise RuntimeError("At least one command should be defined.")

        formatter_class = argparse.HelpFormatter
        if 'formatter_class' in kwargs:
            formatter_class = kwargs['formatter_class']
        parser = ArgumentParser(**kwargs)

        for name, value in _def.common_cmd_args.items():
            parser.add_argument(*value.args, **value.kwargs)

        if num_groups == 1:
            """register arguments as common"""
            group = _def.groups[0]
            for name, value in _def.grouped_cmd_args[group].items():
                parser.add_argument(*value.args, **value.kwargs)
        else:
            """register arguments as groups"""
            subparsers = parser.add_subparsers(
                title='commands', help='available commands', dest='command')
            subparsers.required = True
            for group in _def.groups:
                subparser = subparsers.add_parser(
                    group, **_def.group_descriptions[group],
                    formatter_class=formatter_class)
                for name, value in _def.grouped_cmd_args[group].items():
                    subparser.add_argument(*value.args, **value.kwargs)

        return parser 
Example 48
Project: combirepo   Author: Samsung   File: commandline_parser.py    (license) View Source Project 5 votes vote down vote up
def _split_lines(self, text, width):
        text = re.sub(man_format_remove, '', text)
        # this is the RawTextHelpFormatter._split_lines
        if text.startswith('R|'):
            return text[2:].splitlines()
        return argparse.HelpFormatter._split_lines(self, text, width) 
Example 49
Project: combirepo   Author: Samsung   File: commandline_parser.py    (license) View Source Project 5 votes vote down vote up
def parser_options(formatter_class=argparse.HelpFormatter):
    """
    Retrieve a customized parser to generate man page
    """
    return CommandlineParser().get_formatted_parser(formatter_class) 
Example 50
Project: combirepo   Author: Samsung   File: build_manpage.py    (license) View Source Project 5 votes vote down vote up
def _split_lines(self, text, width):
        """
        Allows forcing newlines in lines starting with R|
        """
        if text.startswith('R|'):
            return text[2:].splitlines()
        return argparse.HelpFormatter._split_lines(self, text, width)