def match_time_unit(val):
'''match some val against time shortcut inputs '''
match = re.match("^(\d+(\.\d+)?)([m|h]?)$", val)
if match:
digit = float(match.group(1))
unit = match.group(3)
if not unit:
return digit
elif unit == 'm':
return digit*60
else:
return digit*60*60
else:
raise argparse.ArgumentTypeError("Duration should be passed in the following format: \n"
"-d 100 : in sec \n"
"-d 10m : in min \n"
"-d 1h : in hours")
python类ArgumentTypeError()的实例源码
def int_ge0(text):
"""
Convert given text to an integer greater than or equal to 0.
Used by `ArgumentParser`.
:param text: Text to convert to integer.
:return: An integer greater than or equal to 0.
"""
try:
# Convert to int
int_value = int(text)
# Ensure greater than or equal to 0
assert int_value >= 0
except Exception:
# Raise an exception to notify ArgumentParser
raise ArgumentTypeError(
'`%s` is not an integer greater than or equal to 0.' % text)
# Return the valid value
return int_value
def read_file(filename, mode="rb"):
"""Returns the given file's contents.
:param str filename: path to file
:param str mode: open mode (see `open`)
:returns: absolute path of filename and its contents
:rtype: tuple
:raises argparse.ArgumentTypeError: File does not exist or is not readable.
"""
try:
filename = os.path.abspath(filename)
return filename, open(filename, mode).read()
except IOError as exc:
raise argparse.ArgumentTypeError(exc.strerror)
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
def valid_date(indate):
"""
Check date format is valid
"""
try:
return datetime.datetime.strptime(indate, "%Y-%m-%d %H:%M:%S")
except ValueError:
msg = "Not a valid date: '{0}'.".format(indate)
raise argparse.ArgumentTypeError(msg)
def create_dir(dirname):
if not os.path.isdir(dirname):
try:
os.makedirs(dirname)
except:
msg = "Cannot create directory: {0}".format(dirname)
raise argparse.ArgumentTypeError(msg)
return dirname
def parse_is_dir(dirname):
if not os.path.isdir(dirname):
msg = "{0} is not a directory".format(dirname)
raise argparse.ArgumentTypeError(msg)
else:
return dirname
def parse_is_file(dirname):
if not os.path.isfile(dirname):
msg = "{0} is not a file".format(dirname)
raise argparse.ArgumentTypeError(msg)
else:
return dirname
def parse_ignore_range(string):
m = re.match(r"(\d+)(?:-(\d+))?$", string)
if not m:
raise argparse.ArgumentTypeError("'" + string + "' is not a range of number.")
start = min(int(m.group(1)), int(m.group(2)))
end = max(int(m.group(1)), int(m.group(2))) or start
if end > (128 << 10):
raise argparse.ArgumentTypeError("Value out of range (max 128KB).")
if start == 0 and end == (128 << 10):
raise argparse.ArgumentTypeError("Invalid range specified.")
return list([start, end])
def parse_range_ip_filter(string):
m = re.match(r"([(0-9abcdef]{1,16})(?:-([0-9abcdef]{1,16}))?$", string.replace("0x", "").lower())
if not m:
raise argparse.ArgumentTypeError("'" + string + "' is not a range of number.")
#print(m.group(1))
#print(m.group(2))
start = min(int(m.group(1).replace("0x", ""), 16), int(m.group(2).replace("0x", ""), 16))
end = max(int(m.group(1).replace("0x", ""), 16), int(m.group(2).replace("0x", ""), 16)) or start
if start > end:
raise argparse.ArgumentTypeError("Invalid range specified.")
return list([start, end])
def check(value):
if '=' not in value:
raise argparse.ArgumentTypeError('%s is not a k=v string' % (value))
return tuple(value.split('=', 2))
def posnum(arg):
"""Make sure that command line arg is a positive number."""
value = float(arg)
if value < 0:
raise argparse.ArgumentTypeError("Value must not be negative!")
return value
def is_output_directory_valid(filename):
if os.path.exists(filename):
raise argparse.ArgumentTypeError("The output directory already exists")
return filename
def is_fastq_valid(filename):
if not os.path.exists(filename):
raise argparse.ArgumentTypeError('Cannot access input file')
return filename
def is_kmer_valid(value_str):
if value_str.isdigit():
kmer = int(value_str)
if kmer%2 == 1 and kmer >= 21 and kmer <= 255:
return kmer
raise argparse.ArgumentTypeError("Invalid Kmer value, it must be an odd integer between 21 and 255")
def is_min_kmers_threshold_valid(value_str):
if value_str.isdigit():
min_kmers_threshold = int(value_str)
if min_kmers_threshold >= 0 and min_kmers_threshold <= 255:
return min_kmers_threshold
raise argparse.ArgumentTypeError("Invalid minimum kmers threshold, it must be between 0 and 255, but ideally less than half the mean coverage.")
def is_max_kmers_threshold_valid(value_str):
if value_str.isdigit():
max_kmers_threshold = int(value_str)
if max_kmers_threshold >= 10 and max_kmers_threshold <= 255:
return max_kmers_threshold
raise argparse.ArgumentTypeError("Invalid maximum kmers threshold, it must be between 10 and 255, and greater than the minimum kmer value, but ideally greater than the coverage.")
def path(d):
try:
assert os.path.isdir(d)
return d
except Exception as e:
raise argparse.ArgumentTypeError("Example {} cannot be located.".format(d))
def parse_attribute(attr):
try:
category, attr = attr.split(':')
except ValueError:
raise ArgumentTypeError('should be in format <category>:<attribute>')
return category, attr
def __call__(self, csv):
args = csv.split(',')
remainder = sorted(set(args) - set(self.choices))
if remainder:
msg = "invalid choices: %r (choose from %r)" % (remainder, self.choices)
raise argparse.ArgumentTypeError(msg)
return args