當前位置: 首頁>>代碼示例>>Python>>正文


Python argparse._HelpAction方法代碼示例

本文整理匯總了Python中argparse._HelpAction方法的典型用法代碼示例。如果您正苦於以下問題:Python argparse._HelpAction方法的具體用法?Python argparse._HelpAction怎麽用?Python argparse._HelpAction使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在argparse的用法示例。


在下文中一共展示了argparse._HelpAction方法的12個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_get_parser_actions

# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import _HelpAction [as 別名]
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 
開發者ID:EvanKepner,項目名稱:mutatest,代碼行數:20,代碼來源:test_cli.py

示例2: base_arguments

# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import _HelpAction [as 別名]
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') 
開發者ID:allegroai,項目名稱:trains-agent,代碼行數:18,代碼來源:base.py

示例3: __init__

# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import _HelpAction [as 別名]
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 
開發者ID:eliasgranderubio,項目名稱:dagda,代碼行數:27,代碼來源:dagda_cli_parser.py

示例4: test_help_action_not_in_optionals

# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import _HelpAction [as 別名]
def test_help_action_not_in_optionals(self):
    _isinstance = lambda x: isinstance(x, _HelpAction)
    self.assertFalse(any(map(_isinstance, self.sorted_actions._optionals))) 
開發者ID:lrq3000,項目名稱:pyFileFixity,代碼行數:5,代碼來源:action_sorter_unittest.py

示例5: add_dynamic_attr

# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import _HelpAction [as 別名]
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] 
開發者ID:ansible,項目名稱:ansibullbot,代碼行數:17,代碼來源:triagers.py

示例6: print_help

# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import _HelpAction [as 別名]
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) 
開發者ID:chihongze,項目名稱:girlfriend,代碼行數:11,代碼來源:cmdargs.py

示例7: arg_parser

# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import _HelpAction [as 別名]
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 
開發者ID:fgaim,項目名稱:gpuview,代碼行數:43,代碼來源:utils.py

示例8: add_parser_help

# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import _HelpAction [as 別名]
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.",
    ) 
開發者ID:nccgroup,項目名稱:Splunking-Crime,代碼行數:14,代碼來源:common.py

示例9: _format_usage

# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import _HelpAction [as 別名]
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) 
開發者ID:s3ql,項目名稱:s3ql,代碼行數:32,代碼來源:parse_args.py

示例10: _format_actions_usage

# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import _HelpAction [as 別名]
def _format_actions_usage(self, actions, groups):
		return (
			super()._format_actions_usage(
				tuple(filterfalse(
					methodcaller(isinstance, (argparse._HelpAction, VersionAction)),
					actions)),
				groups)) 
開發者ID:davidfoerster,項目名稱:aptsources-cleanup,代碼行數:9,代碼來源:__main__.py

示例11: get_parser_actions

# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import _HelpAction [as 別名]
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) 
開發者ID:EvanKepner,項目名稱:mutatest,代碼行數:59,代碼來源:cli.py

示例12: parser

# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import _HelpAction [as 別名]
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_ 
開發者ID:aropan,項目名稱:clist,代碼行數:52,代碼來源:bot.py


注:本文中的argparse._HelpAction方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。