Python argparse._HelpAction() Examples

The following are 12 code examples of argparse._HelpAction(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module argparse , or try the search function .
Example #1
Source File: test_cli.py    From mutatest with MIT License 6 votes vote down vote up
def test_get_parser_actions(mock_parser):
    """Parser action types based on basic inputs."""
    expected_actions = {
        "-h": "--help",
        "-e": "--exclude",
        "-b": "--blacklist",
        "--debug": "--debug",
    }
    expected_types = {
        argparse._HelpAction: ["help"],
        argparse._AppendAction: ["exclude"],
        argparse._StoreAction: ["blacklist"],
        argparse._StoreTrueAction: ["debug"],
    }

    parser_actions = cli.get_parser_actions(mock_parser)
    assert parser_actions.actions == expected_actions
    assert parser_actions.action_types == expected_types 
Example #2
Source File: base.py    From trains-agent with Apache License 2.0 6 votes vote down vote up
def base_arguments(top_parser):
    top_parser.register('action', 'parsers', AliasedSubParsersAction)
    top_parser.add_argument('-h', action=_HelpAction, help='Displays summary of all commands')
    top_parser.add_argument(
        '--help',
        action=_DetailedHelpAction,
        help='Detailed help of command line interface')
    top_parser.add_argument(
        '--version',
        action='version',
        version='TRAINS-AGENT version %s' % Session.version,
        help='TRAINS-AGENT version number')
    top_parser.add_argument(
        '--config-file',
        help='Use a different configuration file (default: "{}")'.format(definitions.CONFIG_FILE))
    top_parser.add_argument('--debug', '-d', action='store_true', help='print debug information') 
Example #3
Source File: dagda_cli_parser.py    From dagda with Apache License 2.0 6 votes vote down vote up
def __init__(self):
        super(DagdaCLIParser, self).__init__()
        self.parser = DagdaGlobalParser(prog='dagda.py', usage=dagda_global_parser_text, add_help=False)
        self.parser.add_argument('command', choices=['vuln', 'check', 'history', 'start', 'monitor', 'docker', 'agent'])
        self.parser.add_argument('-h', '--help', action=_HelpAction)
        self.parser.add_argument('-v', '--version', action='version', version='%(prog)s 0.8.0')
        self.args, self.unknown = self.parser.parse_known_args()
        if self.get_command() == 'vuln':
            self.extra_args = VulnCLIParser()
        elif self.get_command() == 'check':
            self.extra_args = CheckCLIParser()
        elif self.get_command() == 'history':
            self.extra_args = HistoryCLIParser()
        elif self.get_command() == 'start':
            self.extra_args = StartCLIParser()
        elif self.get_command() == 'monitor':
            self.extra_args = MonitorCLIParser()
        elif self.get_command() == 'docker':
            self.extra_args = DockerCLIParser()
        elif self.get_command() == 'agent':
            self.extra_args = AgentCLIParser()

    # -- Getters

    # Gets command 
Example #4
Source File: action_sorter_unittest.py    From pyFileFixity with MIT License 5 votes vote down vote up
def test_help_action_not_in_optionals(self):
    _isinstance = lambda x: isinstance(x, _HelpAction)
    self.assertFalse(any(map(_isinstance, self.sorted_actions._optionals))) 
Example #5
Source File: triagers.py    From ansibullbot with GNU General Public License v3.0 5 votes vote down vote up
def add_dynamic_attr(cls, klass):
    parser = klass.create_parser()
    import argparse
    for action in parser._actions:
        if isinstance(action, argparse._HelpAction):
            continue

        if isinstance(action, (argparse._StoreTrueAction, argparse._StoreTrueAction)):
            cls.locals[action.dest] = [bool]
        elif isinstance(action, argparse._CountAction):
            cls.locals[action.dest] = [int]
        elif isinstance(action, (argparse._AppendAction, argparse._AppendConstAction)):
            cls.locals[action.dest] = [list]
        else:
            cls.locals[action.dest] = [action.type] 
Example #6
Source File: cmdargs.py    From girlfriend with MIT License 5 votes vote down vote up
def print_help(parser, color=None):
    """输出帮助信息"""
    help_text = []
    for action in parser._actions:
        if isinstance(action, argparse._HelpAction):
            continue
        option_strings = ",".join(action.option_strings)
        help_text.append(u"{}  {}".format(option_strings, action.help))
    print "\n", colored("\n".join(help_text), color) 
Example #7
Source File: utils.py    From gpuview with MIT License 5 votes vote down vote up
def arg_parser():
    parser = argparse.ArgumentParser(add_help=False)
    subparsers = parser.add_subparsers(dest='action', help="Action")
    parser.add_argument('-v', '--version', action='version',
                        help='Print gpuview and gpustat versions',
                        version='gpuview %s || gpustat %s' %
                        (__version__, __gpustat__))
    parser.add_argument('-h', '--help', action=_HelpAction,
                        help='Print this help message')

    base_parser = argparse.ArgumentParser(add_help=False)
    base_parser.add_argument('--host', default='0.0.0.0',
                             help="IP address of host (default: 0.0.0.0)")
    base_parser.add_argument('--port', default=9988,
                             help="Port number of host (default: 9988)")
    base_parser.add_argument('--safe-zone', action='store_true',
                             help="Report all details including usernames")
    base_parser.add_argument('--exclude-self', action='store_true',
                             help="Don't report to others but self-dashboard")

    run_parser = subparsers.add_parser("run", parents=[base_parser],
                                       help="Run gpuview server")
    run_parser.add_argument('-d', '--debug', action='store_true',
                            help="Run server in debug mode")

    add_parser = subparsers.add_parser("add", help="Register a new GPU host")
    add_parser.add_argument('--url', required=True,
                            help="URL of GPU host (IP:Port, eg. X.X.X.X:9988")
    add_parser.add_argument('--name', default=None,
                            help="An optional readable name for the GPU host")

    rem_parser = subparsers.add_parser("remove", help="Remove a GPU host")
    rem_parser.add_argument('--url', required=True,
                            help="Url of the GPU node to remove")

    subparsers.add_parser("hosts", help="Print all GPU hosts")

    subparsers.add_parser("service", parents=[base_parser],
                          help="Install gpuview as a service")

    return parser 
Example #8
Source File: common.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def add_parser_help(p):
    """
    So we can use consistent capitalization and periods in the help. You must
    use the add_help=False argument to ArgumentParser or add_parser to use
    this. Add this first to be consistent with the default argparse output.

    """
    p.add_argument(
        '-h', '--help',
        action=argparse._HelpAction,
        help="Show this help message and exit.",
    ) 
Example #9
Source File: parse_args.py    From s3ql with GNU General Public License v3.0 5 votes vote down vote up
def _format_usage(self, usage, actions, groups, prefix):
        '''Special handling for usage lists

        If usage is a list object, its elements will be printed on
        separate lines. DEFAULT_USAGE will be replaced by the
        default usage string of the parser (but, if `usage`` is a list,
        excluding any --help arguments)).
        '''

        if isinstance(usage, list):
            # Omit help argument
            actions = [ x for x in actions if not isinstance(x, argparse._HelpAction) ]
            res = []
            for s in usage:
                if not res:
                    res.append('usage: ')
                else:
                    res.append('  or:  ')
                if s is DEFAULT_USAGE:
                    res.append(super()._format_usage(None, actions, groups, '')[:-1])
                else:
                    res.append(s % dict(prog=self._prog))
                    res.append('\n')

            return '%s\n\n' % ''.join(res)

        elif usage is DEFAULT_USAGE:
            return super()._format_usage(None, actions, groups, prefix)
        else:
            return super()._format_usage(usage, actions, groups, prefix) 
Example #10
Source File: __main__.py    From aptsources-cleanup with MIT License 5 votes vote down vote up
def _format_actions_usage(self, actions, groups):
		return (
			super()._format_actions_usage(
				tuple(filterfalse(
					methodcaller(isinstance, (argparse._HelpAction, VersionAction)),
					actions)),
				groups)) 
Example #11
Source File: cli.py    From mutatest with MIT License 4 votes vote down vote up
def get_parser_actions(parser: argparse.ArgumentParser) -> ParserActionMap:
    """Create a parser action map used when creating the command list mixed from the
    CLI and the ini config file.

    ParserActionMap has both actions and types e.g.,

    .. code-block:: python

        # action-types:

        {argparse._HelpAction: ['help'],
         mutatest.cli.ValidCategoryAction: ['blacklist', 'whitelist'],
         argparse._AppendAction: ['exclude'],
         argparse._StoreAction: ['mode', 'output', 'src', 'testcmds'],
         mutatest.cli.PositiveIntegerAction: ['nlocations', 'rseed', 'exception'],
         argparse._StoreTrueAction: ['debug', 'nocov']}

        # actions:

        {'-h': '--help',
         '-b': '--blacklist',
         '-e': '--exclude',
         '-m': '--mode',
         '-n': '--nlocations',
         '-o': '--output',
         '-r': '--rseed',
         '-s': '--src',
         '-t': '--testcmds',
         '-w': '--whitelist',
         '-x': '--exception',
         '--debug': '--debug',
         '--parallel': '--parallel',
         '--nocov': '--nocov'}

    Args:
        parser: the argparser

    Returns:
        ParserActionMap: includes actions and action_types
    """
    actions: Dict[str, str] = {}
    action_types: Dict[Any, List[str]] = {}

    for action in parser._actions:
        # build the actions
        # option_strings is either [-r, --rseed] or [--debug] for short-hand options
        actions[action.option_strings[0]] = action.option_strings[-1]

        # build the action_types
        # values align to the keywords that can be used in the INI config
        try:
            action_types[type(action)].append(action.option_strings[-1].strip("--"))

        except KeyError:
            action_types[type(action)] = [action.option_strings[-1].strip("--")]

    return ParserActionMap(actions=actions, action_types=action_types) 
Example #12
Source File: bot.py    From clist with Apache License 2.0 4 votes vote down vote up
def parser(self):
        if not hasattr(self, 'parser_'):
            self.parser_ = ThrowingArgumentParser(prog='ask me')
            command_p = self.parser_.add_subparsers(dest='command', help='Please to bot')

            start_p = command_p.add_parser('/start', description='Start communication and connect your account')
            start_p.add_argument('key', nargs='?', help='Connect account using secret key')

            command_p.add_parser('/time', description='Show current time in your timezone')

            resources_p = command_p.add_parser('/resources', description='View resources list')
            resources_p.add_argument('-g', '--grep', help='Grep host field')
            resources_p.add_argument('-d', '--delimiter', help='Events delimiter', default='\n')

            list_p = command_p.add_parser('/list', description='View contest list')
            list_p.add_argument('-g', '--grep', help='Grep by event and resource field')
            list_p.add_argument(
                '-f', '--format', help='Formating events',
                default='%(start)s - %(duration)s - %(remaining)s %(label)s\n[%(event)s](%(href)s) - `%(resource)s`',
            )
            list_p.add_argument('-t', '--time-format', help='Formating time', default='%d.%m %a %H:%M')
            list_p.add_argument('-d', '--delimiter', help='Events delimiter', default='\n\n')
            list_p.add_argument('-q', '--query', help='Query filter', action='append')
            list_p.add_argument('-s', '--sort-by', help='Sorting by field', choices=ContestResource.Meta.ordering)
            list_p.add_argument('-r', '--reverse-sort', help='Reversing sort by field',  action='store_true')
            list_p.add_argument('-o', '--offset', help='Offset start slice', type=int, default=0)
            list_p.add_argument('-l', '--limit', help='Limit slice', type=int, default=5)
            list_p.add_argument('-c', '--coming', help='Only coming events', action='store_true')
            list_p.add_argument('-lb', '--label', help='Labeling contest chars', nargs=3, default=['', '*', '[past]'])
            list_p.add_argument('-np', '--no-paging', help='Paging view', action='store_true')
            list_p.add_argument('-i', '--ignore-filters', help='Ignore filters', action='store_true')

            command_p.add_parser('/iamadmin', description='Set user as admin clistbot for group')
            command_p.add_parser('/iamnotadmin', description='Unset user as admin clistbot for group')

            command_p.add_parser('/unlink', description='Unlink account')

            for a in list_p._actions:
                if not isinstance(a, argparse._HelpAction):
                    if a.default is not None:
                        d = str(a.default).replace('\n', r'\n')
                        a.help = a.help + '. Default: "%s"' % d.replace('%', '%%')

            command_p.add_parser('/prev', description='Show previous page in paging')
            command_p.add_parser('/next', description='Show next page in paging')
            command_p.add_parser('/repeat', description='Repeat last command')

            command_p.add_parser('/help', description='Show what I can do')

        return self.parser_