Python argparse.ArgumentTypeError() Examples

The following are 30 code examples of argparse.ArgumentTypeError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module argparse , or try the search function .
Example #1
Source File: validators.py    From ripe-atlas-tools with GNU General Public License v3.0 6 votes vote down vote up
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
            ) 
Example #2
Source File: search_cli_arguments.py    From VxAPI with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #3
Source File: default_cli_arguments.py    From VxAPI with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #4
Source File: __init__.py    From tox with MIT License 6 votes vote down vote up
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",
    ) 
Example #5
Source File: assign_role.py    From JetPack with Apache License 2.0 6 votes vote down vote up
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) 
Example #6
Source File: validators.py    From ripe-atlas-tools with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #7
Source File: validators.py    From ripe-atlas-tools with GNU General Public License v3.0 6 votes vote down vote up
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."
            ) 
Example #8
Source File: validators.py    From ripe-atlas-tools with GNU General Public License v3.0 6 votes vote down vote up
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") 
Example #9
Source File: validators.py    From ripe-atlas-tools with GNU General Public License v3.0 6 votes vote down vote up
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") 
Example #10
Source File: devappserver2_test.py    From browserscope with Apache License 2.0 5 votes vote down vote up
def test_port_too_high(self):
    self.assertRaises(argparse.ArgumentTypeError, devappserver2.PortParser(),
                      '65536') 
Example #11
Source File: validators.py    From ripe-atlas-tools with GNU General Public License v3.0 5 votes vote down vote up
def alias_is_valid(string):
        ret = None

        if string and not string.isdigit():
            pattern = re.compile("^[a-zA-Z\._\-0-9]+$")

            if pattern.match(string):
                ret = string

        if not ret:
            raise argparse.ArgumentTypeError(
                '"{}" does not appear to be a valid '
                'alias.'.format(string))

        return ret 
Example #12
Source File: validators.py    From ripe-atlas-tools with GNU General Public License v3.0 5 votes vote down vote up
def __call__(self, string):
            if string.isdigit():
                return int(string)

            if string in aliases[self.TYPE]:
                return int(aliases[self.TYPE][string])
            else:
                raise argparse.ArgumentTypeError(
                    '"{}" does not appear to be an existent '
                    '{} alias.'.format(string, self.TYPE)
                ) 
Example #13
Source File: validators.py    From ripe-atlas-tools with GNU General Public License v3.0 5 votes vote down vote up
def __call__(self, string):

            r = []

            for i in string.split(","):

                try:
                    i = int(i)
                except ValueError:
                    raise argparse.ArgumentTypeError(
                        "The ids supplied were not in the correct format. Note "
                        "that you must specify them as a list of "
                        "comma-separated integers without spaces.  Example: "
                        "1,2,34,157,10006"
                    )

                if i < self.minimum:
                    raise argparse.ArgumentTypeError(
                        "{} is lower than the minimum permitted value of "
                        "{}.".format(i, self.minimum)
                    )
                if i > self.maximum:
                    raise argparse.ArgumentTypeError(
                        "{} exceeds the maximum permitted value of {}.".format(
                            i, self.maximum)
                    )

                r.append(i)

            return r 
Example #14
Source File: config.py    From c3dpo_nrsfm with MIT License 5 votes vote down vote up
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.') 
Example #15
Source File: config.py    From c3dpo_nrsfm with MIT License 5 votes vote down vote up
def arg_as_list(s):
    v = ast.literal_eval(s)
    if type(v) is not list:
        raise argparse.ArgumentTypeError("Argument \"%s\" is not a list" % (s))
    return v 
Example #16
Source File: devappserver2_test.py    From browserscope with Apache License 2.0 5 votes vote down vote up
def test_port_zero_not_allowed(self):
    self.assertRaises(argparse.ArgumentTypeError,
                      devappserver2.PortParser(allow_port_zero=False), '0') 
Example #17
Source File: devappserver2_test.py    From browserscope with Apache License 2.0 5 votes vote down vote up
def test_negative_port(self):
    self.assertRaises(argparse.ArgumentTypeError, devappserver2.PortParser(),
                      '-1') 
Example #18
Source File: devappserver2_test.py    From browserscope with Apache License 2.0 5 votes vote down vote up
def test_single_zero_arg(self):
    self.assertRaises(argparse.ArgumentTypeError,
                      devappserver2.parse_max_server_instances, '0') 
Example #19
Source File: devappserver2_test.py    From browserscope with Apache License 2.0 5 votes vote down vote up
def test_multiple_non_colon(self):
    self.assertRaises(
        argparse.ArgumentTypeError,
        devappserver2.parse_max_server_instances, 'default:10,foo') 
Example #20
Source File: validators.py    From ripe-atlas-tools with GNU General Public License v3.0 5 votes vote down vote up
def __call__(self, string):

            if not self.regex.match(string):
                raise argparse.ArgumentTypeError(
                    '"{}" does not appear to be valid.'.format(string))

            return string 
Example #21
Source File: validators.py    From ripe-atlas-tools with GNU General Public License v3.0 5 votes vote down vote up
def test_integer_range(self):

        self.assertEqual(1, ArgumentType.integer_range(1, 10)("1"))
        self.assertEqual(10, ArgumentType.integer_range(1, 10)("10"))
        self.assertEqual(1, ArgumentType.integer_range(-1, 1)("1"))
        self.assertEqual(-1, ArgumentType.integer_range(-1, 1)("-1"))

        for value in ("0", "11", "-1"):
            with self.assertRaises(argparse.ArgumentTypeError):
                ArgumentType.integer_range(1, 10)(value) 
Example #22
Source File: validators.py    From ripe-atlas-tools with GNU General Public License v3.0 5 votes vote down vote up
def ip_or_domain(string):
        message = '"{}" does not appear to be an IP address or host ' \
                  'name'.format(string)

        if " " in string:
            raise argparse.ArgumentTypeError(message)
        if "." not in string and ":" not in string:
            if not re.match(r"^\w+$", string):
                raise argparse.ArgumentTypeError(message)

        return string 
Example #23
Source File: validators.py    From ripe-atlas-tools with GNU General Public License v3.0 5 votes vote down vote up
def datetime(string):
        try:
            return parser.parse(string)
        except:
            raise argparse.ArgumentTypeError(
                "Times must be specified in ISO 8601 format.  For example: "
                "2010-10-01T00:00:00 or a portion thereof.  All times are in "
                "UTC."
            ) 
Example #24
Source File: validators.py    From ripe-atlas-tools with GNU General Public License v3.0 5 votes vote down vote up
def country_code(string):
        if not re.match(r"^[a-zA-Z][a-zA-Z]$", string):
            raise argparse.ArgumentTypeError(
                "Countries must be defined with a two-letter ISO code")
        return string.upper() 
Example #25
Source File: validators.py    From ripe-atlas-tools with GNU General Public License v3.0 5 votes vote down vote up
def path(string):
        if not os.path.exists(string) and not string == "-":
            raise argparse.ArgumentTypeError(
                'The file name specified, "{}" does not appear to exist'.format(
                    string
                )
            )
        return string 
Example #26
Source File: id_to_mol2.py    From screenlamp with Apache License 2.0 5 votes vote down vote up
def str2bool(v):
    if v.lower() in ('yes', 'true', 't', 'y', '1'):
        return True
    if v.lower() in ('no', 'false', 'f', 'n', '0'):
        return False
    else:
        raise argparse.ArgumentTypeError('Boolean value expected.') 
Example #27
Source File: id_to_mol2.py    From screenlamp with Apache License 2.0 5 votes vote down vote up
def str2bool(v):
    if v.lower() in ('yes', 'true', 't', 'y', '1'):
        return True
    if v.lower() in ('no', 'false', 'f', 'n', '0'):
        return False
    else:
        raise argparse.ArgumentTypeError('Boolean value expected.') 
Example #28
Source File: val.py    From Fast_Seg with Apache License 2.0 5 votes vote down vote up
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.') 
Example #29
Source File: train_distribute.py    From Fast_Seg with Apache License 2.0 5 votes vote down vote up
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.') 
Example #30
Source File: tools.py    From Fast_Seg with Apache License 2.0 5 votes vote down vote up
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.')