本文整理汇总了Python中argparse.ArgumentTypeError方法的典型用法代码示例。如果您正苦于以下问题:Python argparse.ArgumentTypeError方法的具体用法?Python argparse.ArgumentTypeError怎么用?Python argparse.ArgumentTypeError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类argparse
的用法示例。
在下文中一共展示了argparse.ArgumentTypeError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: add_submit_files_arg
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentTypeError [as 别名]
def add_submit_files_arg(self):
def validate_path(path):
files = [path]
if os.path.exists(path) is False:
raise argparse.ArgumentTypeError('No such file or directory: \'{}\''.format(path))
if os.path.isdir(path):
if path.startswith('/') is True: # Given path is absolute
abs_path = path
else:
abs_path = '/'.join(os.path.dirname(os.path.realpath(__file__)).split('/')[:-2] + [path])
files = list(filter(lambda path: os.path.isfile(path), ['{}/{}'.format(abs_path, x) for x in os.listdir(path)]))
return files
self.parser.add_argument('file', type=validate_path, help='File to submit (when directory given, all files from it will be submitted - non recursively)')
return self
示例2: add_search_term_av_detect_opt
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentTypeError [as 别名]
def add_search_term_av_detect_opt(self):
def type_av_detect(value):
if value.find('-'):
values = value.split('-')
else:
values = [value]
for iter_value in values:
forced_int_value = int(iter_value)
if forced_int_value < 0 or forced_int_value > 100:
raise argparse.ArgumentTypeError('{} is not a value between {} and {}'.format(iter_value, 0, 100))
return value
self.parser.add_argument('--av-detect', type=type_av_detect, help='AV Multiscan range e.g. 50-70 (min 0, max 100)')
return self
示例3: comma_separated_integers_or_file
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentTypeError [as 别名]
def comma_separated_integers_or_file(cls, string):
"""
Allow a list of comma-separated integers, or a file containing a
newline-separated list of integers, OR "-" which implies standard out.
"""
if re.match(r"^((\d+,?)+)$", string):
return cls.comma_separated_integers()(string)
f = sys.stdin
if not string == "-":
if not os.path.exists(string):
raise argparse.ArgumentTypeError("Cannot find file: {}".format(
string
))
f = open(string)
try:
return [int(_) for _ in f.readlines()]
except ValueError:
raise argparse.ArgumentTypeError(
"The contents of the file presented does not conform to input "
"standards. Please ensure that every line in the file "
"consists of a single integer."
)
示例4: __call__
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentTypeError [as 别名]
def __call__(self, string):
message = "The integer must be between {} and {}.".format(
self.minimum, self.maximum)
if self.maximum == float("inf"):
message = "The integer must be greater than {}.".format(
self.minimum)
try:
integer = int(string)
if integer < self.minimum or integer > self.maximum:
raise argparse.ArgumentTypeError(message)
except ValueError:
raise argparse.ArgumentTypeError(
"An integer must be specified."
)
return integer
示例5: test_comma_separated_integers
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentTypeError [as 别名]
def test_comma_separated_integers(self):
self.assertEqual(
[1, 2, 3], ArgumentType.comma_separated_integers()("1,2,3"))
self.assertEqual(
[1, 2, 3], ArgumentType.comma_separated_integers()("1, 2, 3"))
self.assertEqual([1], ArgumentType.comma_separated_integers()("1"))
with self.assertRaises(argparse.ArgumentTypeError):
ArgumentType.comma_separated_integers()("1,2,3,pizza!")
with self.assertRaises(argparse.ArgumentTypeError):
ArgumentType.comma_separated_integers(minimum=5)("4,5,6,7")
with self.assertRaises(argparse.ArgumentTypeError):
ArgumentType.comma_separated_integers(maximum=5)("1,2,3,4,6")
示例6: test_datetime
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentTypeError [as 别名]
def test_datetime(self):
d = datetime.datetime(2015, 12, 1)
self.assertEqual(d, ArgumentType.datetime("2015-12-1"))
self.assertEqual(d, ArgumentType.datetime("2015-12-1T00"))
self.assertEqual(d, ArgumentType.datetime("2015-12-1T00:00"))
self.assertEqual(d, ArgumentType.datetime("2015-12-1T00:00:00"))
self.assertEqual(d, ArgumentType.datetime("2015-12-1"))
self.assertEqual(d, ArgumentType.datetime("2015-12-1 00"))
self.assertEqual(d, ArgumentType.datetime("2015-12-1 00:00"))
self.assertEqual(d, ArgumentType.datetime("2015-12-1 00:00:00"))
with self.assertRaises(argparse.ArgumentTypeError):
ArgumentType.datetime("yesterday")
with self.assertRaises(argparse.ArgumentTypeError):
ArgumentType.datetime("Definitely not a date, or even a time")
示例7: test_measurement_alias
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentTypeError [as 别名]
def test_measurement_alias(self):
tests = ["", "\\invalid", "+invalid",
":invalid", "12345"]
for test in tests:
with self.assertRaises(argparse.ArgumentTypeError):
ArgumentType.alias_is_valid(test)
tests = ["valid", "123valid", "valid123", "_valid",
"valid_", "-valid", "valid-", ".valid"]
for test in tests:
self.assertEqual(
ArgumentType.alias_is_valid(test),
test
)
示例8: cli_skip_missing_interpreter
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentTypeError [as 别名]
def cli_skip_missing_interpreter(parser):
class SkipMissingInterpreterAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
value = "true" if values is None else values
if value not in ("config", "true", "false"):
raise argparse.ArgumentTypeError("value must be config, true or false")
setattr(namespace, self.dest, value)
parser.add_argument(
"-s",
"--skip-missing-interpreters",
default="config",
metavar="val",
nargs="?",
action=SkipMissingInterpreterAction,
help="don't fail tests for missing interpreters: {config,true,false} choice",
)
示例9: role_index
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentTypeError [as 别名]
def role_index(string):
role = string
index = None
if string.find("-") != -1:
role_tokens = role.split("-")
role = role_tokens[0]
index = role_tokens[1]
if role not in ROLES.keys():
raise argparse.ArgumentTypeError(
"{} is not a valid role; choices are {}".format(
role, str(
ROLES.keys())))
if index and not index.isdigit():
raise argparse.ArgumentTypeError(
"{} is not a valid role index; it must be a number".format(index))
return RoleIndex(role, index)
示例10: portNumber
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentTypeError [as 别名]
def portNumber(string):
value = int(string)
if 0 <= value <= 65535:
return value
raise argparse.ArgumentTypeError("port must be an integer between 0-65535; got '{}'' instead".format(string))
示例11: converterOptions
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentTypeError [as 别名]
def converterOptions(value):
value = value.lower()
options = ["auto", "librsvg", "webkittopdf", "inkscape", "rsvg-convert"]
if value in options:
return value
raise argparse.ArgumentTypeError("converter must be one of '{}'; got '{}'' instead".format(",".join(options), value))
示例12: custom_bool
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentTypeError [as 别名]
def custom_bool(val):
if isinstance(val, bool):
return val
if val.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif val.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
from argparse import ArgumentTypeError
raise ArgumentTypeError('Boolean value expected.')
示例13: restricted_float
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentTypeError [as 别名]
def restricted_float(x, inter):
x = float(x)
if x < inter[0] or x > inter[1]:
raise argparse.ArgumentTypeError("%r not in range [1e-5, 1e-4]"%(x,))
return x
# Argument parser
示例14: make_file_extension_assertion
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentTypeError [as 别名]
def make_file_extension_assertion(extension):
"""Function factory for file extension argparse assertion
Args:
extension (string): the file extension to assert
Returns:
string: the supplied extension, if assertion is successful.
"""
def file_extension_assertion(file_path):
base, ext = os.path.splitext(file_path)
if ext.lower() != extension:
raise argparse.ArgumentTypeError('File must have ' + extension + ' extension')
return file_path
return file_extension_assertion
示例15: model_class
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentTypeError [as 别名]
def model_class(class_name):
if class_name not in models.__all__:
raise argparse.ArgumentTypeError("Invalid model {}; choices: {}".format(
class_name, models.__all__))
return getattr(models, class_name)