本文整理汇总了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
示例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')
示例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
示例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)))
示例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]
示例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)
示例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
示例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.",
)
示例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)
示例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))
示例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)
示例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_