我们从Python开源项目中,提取了以下6个代码示例,用于说明如何使用argparse._StoreAction()。
def addExtraArguments(self, parser): class store_as_array(argparse._StoreAction): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, self.dest, np.array(values)) parser.add_argument("-qoi_dim", type=int, default=1, action="store") parser.add_argument("-qoi_problem", type=int, default=0, action="store") parser.add_argument("-qoi_a0", type=float, default=0., action="store") parser.add_argument("-qoi_f0", type=float, default=1., action="store") parser.add_argument("-qoi_df_nu", type=float, default=1., action="store") parser.add_argument("-qoi_df_L", type=float, default=1., action="store") parser.add_argument("-qoi_df_sig", type=float, default=1., action="store") parser.add_argument("-qoi_scale", type=float, default=1., action="store") parser.add_argument("-qoi_sigma", type=float, default=1., action="store") parser.add_argument("-qoi_x0", type=float, nargs='+', default=[0.4,0.2,0.6], action=store_as_array)
def _make_stdin_action(func, err_msg): """ Return a StdinAction object that checks for stdin. func should be the function associated with the parser's -r flag that is not valid to use with stdin. """ class StdinAction(argparse._StoreAction): def __call__(self, parser, namespace, values, option_string=None): if values == '-': if namespace.func == func: raise argparse.ArgumentError(self, err_msg) else: ntf = tempfile.NamedTemporaryFile(delete=False, mode='w') try: ntf.write(sys.stdin.read()) finally: ntf.close() super(StdinAction, self).__call__(parser, namespace, TempPath(ntf.name), option_string=option_string) else: super(StdinAction, self).__call__(parser, namespace, values, option_string=option_string) return StdinAction
def addExtraArguments(self, parser): class store_as_array(argparse._StoreAction): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, self.dest, np.array(values)) parser.add_argument("-qoi_dim", type=int, default=10, action="store") parser.add_argument("-qoi_func", type=int, default=1, action="store")
def __init__(self, *args, **kwargs): super(argparse._StoreAction, self).__init__(*args, **kwargs)
def convert_item_to_command_line_arg(self, action, key, value): """Converts a config file or env var key + value to a list of commandline args to append to the commandline. Args: action: The argparse Action object for this setting, or None if this config file setting doesn't correspond to any defined configargparse arg. key: string (config file key or env var name) value: parsed value of type string or list """ args = [] if action is None: command_line_key = \ self.get_command_line_key_for_unknown_config_file_setting(key) else: command_line_key = action.option_strings[-1] # handle boolean value if action is not None and isinstance(action, ACTION_TYPES_THAT_DONT_NEED_A_VALUE): if value.lower() in ("true", "yes"): args.append( command_line_key ) elif value.lower() in ("false", "no"): # don't append when set to "false" / "no" pass else: self.error("Unexpected value for %s: '%s'. Expecting 'true', " "'false', 'yes', or 'no'" % (key, value)) elif isinstance(value, list): if action is None or isinstance(action, argparse._AppendAction): for list_elem in value: args.append( command_line_key ) args.append( str(list_elem) ) elif (isinstance(action, argparse._StoreAction) and action.nargs in ('+', '*')) or ( isinstance(action.nargs, int) and action.nargs > 1): args.append( command_line_key ) for list_elem in value: args.append( str(list_elem) ) else: self.error(("%s can't be set to a list '%s' unless its action type is changed " "to 'append' or nargs is set to '*', '+', or > 1") % (key, value)) elif isinstance(value, str): args.append( command_line_key ) args.append( value ) else: raise ValueError("Unexpected value type %s for value: %s" % ( type(value), value)) return args
def add_argument(self, *args, **kwargs): """ This method supports the same args as ArgumentParser.add_argument(..) as well as the additional args below. Additional Args: env_var: If set, the value of this environment variable will override any config file or default values for this arg (but can itself be overriden on the commandline). Also, if auto_env_var_prefix is set in the constructor, this env var name will be used instead of the automatic name. is_config_file_arg: If True, this arg is treated as a config file path This provides an alternative way to specify config files in place of the ArgumentParser(fromfile_prefix_chars=..) mechanism. Default: False is_write_out_config_file_arg: If True, this arg will be treated as a config file path, and, when it is specified, will cause configargparse to write all current commandline args to this file as config options and then exit. Default: False """ env_var = kwargs.pop("env_var", None) is_config_file_arg = kwargs.pop( "is_config_file_arg", None) or kwargs.pop( "is_config_file", None) # for backward compat. is_write_out_config_file_arg = kwargs.pop( "is_write_out_config_file_arg", None) action = self.original_add_argument_method(*args, **kwargs) action.is_positional_arg = not action.option_strings action.env_var = env_var action.is_config_file_arg = is_config_file_arg action.is_write_out_config_file_arg = is_write_out_config_file_arg if action.is_positional_arg and env_var: raise ValueError("env_var can't be set for a positional arg.") if action.is_config_file_arg and not isinstance(action, argparse._StoreAction): raise ValueError("arg with is_config_file_arg=True must have " "action='store'") if action.is_write_out_config_file_arg: error_prefix = "arg with is_write_out_config_file_arg=True " if not isinstance(action, argparse._StoreAction): raise ValueError(error_prefix + "must have action='store'") if is_config_file_arg: raise ValueError(error_prefix + "can't also have " "is_config_file_arg=True") return action