我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用argparse.Action()。
def do_table_set_default(self, line): "Set default action for a match table: table_set_default <table name> <action name> <action parameters>" args = line.split() self.at_least_n_args(args, 2) table_name, action_name = args[0], args[1] table = self.get_res("table", table_name, TABLES) if action_name not in table.actions: raise UIn_Error( "Table %s has no action %s" % (table_name, action_name) ) action = ACTIONS[action_name] if len(args[2:]) != action.num_params(): raise UIn_Error( "Action %s needs %d parameters" % (action_name, action.num_params()) ) runtime_data = parse_runtime_data(action, args[2:]) self.print_set_default(table_name, action_name, runtime_data) self.client.bm_mt_set_default_action(0, table_name, action_name, runtime_data)
def do_act_prof_create_member(self, line): "Add a member to an action profile: act_prof_create_member <action profile name> <action_name> [action parameters]" args = line.split() self.at_least_n_args(args, 2) act_prof_name, action_name = args[0], args[1] act_prof = self.get_res("action profile", act_prof_name, ACTION_PROFS) if action_name not in act_prof.actions: raise UIn_Error("Action profile '{}' has no action '{}'".format( act_prof_name, action_name)) action = ACTIONS[action_name] action_params = args[2:] runtime_data = self.parse_runtime_data(action, action_params) mbr_handle = self.client.bm_mt_act_prof_add_member( 0, act_prof_name, action_name, runtime_data) print "Member has been created with handle", mbr_handle
def pytest_addoption(parser): group = parser.getgroup("sqlalchemy") def make_option(name, **kw): callback_ = kw.pop("callback", None) if callback_: class CallableAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): callback_(option_string, values, parser) kw["action"] = CallableAction group.addoption(name, **kw) plugin_base.setup_options(make_option) plugin_base.read_config()
def __call__( self, parser, # type: argparse.ArgumentParser namespace, # type: argparse.Namespace values, # type: Union[ARGPARSE_TEXT, Sequence[Any], None] option_string=None # type: Optional[ARGPARSE_TEXT] ): # type: (...) -> None """Checks to make sure that the destination is empty before writing. :raises parser.error: if destination is already set """ if getattr(namespace, self.dest) is not None: # type: ignore # typeshed doesn't know about Action.dest yet? parser.error('{} argument may not be specified more than once'.format(option_string)) return setattr(namespace, self.dest, values) # type: ignore # typeshed doesn't know about Action.dest yet?
def required_length(minimum: int, maximum: int, optional: bool = False): """Returns a custom required length class""" class RequiredLength(argparse.Action): def __call__(self, parser, args, values, option_string=None): is_allowed = ( (minimum <= len(values) <= maximum) or (optional and not len(values)) ) if is_allowed: setattr(args, self.dest, values) return raise argparse.ArgumentTypeError( 'Argument "{}" must have {}-{} arguments'.format( self.dest, minimum, maximum ) ) return RequiredLength
def _make_print_cli_list_spec_action(cli_list_spec_file): with open(cli_list_spec_file) as f: str_cli_list_spec = f.read() class _PrintCLIListSpecAction(argparse.Action): def __init__(self, option_strings, dest=argparse.SUPPRESS, default=argparse.SUPPRESS, help=None): super(_PrintCLIListSpecAction, self).__init__( option_strings=option_strings, dest=dest, default=default, nargs=0, help=help) def __call__(self, parser, namespace, values, option_string=None): print str_cli_list_spec parser.exit() return _PrintCLIListSpecAction
def get_argparse_extension_checker(choices, dir_allowed=False): """Get an :class:`argparge.Action` class that can check for correct extensions. Returns: argparse.Action: a class (not an instance) of an argparse action. """ class Act(argparse.Action): def __call__(self, parser, namespace, fname, option_string=None): is_valid = any(map(lambda choice: fname[-len(choice):] == choice, choices)) if not is_valid and dir_allowed and os.path.isdir(fname): is_valid = True if is_valid: setattr(namespace, self.dest, fname) else: option_string = '({})'.format(option_string) if option_string else '' parser.error("File doesn't end with one of {}{}".format(choices, option_string)) return Act
def test(self): def get_my_type(string): return 'my_type{%s}' % string parser = argparse.ArgumentParser() parser.register('type', 'my_type', get_my_type) parser.add_argument('-x', type='my_type') parser.add_argument('y', type='my_type') self.assertEqual(parser.parse_args('1'.split()), NS(x=None, y='my_type{1}')) self.assertEqual(parser.parse_args('-x 1 42'.split()), NS(x='my_type{1}', y='my_type{42}')) # ============ # Action tests # ============
def add_deprecated_argument(add_argument, argument_name, nargs): """Adds a deprecated argument with the name argument_name. Deprecated arguments are not shown in the help. If they are used on the command line, a warning is shown stating that the argument is deprecated and no other action is taken. :param callable add_argument: Function that adds arguments to an argument parser/group. :param str argument_name: Name of deprecated argument. :param nargs: Value for nargs when adding the argument to argparse. """ class ShowWarning(argparse.Action): """Action to log a warning when an argument is used.""" def __call__(self, unused1, unused2, unused3, option_string=None): sys.stderr.write( "Use of {0} is deprecated.\n".format(option_string)) configargparse.ACTION_TYPES_THAT_DONT_NEED_A_VALUE.add(ShowWarning) add_argument(argument_name, action=ShowWarning, help=argparse.SUPPRESS, nargs=nargs)
def parse_args(): class FullPaths(argparse.Action): """Expand user- and relative-paths""" def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, self.dest, os.path.abspath(os.path.expanduser(values))) usage = " " parser = argparse.ArgumentParser(description="STAR-SEQR Parameters:", epilog=usage) parser.add_argument('-j', '--json', type=str, required=False, action=FullPaths, default='/data/input/AppSession.json', help='json input file from basespace app') parser.add_argument('-s', '--sample_path', type=str, required=False, action=FullPaths, default='/data/input/samples/', help='default path for samples') parser.add_argument('-r', '--results_path', type=str, required=False, action=FullPaths, default='/data/output/appresults/', help='default path for results') parser.add_argument('-t', '--scratch_path', type=str, required=False, action=FullPaths, default='/data/scratch/', help='default path for scratch') args = parser.parse_args() return args
def add_subparsers(parser): subparsers = parser.add_subparsers() # see http://stackoverflow.com/questions/18282403/ # for the following two lines (py3 compat) subparsers.required = False subparsers.dest = "command" for func, args, kwargs in subcommand.discover(globals()): if len(args) > 1: name = args[1] else: name = func.__name__ doc, description = parse_docstring(func.__doc__) subparser = subparsers.add_parser(name, description=description, help=doc) subparser.Action = argparse.Action add_generic_options(subparser) func(subparser) mainloc = args[0] subparser.set_defaults(mainloc=mainloc)
def __call__(self, parser, namespace, values, option_string=None): """Re-implementation of the base class method. See `argparse.Action` documentation for parameter description. """ dest = getattr(namespace, self.dest) if dest is None: dest = [] setattr(namespace, self.dest, dest) for componentLevel in values: component, sep, levelStr = componentLevel.partition("=") if not levelStr: levelStr, component = component, None logLevelUpr = levelStr.upper() if logLevelUpr not in self.permittedLevels: parser.error("loglevel=%s not one of %s" % (levelStr, tuple(self.permittedLevels))) dest.append((component, logLevelUpr))