def _group(option, opt_str, value, parser): try: value = int(value) except ValueError: try: value = grp.getgrnam(value)[2] except KeyError: raise OptionValueError('group not found: %r' % value) setattr(parser.values, option.dest, value)
def check_ip_option(option, opt, value, allow_loopback=False): try: if allow_loopback: return CheckedIPAddressLoopback(value) else: return CheckedIPAddress(value) except Exception as e: raise OptionValueError("option {}: invalid IP address {}: {}".format( opt, value, e))
def checkserver(option, opt_str, value, parser): m = re.match(r"^([^:]+?)(?::(\d+))?$", value) if m is None: raise OptionValueError( u"A00001: If you use %s option, specify HOST or HOST:PORT style." % opt_str) parser.values.server = m.group(1) if m.group(2) is not None: parser.values.port = m.group(2)
def check_ip_address(option, opt_str, value, parser): '''Check IP address as an OptionParser callback Postcondition: sets value to proper option if check passes Raises: OptionValueError if IP address is malformed ''' segments = value.split(".") if len(segments) != 4: raise OptionValueError(_("\nMalformed IP address: '%s'\n") % value) for segment in segments: try: segment = int(segment) if segment < 0 or segment > 255: raise OptionValueError( _("\nMalformed IP address: '%s'\n") % value) except (ValueError, TypeError): raise OptionValueError(_("\nMalformed IP address: '%s'\n") % value) setattr(parser.values, option.dest, value)
def process_manylinux(option, option_str, option_value, parser): if option_str.startswith('--no'): setattr(parser.values, option.dest, None) elif option_value.startswith('manylinux'): setattr(parser.values, option.dest, option_value) else: raise OptionValueError( 'Please specify a manylinux standard; ie: --manylinux=manylinux1. ' 'Given {}'.format(option_value))
def validate(self): """ Validate digs the fqdn and IP address. If either of these do not resolve properly, raise an error If the bootstrap option is specified, validate checks to make sure that the script exists """ # Slice off the last character from the result [:-2] checked_hostname = Popen("dig +short -x %s" % self.args[1], stdout=PIPE, shell=True).communicate()[0][:-2] checked_ip = Popen("dig +short %s" % self.args[0], stdout=PIPE, shell=True).communicate()[0].strip() if checked_hostname != self.args[0] or checked_ip != self.args[1]: raise OptionValueError('Your FQDN and IP do not resolve properly') bootstrap = os.path.join(self.bootstrap_path, self.options.bootstrap) if os.path.exists(bootstrap) is not True: raise OptionValueError('The specified bootstrap script does not exist')
def _cb_cmd_opt(option, opt_str, value, parser): """OptionParser callback, which handles command options""" if hasattr(parser.values, 'command'): # raise error if two exlusive commands appeared msg = _('Please specify only one command option') raise OptionValueError(msg) parser.values.command = opt_str parser.values.command_values = value parser.values.args = option.args
def loglevel_callback(option, opt_str, value, parser): value = value.upper() choices = ['NOTSET', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'] if not value in choices: raise OptionValueError( '%s is not a valid loglevel. You can only choose from %s' % (value, ', '.join(choices))) loglevel = getattr(logging, value) setattr(parser.values, option.dest, loglevel)
def _store_root_version(): if 'ROOTSYS' in os.environ: vstart = os.environ['ROOTSYS'].find('ROOT/') + 5 vend = os.environ['ROOTSYS'][vstart:].find('/') rootversion = os.environ['ROOTSYS'][vstart:vstart + vend] os.environ['ROOTVERSION'] = rootversion else: msg = 'Tried to setup ROOTVERSION environment variable but no ROOTSYS variable found.' raise OptionValueError(msg)
def prange_callback(option, opt_str, value, parser, *args, **kwargs): # e.g.: ./script.py --prange=0,64 -> xrange(0,64) object match = re.match("^(\d+),(\d+)$", value) if match: p0, p1 = int(match.group(1)), int(match.group(2)) else: match = re.match("^(\d+)$", value) if match: p0 = int(match.group(1)) p1 = p0 + 1 else: raise OptionValueError( "Invalid --param-range / -p format.") if not p0 < p1: raise OptionValueError( "Invalid --param-range / -p specified: second value must be greater than first value" ) setattr(parser.values, "prange", range(p0, p1))
def check_unicode(option, opt, value): """Check that the value is a unicode string.""" if not isinstance(value, bytes): return value try: return value.decode(sys.getdefaultencoding()) except UnicodeDecodeError: raise OptionValueError('option {}: Cannot decode: {}'.format( opt, value))
def split_name(value): """ Split an option in form ``NAME:VALUE`` and check if ``NAME`` exists. """ parts = value.split(':', 1) if len(parts) != 2: raise OptionValueError( "option value must be specified as NAME:VALUE; got '%s' instead" % value) name, val = parts if name not in api_register: raise OptionValueError( "the name '%s' has not been registered; use --external-api" % name) return (name, val)
def __to_seconds(self, option, opt_string, time_string, parser): match = re.search(self.time_pattern, time_string) if not match: raise OptionValueError('Invalid time format for option {}'.format( option.dest)) ts = dict( map(lambda g: (g, int(match.group(g) or '0')), ['h', 'm', 's'])) seconds = ts['h'] * 3600 + ts['m'] * 60 + ts['s'] setattr(parser.values, option.dest, seconds)
def _user(option, opt_str, value, parser): try: value = int(value) except ValueError: try: value = pwd.getpwnam(value)[2] except KeyError: raise OptionValueError('user not found: %r' % value) setattr(parser.values, option.dest, value)
def MoveAction(option, opt, value, parser): errorIfMultipleOption(parser.rargs) if(len(parser.rargs) == 0 ): raise OptionValueError("No argument found. This option requires at least one argument.") stor = helper_get_stor_dir() if(stor is None): exit("Unable to connect to the Airtime server.") dest = stor+"organize/" copy_or_move_files_to(parser.rargs, dest, 'move')
def check_slice(option, opt, value): """ returns an int or slice """ try: return str2slice_or_int(value) except ValueError: message = "option %s: invalid slice value: %r" % (opt, value) raise OptionValueError(message)
def parserCB_UpdateConfig(self, option, opt_str, value, parser): "Used by the optparse object as a callback function for the --defaults argument" if not self.__jobxml_parsed: try: self.read(value) setattr(parser.values, option.dest, value) except Exception, e: raise OptionValueError( 'Failed to parse configuration file (%s): %s' % (value, e))
def StorageSetAction(option, opt, value, parser): bypass = False isF = '-f' in parser.rargs isForce = '--force' in parser.rargs if(isF or isForce ): bypass = True if(isF): parser.rargs.remove('-f') if(isForce): parser.rargs.remove('--force') if(not bypass): errorIfMultipleOption(parser.rargs, "Only [-f] and [--force] option is allowed with this option.") possibleInput = ['y','Y','n','N'] confirm = raw_input("Are you sure you want to change the storage direcory? (y/N)") confirm = confirm or 'N' while(confirm not in possibleInput): print "Not an acceptable input: %s\n" % confirm confirm = raw_input("Are you sure you want to change the storage direcory? (y/N) ") confirm = confirm or 'N' if(confirm == 'n' or confirm =='N'): sys.exit(1) if(len(parser.rargs) > 1): raise OptionValueError("Too many arguments. This option requires exactly one argument.") elif(len(parser.rargs) == 0 ): raise OptionValueError("No argument found. This option requires exactly one argument.") path = parser.rargs[0] if (path[0] == "/" or path[0] == "~"): path = os.path.realpath(path) else: path = currentDir+path path = apc.encode_to(path, 'utf-8') if(os.path.isdir(path)): res = api_client.set_storage_dir(path) if(res is None): exit("Unable to connect to the Airtime server.") # sucess if(res['msg']['code'] == 0): print "Successfully set storage folder to %s" % path else: print "Setting storage folder failed: %s" % res['msg']['error'] else: print "The given path is not a directory: %s" % path
def check_multiple_choice(option, opt, value): #split_char = ';' if ';' in value else ',' values = value.split(option.split_char) for v in values: if v not in option.mchoices: choices = ",".join(map(repr, option.mchoices)) raise OptionValueError( "option %s: invalid choice: %r (choose from %s)" % (opt, v, choices)) return values
def validServerURL(option, opt_str, value, parser): """ This raises an optparse error if the url is not valid """ if value is not None: if not validURL(value): raise OptionValueError("%s option value '%s' not valid." % (opt_str, value)) setattr(parser.values, option.dest, value) else: setattr(parser.values, option.dest, option.default)
def check_date(option, opt, value): valid_formats = ['%Y-%m-%d', '%Y%m%d', '%Y/%m/%d'] for f in valid_formats: try: dt = datetime.strptime(value, f) return dt.date() except ValueError: pass raise OptionValueError('option %s: invalid date or format: %s. use following format: %s' % (opt, value, ','.join(valid_formats)))
def check_eval(dummy, opt, value): """ Takes `value` and evaluates it as a python expression. """ try: val = eval(str(value)) except: raise OptionValueError("Could not evaluate %s as a python " \ "expression for option %s.\n" % (value, opt)) return val
def check_function( dummy, opt, value ): """ Cast `value` to a function. Currently does nothing. """ try: pass except: raise OptionValueError("Could not evaluate %s into function for " \ "option %s.\n" % (value, opt )) return value
def check_boolean( dummy, opt, value ): """ Cast `value` to a boolean value. """ try: val = bool(value) except: raise OptionValueError("Could not evalute %s into boolean for " \ "option %s.\n" % (value, opt)) return val
def check_expr( dummy, opt, value ): """ Evaluate `value` as an expression. """ try: val = eval(value) except: raise OptionValueError( "Could not evaluate value for option %s:\n%s" % ( opt, value ) ) return val
def check_MAC_address(option, opt_str, value, parser): """ Check MAC address as an OptionParser callback Postcondition: sets value to proper option if check passes Raises: OptionValueError if MAC address is malformed """ try: value = str(com.MACAddress(value)) except com.MACAddress.MACAddressError, e: raise OptionValueError(str(e))
def isfile_callback(option, opt_str, value, parser): """ is the specified path a file? """ if not value: # no file specified -> set default! setattr( parser.values, option.dest, option.default ) elif os.path.isfile(value): # set os.path.abspath of file name setattr( parser.values, option.dest, os.path.abspath(value) ) else: raise OptionValueError("'%s' in not a (regular) file (%s)" % (value,opt_str))
def _check_dict(option, opt, value): if option or opt or value: pass # Shut up lint checker v = value.lower() choices = option.choices try: return choices[v] except KeyError: raise OptionValueError( "option %s: invalid choice: '%s' " \ "(choose from '%s')" % (opt, value, "', '".join(choices)))
def store_verbose_level(option, opt, value, parser): if value == "s" or value == "silent": parser.values.verbose_level = VERBOSE_LEVEL_SILENT elif value == "n" or value == "normal": parser.values.verbose_level = VERBOSE_LEVEL_NORMAL elif value == "v" or value == "verbose": parser.values.verbose_level = VERBOSE_LEVEL_VERBOSE else: format = "should be one of %s: %s" raise OptionValueError(format % (available_values, value))
def store_use_color(option, opt, value, parser): if value == "yes" or value == "true": parser.values.use_color = True elif value == "no" or value == "false": parser.values.use_color = False elif value == "auto" or value is None: pass else: format = "should be one of %s: %s" raise OptionValueError(format % (available_values, value))