我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用optparse.OptionValueError()。
def _applyConfigurationToValues(self, parser, config, values): for name, value, filename in config: if name in option_blacklist: continue try: self._processConfigValue(name, value, values, parser) except NoSuchOptionError, exc: self._file_error( "Error reading config file %r: " "no such option %r" % (filename, exc.name), name=name, filename=filename) except optparse.OptionValueError, exc: msg = str(exc).replace('--' + name, repr(name), 1) self._file_error("Error reading config file %r: " "%s" % (filename, msg), name=name, filename=filename)
def process(self, opt, value, values, parser): """ Call the validator function on applicable settings and evaluate the 'overrides' option. Extends `optparse.Option.process`. """ result = optparse.Option.process(self, opt, value, values, parser) setting = self.dest if setting: if self.validator: value = getattr(values, setting) try: new_value = self.validator(setting, value, parser) except Exception, error: raise (optparse.OptionValueError( 'Error in option "%s":\n %s' % (opt, ErrorString(error))), None, sys.exc_info()[2]) setattr(values, setting, new_value) if self.overrides: setattr(values, self.overrides, None) return result
def check_sort_key(option, opt, value): result = [] for value in field_split(value): value = value.strip().split(":") field, sort_opts = value[0], value[1:] sort_type = desc = None for sort_opt in sort_opts: if sort_opt == "desc": desc = True elif SortType.is_valid(sort_opt): sort_type = sort_opt else: raise OptionValueError("Unknown sort option: {0!r}".format(sort_opt)) result.append(DataFieldOrder(field, sort_type=sort_type, desc=desc)) return result
def sign_options(): def callback(option, opt_str, value, parser, sign_str): if parser.values.sign_str not in [None, sign_str]: raise optparse.OptionValueError( 'Cannot give more than one of --ack, --sign, --review') parser.values.sign_str = sign_str return [ opt('--sign', action = 'callback', dest = 'sign_str', args = [], callback = callback, callback_args = ('Signed-off-by',), short = 'Add "Signed-off-by:" line', long = """ Add a "Signed-off-by:" to the end of the patch."""), opt('--ack', action = 'callback', dest = 'sign_str', args = [], callback = callback, callback_args = ('Acked-by',), short = 'Add "Acked-by:" line', long = """ Add an "Acked-by:" line to the end of the patch."""), opt('--review', action = 'callback', dest = 'sign_str', args = [], callback = callback, callback_args = ('Reviewed-by',), short = 'Add "Reviewed-by:" line', long = """ Add a "Reviewed-by:" line to the end of the patch.""")]
def _person_opts(person, short): """Sets options.<person> to a function that modifies a Person according to the commandline options.""" def short_callback(option, opt_str, value, parser, field): f = getattr(parser.values, person) if field == "date": value = git.Date(value) setattr(parser.values, person, lambda p: getattr(f(p), 'set_' + field)(value)) def full_callback(option, opt_str, value, parser): ne = utils.parse_name_email(value) if not ne: raise optparse.OptionValueError( 'Bad %s specification: %r' % (opt_str, value)) name, email = ne short_callback(option, opt_str, name, parser, 'name') short_callback(option, opt_str, email, parser, 'email') return ( [opt('--%s' % person, metavar = '"NAME <EMAIL>"', type = 'string', action = 'callback', callback = full_callback, dest = person, default = lambda p: p, short = 'Set the %s details' % person)] + [opt('--%s%s' % (short, f), metavar = f.upper(), type = 'string', action = 'callback', callback = short_callback, dest = person, callback_args = (f,), short = 'Set the %s %s' % (person, f)) for f in ['name', 'email', 'date']])
def output_option_parser(option, opt, value, parser): """Parse the string of outputs and validate it. Args: option (optparse.Option): the Option instnace. opt (str): option calling format. value (str): user input for the option. parser (optparse.OptionParser): the parser of the option. Raises: optparse.OptionValueError. unsupported handler requested. """ output_options = get_result_handler_options() handlers = value.split(',') for handler in handlers: if handler not in output_options: raise optparse.OptionValueError( 'Unsupported handler %r, supported handlers: %s' % (handler, ", ".join(output_options))) setattr(parser.values, option.dest, handlers)
def process(self, opt, value, values, parser): """ Call the validator function on applicable settings and evaluate the 'overrides' option. Extends `optparse.Option.process`. """ result = optparse.Option.process(self, opt, value, values, parser) setting = self.dest if setting: if self.validator: value = getattr(values, setting) try: new_value = self.validator(setting, value, parser) except Exception as error: raise optparse.OptionValueError( 'Error in option "%s":\n %s' % (opt, ErrorString(error))) setattr(values, setting, new_value) if self.overrides: setattr(values, self.overrides, None) return result
def check_default(self, option, key, val): try: return option.check_value(key, val) except optparse.OptionValueError as exc: print("An error occurred during configuration: %s" % exc) sys.exit(3)
def _check_color(option, opt_str, value, parser): """OptionParser callback to check if the given color is valid.""" if not helpers.is_color(value): raise OptionValueError("option %s: invalid color: '%s'" % (opt_str, value)) # noqa setattr(parser.values, option.dest, value)
def _check_colorshift(option, opt_str, values, parser): """OptionParser callback to check if the given colors are valid. Also transfroms a little bit the args to make it works: [color1, color2, speed] -> [[color1, color2], speed] """ colors = values[:-1] speed = values[-1] for color in colors: if not helpers.is_color(color): raise OptionValueError("option %s: invalid color: '%s'" % (opt_str, color)) # noqa if not speed.isdigit(): raise OptionValueError("option %s: invalid speed: '%s'" % (opt_str, speed)) # noqa setattr(parser.values, option.dest, [colors, int(speed)])
def exclude_callback(option, opt, value, parser): if EXCLUDE_RE.match(value) is None: raise optparse.OptionValueError("%s argument has invalid value" % (opt,)) parser.values.exclude = TAG_RE.findall(value)
def check_default(self, option, key, val): try: return option.check_value(key, val) except optparse.OptionValueError: e = sys.exc_info()[1] print("An error occurred during configuration: %s" % e) sys.exit(3)
def optparse_callback(option, opt_str, value, parser, callback, parsed): try: parsed[option.dest] = callback(value) except ParamError as error: message = "option " + opt_str + ": " + error.args[0] raise optparse.OptionValueError(message)
def __init__(self): def check_charset_option(option, opt_str, value, parser): """Value must be a valid charset""" try: dummy = codecs.lookup(value) except LookupError, e: raise optparse.OptionValueError( "Charset '%s' in unknown or not supported by your sytem." % value) setattr(parser.values, option.dest, value) return parser = optparse.OptionParser( usage=USAGE % (VERSION, self.__class__.__doc__), version=VERSION) parser.add_option( '-c', '--charset', dest='charset', default=DEFAULT_CHARSET, type='string', action='callback', callback=check_charset_option, help="Converts output to this charset (default %s)" % DEFAULT_CHARSET ) parser.add_option( '-v', '--verbosity', dest='verbosity', default=0, action='count', help="Adds verbosity for each '-v'") self.options, self.args = parser.parse_args() if (len(self.args) < 2 or self.args[0] not in self.commands.keys()): parser.error("Invalid arguments") self.filenames = self.args[1:] return
def update_defaults(self, defaults): """ Updates the given defaults with values from the config files and the environ. Does a little special handling for certain types of options (lists). """ # Then go and look for the other sources of configuration: config = {} # 1. config files config.update(dict(self.get_config_section('virtualenv'))) # 2. environmental variables config.update(dict(self.get_environ_vars())) # Then set the options with those values for key, val in config.items(): key = key.replace('_', '-') if not key.startswith('--'): key = '--%s' % key # only prefer long opts option = self.get_option(key) if option is not None: # ignore empty values if not val: continue # handle multiline configs if option.action == 'append': val = val.split() else: option.nargs = 1 if option.action == 'store_false': val = not strtobool(val) elif option.action in ('store_true', 'count'): val = strtobool(val) try: val = option.convert_value(key, val) except optparse.OptionValueError: e = sys.exc_info()[1] print("An error occured during configuration: %s" % e) sys.exit(3) defaults[option.dest] = val return defaults