Python argparse.ArgumentTypeError() Examples

The following are 30 code examples for showing how to use argparse.ArgumentTypeError(). These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module argparse , or try the search function .

Example 1
Project: VxAPI   Author: PayloadSecurity   File: default_cli_arguments.py    License: 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 2
Project: VxAPI   Author: PayloadSecurity   File: search_cli_arguments.py    License: 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
Project: ripe-atlas-tools   Author: RIPE-NCC   File: validators.py    License: 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 4
Project: ripe-atlas-tools   Author: RIPE-NCC   File: validators.py    License: 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 5
Project: ripe-atlas-tools   Author: RIPE-NCC   File: validators.py    License: 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 6
Project: ripe-atlas-tools   Author: RIPE-NCC   File: validators.py    License: 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 7
Project: ripe-atlas-tools   Author: RIPE-NCC   File: validators.py    License: 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 8
Project: tox   Author: tox-dev   File: __init__.py    License: 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 9
Project: JetPack   Author: dsp-jetpack   File: assign_role.py    License: 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 10
Project: svviz   Author: svviz   File: commandline.py    License: MIT License 5 votes vote down vote up
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)) 
Example 11
Project: svviz   Author: svviz   File: commandline.py    License: MIT License 5 votes vote down vote up
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)) 
Example 12
Project: godot-mono-builds   Author: godotengine   File: cmd_utils.py    License: MIT License 5 votes vote down vote up
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.') 
Example 13
Project: nmp_qc   Author: priba   File: demo_grec_intnet.py    License: MIT License 5 votes vote down vote up
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 
Example 14
Project: nmp_qc   Author: priba   File: demo_qm9_duvenaud.py    License: MIT License 5 votes vote down vote up
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 
Example 15
Project: nmp_qc   Author: priba   File: demo_gwhist_ggnn.py    License: MIT License 5 votes vote down vote up
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 
Example 16
Project: nmp_qc   Author: priba   File: demo_letter_intnet.py    License: MIT License 5 votes vote down vote up
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 
Example 17
Project: nmp_qc   Author: priba   File: demo_qm9_ggnn.py    License: MIT License 5 votes vote down vote up
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 
Example 18
Project: nmp_qc   Author: priba   File: demo_letter_ggnn.py    License: MIT License 5 votes vote down vote up
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 
Example 19
Project: nmp_qc   Author: priba   File: demo_grec_duvenaud.py    License: MIT License 5 votes vote down vote up
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 
Example 20
Project: nmp_qc   Author: priba   File: demo_qm9_mpnn.py    License: MIT License 5 votes vote down vote up
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 
Example 21
Project: nmp_qc   Author: priba   File: demo_gwhist_duvenaud.py    License: MIT License 5 votes vote down vote up
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 
Example 22
Project: nmp_qc   Author: priba   File: demo_grec_mpnn.py    License: MIT License 5 votes vote down vote up
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 
Example 23
Project: nmp_qc   Author: priba   File: main.py    License: MIT License 5 votes vote down vote up
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 
Example 24
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 
Example 25
Project: dogTorch   Author: ehsanik   File: main.py    License: MIT License 5 votes vote down vote up
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) 
Example 26
Project: dogTorch   Author: ehsanik   File: main.py    License: MIT License 5 votes vote down vote up
def dataset_class(class_name):
    if class_name not in datasets.__all__:
        raise argparse.ArgumentTypeError(
            "Invalid dataset {}; choices: {}".format(class_name,
                                                     datasets.__all__))
    return getattr(datasets, class_name) 
Example 27
Project: ACAN   Author: miraiaroha   File: __init__.py    License: 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 28
Project: view-finding-network   Author: yiling-chen   File: vfn_train.py    License: GNU General Public License v3.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
Project: view-finding-network   Author: yiling-chen   File: vfn_eval.py    License: GNU General Public License v3.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
Project: mx   Author: graalvm   File: mx_unittest.py    License: GNU General Public License v2.0 5 votes vote down vote up
def is_strictly_positive(value):
    try:
        if int(value) <= 0:
            raise ArgumentTypeError("%s must be greater than 0" % value)
    except ValueError:
        raise ArgumentTypeError("%s: integer greater than 0 expected" % value)
    return value