Python argparse.ArgumentTypeError() Examples

The following are code examples for showing how to use argparse.ArgumentTypeError(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: test_argparse.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_argument_type_error(self):

        def spam(string):
            raise argparse.ArgumentTypeError('spam!')

        parser = ErrorRaisingArgumentParser(prog='PROG', add_help=False)
        parser.add_argument('x', type=spam)
        try:
            parser.parse_args(['XXX'])
        except ArgumentParserError:
            expected = 'usage: PROG x\nPROG: error: argument x: spam!\n'
            msg = sys.exc_info()[1].stderr
            self.assertEqual(expected, msg)
        else:
            self.fail()

# ================================================
# Check that the type function is called only once
# ================================================ 
Example 2
Project: flasky   Author: RoseOu   File: input.py    MIT License 6 votes vote down vote up
def __call__(self, string):
        """Parse credentials from `string`.

        ("username" or "username:password").

        """
        try:
            return super(AuthCredentialsArgType, self).__call__(string)
        except ArgumentTypeError:
            # No password provided, will prompt for it later.
            return self.key_value_class(
                key=string,
                value=None,
                sep=SEP_CREDENTIALS,
                orig=string
            ) 
Example 3
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: idmapshift.py    Apache License 2.0 6 votes vote down vote up
def id_map_type(val):
    maps = val.split(',')
    id_maps = []
    for m in maps:
        map_vals = m.split(':')

        if len(map_vals) != 3:
            msg = ('Invalid id map %s, correct syntax is '
                   'guest-id:host-id:count.')
            raise argparse.ArgumentTypeError(msg % val)

        try:
            vals = [int(i) for i in map_vals]
        except ValueError:
            msg = 'Invalid id map %s, values must be integers' % val
            raise argparse.ArgumentTypeError(msg)

        id_maps.append(tuple(vals))
    return id_maps 
Example 4
Project: multiprot   Author: strubelab   File: parseChains.py    Apache License 2.0 6 votes vote down vote up
def divide(s):
    """
    Converts entries for the --chain argument into tuples, and checks if PDB file
    exists

    E.g.
    ABCD.pdb:A --> ('ABCD.pdb','A')
    ABCD.pdb   --> ('ABCD.pdb',)
    
    :param s: string with one of the entries for --chain argument
    :type s: str

    """
    r = tuple(s.split(':'))
    # Does not work... find out why
    # if not os.path.exists(r[0]):
    #     raise argparse.ArgumentTypeError('Specified PDB file does not exist')
    
    return r 
Example 5
Project: PlateTectonicTools   Author: EarthByte   File: rotation_tools.py    GNU General Public License v2.0 6 votes vote down vote up
def __call__(self, parser, namespace, values, option_string=None):
            # Need two numbers (rotation threshold and threshold time interval).
            if len(values) != 2:
                parser.error('accuracy must be specified as two numbers (rotation threshold and threshold time interval)')
            
            try:
                # Convert strings to float.
                threshold_rotation_accuracy_degrees = float(values[0])
                threshold_time_interval = float(values[1])
            except ValueError:
                raise argparse.ArgumentTypeError("encountered a rotation threshold and threshold time interval that is not a number")
            
            if threshold_rotation_accuracy_degrees <= 0 or threshold_rotation_accuracy_degrees > 90:
                parser.error('rotation threshold must be in the range (0, 90]')
            if threshold_time_interval <= 0:
                parser.error('threshold time interval must be positive')
            
            setattr(namespace, self.dest, (threshold_rotation_accuracy_degrees, threshold_time_interval)) 
Example 6
Project: PlateTectonicTools   Author: EarthByte   File: remove_plate_rotations.py    GNU General Public License v2.0 6 votes vote down vote up
def __call__(self, parser, namespace, values, option_string=None):
            # Need two numbers (rotation threshold and threshold time interval).
            if len(values) != 2:
                parser.error('accuracy must be specified as two numbers (rotation threshold and threshold time interval)')
            
            try:
                # Convert strings to float.
                threshold_rotation_accuracy_degrees = float(values[0])
                threshold_time_interval = float(values[1])
            except ValueError:
                raise argparse.ArgumentTypeError("encountered a rotation threshold and threshold time interval that is not a number")
            
            if threshold_rotation_accuracy_degrees < 0 or threshold_rotation_accuracy_degrees > 90:
                parser.error('rotation threshold must be in the range [0, 90]')
            if threshold_time_interval <= 0:
                parser.error('threshold time interval must be positive')
            
            setattr(namespace, self.dest, (threshold_rotation_accuracy_degrees, threshold_time_interval)) 
Example 7
Project: bpb   Author: black-percentage-bot   File: bpb.py    Do What The F*ck You Want To Public License 6 votes vote down vote up
def check_log(p):
	if os.path.isfile(p) and os.access(p, os.R_OK) and os.access(p, os.W_OK):
		return p
	else:
		try:
			open(p, 'a').close()
		except Exception as e:
			raise argparse.ArgumentTypeError("The defined log file \""+str(p)+"\" is not a file or read-/writeable.")
			
		if os.path.isfile(p) and os.access(p, os.R_OK) and os.access(p, os.W_OK):
			return p
		else:
			raise argparse.ArgumentTypeError("The defined log file \""+str(p)+"\" is not a file or read-/writeable.")

# Process all comments, takes loads of arguments
# sub = Submission
# tri = Trigger string
# ver = Verbouse flag
# prc = Processed list
# log = Logfile
# iex = Image extensions
# msg = Bot message
# dbg = Debug flag 
Example 8
Project: bpb   Author: black-percentage-bot   File: bpb.py    Do What The F*ck You Want To Public License 6 votes vote down vote up
def check_intervall(i):

	try:
		if isinstance(int(i[:-1]),int):
			if i.lower().endswith('s'):
				return int(i[:-1])
			elif i.lower().endswith('m'):
				return int(i[:-1])*60
			elif i.lower().endswith('h'):
				return int(i[:-1])*60*60
			else:
				raise argparse.ArgumentTypeError("The defined intervall unit \""+str(i[-1])+"\" is not supported. Use 's' for seconds, 'm' for minutes or 'h' for hours (e.g -i 427s)")
		else:
			raise argparse.ArgumentTypeError("The defined intervall time \""+str(i[:-1])+"\" is not an integer.")
	except ValueError as e:
		raise argparse.ArgumentTypeError("The defined intervall time \""+str(i[:-1])+"\" is not an integer.")

# calculate percentage
# returns list of percentage, trueblack pixel count and total number of 
# m defines the mode: "online" or "offline". 
Example 9
Project: PEAKachu   Author: tbischler   File: float_range.py    ISC License 5 votes vote down vote up
def frac_float(string_value):
    value = float(string_value)
    if value < 0.0 or value > 1.0:
        raise argparse.ArgumentTypeError("{} not in range [0.0, 1.0]".format(
            value))
    return value 
Example 10
Project: godot-mono-builds   Author: godotengine   File: cmd_utils.py    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 11
Project: pyblish-win   Author: pyblish   File: test_argparse.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_argument_error(self):
        msg = "my error here"
        error = argparse.ArgumentError(None, msg)
        self.assertEqual(str(error), msg)

# =======================
# ArgumentTypeError tests
# ======================= 
Example 12
Project: robust-atd   Author: shadowbq   File: __init__.py    MIT License 5 votes vote down vote up
def check_md5(value):
    if len(value) != 32:
        raise argparse.ArgumentTypeError("%s is an invalid md5 hash value" % value)
    return value 
Example 13
Project: robust-atd   Author: shadowbq   File: __init__.py    MIT License 5 votes vote down vote up
def slash_dir(value):
    if value[len(value)-1] != "/":
        raise argparse.ArgumentTypeError("%s should end in a slash" % value)
    value = os.path.expanduser(value)
    return value 
Example 14
Project: utilities   Author: czbiohub   File: evros.py    MIT License 5 votes vote down vote up
def resource_range(name, min_val, max_val):
    def range_validator(s):
        value = int(s)
        if value < min_val:
            msg = f"{name} must be at least"
            raise argparse.ArgumentTypeError(msg)
        if value > max_val:
            msg = f"{name} can be at most"
            raise argparse.ArgumentTypeError(msg)
        return value

    return range_validator 
Example 15
Project: nmp_qc   Author: priba   File: demo_grec_intnet.py    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_qm9_duvenaud.py    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_gwhist_ggnn.py    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_intnet.py    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_qm9_ggnn.py    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_letter_ggnn.py    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_grec_duvenaud.py    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_qm9_mpnn.py    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: demo_gwhist_duvenaud.py    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
Project: nmp_qc   Author: priba   File: demo_grec_mpnn.py    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 25
Project: nmp_qc   Author: priba   File: main.py    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 26
Project: flasky   Author: RoseOu   File: input.py    MIT License 5 votes vote down vote up
def _guess_method(self):
        """Set `args.method` if not specified to either POST or GET
        based on whether the request has data or not.

        """
        if self.args.method is None:
            # Invoked as `http URL'.
            assert not self.args.items
            if not self.args.ignore_stdin and not self.env.stdin_isatty:
                self.args.method = HTTP_POST
            else:
                self.args.method = HTTP_GET

        # FIXME: False positive, e.g., "localhost" matches but is a valid URL.
        elif not re.match('^[a-zA-Z]+$', self.args.method):
            # Invoked as `http URL item+'. The URL is now in `args.method`
            # and the first ITEM is now incorrectly in `args.url`.
            try:
                # Parse the URL as an ITEM and store it as the first ITEM arg.
                self.args.items.insert(
                    0,
                    KeyValueArgType(*SEP_GROUP_ITEMS).__call__(self.args.url)
                )

            except ArgumentTypeError as e:
                if self.args.traceback:
                    raise
                self.error(e.message)

            else:
                # Set the URL correctly
                self.args.url = self.args.method
                # Infer the method
                has_data = (
                    (not self.args.ignore_stdin and
                     not self.env.stdin_isatty) or any(
                        item.sep in SEP_GROUP_DATA_ITEMS
                        for item in self.args.items
                    )
                )
                self.args.method = HTTP_POST if has_data else HTTP_GET 
Example 27
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: image_segmentaion.py    Apache License 2.0 5 votes vote down vote up
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 28
Project: GSM-SGD   Author: DingXiaoH   File: pyt_utils.py    MIT License 5 votes vote down vote up
def extant_file(x):
    """
    'Type' for argparse - checks that file exists but does not open.
    """
    if not os.path.exists(x):
        # Argparse uses the ArgumentTypeError to give a rejection message like:
        # error: argument input: x does not exist
        raise argparse.ArgumentTypeError("{0} does not exist".format(x))
    return x 
Example 29
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: test_idmapshift.py    Apache License 2.0 5 votes vote down vote up
def test_id_map_type_not_int(self):
        self.assertRaises(argparse.ArgumentTypeError, idmapshift.id_map_type,
                          "a:1:1") 
Example 30
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: test_idmapshift.py    Apache License 2.0 5 votes vote down vote up
def test_id_map_type_not_proper_format(self):
        self.assertRaises(argparse.ArgumentTypeError, idmapshift.id_map_type,
                          "1:1") 
Example 31
Project: CAFA_assessment_tool   Author: ashleyzhou972   File: tc_main_forTCfiles.py    GNU General Public License v3.0 5 votes vote down vote up
def extant_file(x):
        if not os.path.isfile(x):
            raise argparse.ArgumentTypeError("{0} does not exist".format(x))
        else:
            return(x) 
Example 32
Project: CAFA_assessment_tool   Author: ashleyzhou972   File: assess_main.py    GNU General Public License v3.0 5 votes vote down vote up
def extant_file(x):
    if not os.path.isfile(x):
        raise argparse.ArgumentTypeError("{0} does not exist".format(x))
    else:
        return(open(x,'r')) 
Example 33
Project: CAFA_assessment_tool   Author: ashleyzhou972   File: plot.py    GNU General Public License v3.0 5 votes vote down vote up
def extant_file(x):
    if not os.path.isfile(x):
        raise argparse.ArgumentTypeError("{0} does not exist".format(x))
    else:
        return(open(x,'r')) 
Example 34
Project: dogTorch   Author: ehsanik   File: main.py    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 35
Project: dogTorch   Author: ehsanik   File: main.py    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 36
Project: ACAN   Author: miraiaroha   File: __init__.py    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 37
Project: view-finding-network   Author: yiling-chen   File: vfn_train.py    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 38
Project: view-finding-network   Author: yiling-chen   File: vfn_eval.py    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 39
Project: Parallel.GAMIT   Author: demiangomez   File: Utils.py    GNU General Public License v3.0 5 votes vote down vote up
def required_length(nmin,nmax):
    class RequiredLength(argparse.Action):
        def __call__(self, parser, args, values, option_string=None):
            if not nmin<=len(values)<=nmax:
                msg='argument "{f}" requires between {nmin} and {nmax} arguments'.format(
                    f=self.dest,nmin=nmin,nmax=nmax)
                raise argparse.ArgumentTypeError(msg)
            setattr(args, self.dest, values)
    return RequiredLength 
Example 40
Project: garleek   Author: insilichem   File: cli.py    MIT License 5 votes vote down vote up
def _extant_file(path, abspath=False):
    if os.path.isfile(path):
        if abspath:
            return os.path.abspath(path)
        return path
    raise ArgumentTypeError("File `{}` cannot be found".format(path)) 
Example 41
Project: garleek   Author: insilichem   File: cli.py    MIT License 5 votes vote down vote up
def _extant_file_prm(path, abspath=False):
    if os.path.isfile(path):
        if abspath:
            return os.path.abspath(path)
        return path
    indatapath = os.path.join(_here, 'data', 'prm', path)
    if os.path.isfile(indatapath):
        if abspath:
            return indatapath
        return path
    if os.path.isfile(indatapath + '.prm'):
        if abspath:
            return indatapath + '.prm'
        return path
    raise ArgumentTypeError("File `{}` cannot be found".format(path)) 
Example 42
Project: garleek   Author: insilichem   File: cli.py    MIT License 5 votes vote down vote up
def _extant_file_types(path, abspath=False):
    if os.path.isfile(path):
        if abspath:
            return os.path.abspath(path)
        return path
    indatapath = os.path.join(_here, 'data', 'atom_types', path)
    if os.path.isfile(indatapath):
        if abspath:
            return indatapath
        return path
    raise ArgumentTypeError("File `{}` cannot be found".format(path)) 
Example 43
Project: mx   Author: graalvm   File: mx.py    GNU General Public License v2.0 5 votes vote down vote up
def _parse_multireleasejar_version(value):
    try:
        mrjVersion = int(value)
        if mrjVersion < 9:
            raise ArgumentTypeError('multi-release jar version ({}) must be greater than 8'.format(value))
        return mrjVersion
    except ValueError:
        raise ArgumentTypeError('multi-release jar version ({}) must be an int value greater than 8'.format(value)) 
Example 44
Project: mx   Author: graalvm   File: mx_unittest.py    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 
Example 45
Project: twitterscraper   Author: taspinar   File: main.py    MIT License 5 votes vote down vote up
def valid_date(s):
    try:
        return dt.datetime.strptime(s, "%Y-%m-%d").date()
    except ValueError:
        msg = "Not a valid date: '{0}'.".format(s)
        raise argparse.ArgumentTypeError(msg) 
Example 46
Project: PlateTectonicTools   Author: EarthByte   File: convert_xy_to_gplates.py    GNU General Public License v2.0 5 votes vote down vote up
def unicode_filename(value_string):
        try:
            # Filename uses the system encoding - decode from 'str' to 'unicode'.
            filename = value_string.decode(sys.getfilesystemencoding())
        except UnicodeDecodeError:
            raise argparse.ArgumentTypeError("Unable to convert filename %s to unicode" % value_string)
        
        return filename 
Example 47
Project: vrgan   Author: ricbl   File: opts.py    MIT License 5 votes vote down vote up
def str2bool(v):
    if isinstance(v, bool):
       return 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 48
Project: pytorch-segmentation-toolbox   Author: speedinghzl   File: train.py    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 49
Project: hacking-tools   Author: girishramnani   File: _pfish_tools.py    MIT License 5 votes vote down vote up
def ValidateDirectory(theDir):
    if not os.path.isdir(theDir):
        raise argparse.ArgumentTypeError("Directory does not exist")
    else:
        return theDir 
Example 50
Project: hacking-tools   Author: girishramnani   File: _pfish_tools.py    MIT License 5 votes vote down vote up
def ValidateDirectoryWritable(theDir):
    if not os.path.isdir(theDir):
        raise argparse.ArgumentTypeError("Directory does not exist")
    if os.access(theDir,os.W_OK):
        return theDir
    else:
        raise argparse.ArgumentTypeError("Directory is not writable") 
Example 51
Project: wdl-cell-ranger   Author: chanzuckerberg   File: utils.py    MIT License 5 votes vote down vote up
def str_to_bool(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 52
Project: ommprotocol   Author: insilichem   File: utils.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def extant_file(path):
    """
    Check if file exists with argparse
    """
    if not os.path.exists(path):
        raise argparse.ArgumentTypeError("{} does not exist".format(path))
    return path 
Example 53
Project: smoke-zephyr   Author: zeroSteiner   File: argparse_types.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __call__(self, arg):
		if hasattr(self.regex, 'match'):
			result = self.regex.match(arg)
		else:
			result = re.match(self.regex, arg)
		if not result:
			raise argparse.ArgumentTypeError(self.error_message.format(arg=repr(arg)))
		return arg 
Example 54
Project: smoke-zephyr   Author: zeroSteiner   File: argparse_types.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __call__(self, arg):
		try:
			arg = ast.literal_eval(arg)
		except ValueError:
			raise argparse.ArgumentTypeError("{arg} is invalid".format(arg=repr(arg)))
		if not isinstance(arg, int):
			raise argparse.ArgumentTypeError("{arg} is invalid".format(arg=repr(arg)))
		if arg < self.start:
			raise argparse.ArgumentTypeError("{arg} is invalid (low)".format(arg=repr(arg)))
		if arg > self.stop:
			raise argparse.ArgumentTypeError("{arg} is invalid (high)".format(arg=repr(arg)))
		return arg 
Example 55
Project: smoke-zephyr   Author: zeroSteiner   File: argparse_types.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def bin_b64_type(arg):
	"""An argparse type representing binary data encoded in base64."""
	try:
		arg = base64.standard_b64decode(arg)
	except (binascii.Error, TypeError):
		raise argparse.ArgumentTypeError("{0} is invalid base64 data".format(repr(arg)))
	return arg 
Example 56
Project: smoke-zephyr   Author: zeroSteiner   File: argparse_types.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def bin_hex_type(arg):
	"""An argparse type representing binary data encoded in hex."""
	if re.match(r'^[a-f0-9]{2}(:[a-f0-9]{2})+$', arg, re.I):
		arg = arg.replace(':', '')
	elif re.match(r'^(\\x[a-f0-9]{2})+$', arg, re.I):
		arg = arg.replace('\\x', '')
	try:
		arg = binascii.a2b_hex(arg)
	except (binascii.Error, TypeError):
		raise argparse.ArgumentTypeError("{0} is invalid hex data".format(repr(arg)))
	return arg 
Example 57
Project: smoke-zephyr   Author: zeroSteiner   File: argparse_types.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def dir_type(arg):
	"""An argparse type representing a valid directory."""
	if not os.path.isdir(arg):
		raise argparse.ArgumentTypeError("{0} is not a valid directory".format(repr(arg)))
	return arg 
Example 58
Project: smoke-zephyr   Author: zeroSteiner   File: argparse_types.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def log_level_type(arg):
	"""An argparse type representing a logging level."""
	if not arg.upper() in ('NOTSET', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'):
		raise argparse.ArgumentTypeError("{0} is not a valid log level".format(repr(arg)))
	return getattr(logging, arg.upper()) 
Example 59
Project: smoke-zephyr   Author: zeroSteiner   File: argparse_types.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def port_type(arg):
	"""An argparse type representing a tcp or udp port number."""
	error_msg = "{0} is not a valid port".format(repr(arg))
	try:
		arg = ast.literal_eval(arg)
	except ValueError:
		raise argparse.ArgumentTypeError(error_msg)
	if arg < 0 or arg > 65535:
		raise argparse.ArgumentTypeError(error_msg)
	return arg 
Example 60
Project: smoke-zephyr   Author: zeroSteiner   File: argparse_types.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def timespan_type(arg):
	"""An argparse type representing a timespan such as 6h for 6 hours."""
	try:
		arg = parse_timespan(arg)
	except ValueError:
		raise argparse.ArgumentTypeError("{0} is not a valid time span".format(repr(arg)))
	return arg 
Example 61
Project: smoke-zephyr   Author: zeroSteiner   File: argparse_types.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _invalid_argparse_type(self, function, invalid):
		with self.assertRaises(argparse.ArgumentTypeError):
			function(invalid) 
Example 62
Project: hnbex-cli   Author: ihabunek   File: console.py    GNU General Public License v3.0 5 votes vote down vote up
def date_type(value):
    if value.lower() == 'today':
        return date.today()

    if value.lower() == 'tomorrow':
        return date.today() + timedelta(days=1)

    try:
        value = datetime.strptime(value, "%Y-%m-%d").date()
    except:
        raise ArgumentTypeError("Invalid date '{}'".format(value))

    return value 
Example 63
Project: hnbex-cli   Author: ihabunek   File: console.py    GNU General Public License v3.0 5 votes vote down vote up
def currency_type(value):
    if not re.match("^[a-z]{3}$", value, re.IGNORECASE):
        raise ArgumentTypeError("Invalid currency code '{}'".format(value))

    return value.upper() 
Example 64
Project: graph-keyword-search   Author: usc-isi-i2   File: util.py    Apache License 2.0 5 votes vote down vote up
def validDatestamp(string):
    if re.search(r"""^201[2-9][01][0-9][0-3][0-9]$""", string):
        value=int(string)
    else:
        msg = "%r is not a valid datestamp" % string
        raise argparse.ArgumentTypeError(msg)
    return value 
Example 65
Project: graph-keyword-search   Author: usc-isi-i2   File: util.py    Apache License 2.0 5 votes vote down vote up
def validDatestampRange(string):
    m = re.search(r"""^(201[2-9][01][0-9][0-3][0-9]):(201[2-9][01][0-9][0-3][0-9])$""", string)
    if m:
        d1 = int(m.group(1))
        d2 = int(m.group(2))
        if d1 < d2:
            value = (d1, d2)
    else:
        msg = "%r is not a valid datestamp range" % string
        raise argparse.ArgumentTypeError(msg)
    return value 
Example 66
Project: graph-keyword-search   Author: usc-isi-i2   File: util.py    Apache License 2.0 5 votes vote down vote up
def validDatestampOrRange(string):
    try:
        return validDatestampRange(string)
    except argparse.ArgumentTypeError as e:
        try:
            return validDatestamp(string)
        except argparse.ArgumentTypeError as e:
            msg = "%r is neither a valid datestamp nor a datestamp range" % string
            raise argparse.ArgumentTypeError(msg)

# haversine great circle distance 
Example 67
Project: AvereSDK   Author: Azure   File: vfxt.py    MIT License 5 votes vote down vote up
def _validate_ip(addr):
    addr = addr.split('/')[0]
    octets = [n for n in addr.split('.') if n != '']
    if len(octets) != 4:
        raise argparse.ArgumentTypeError("malformed IP address: {}".format(addr))
    try:
        if all([0 <= v <= 255 for v in [int(n) for n in octets]]):
            return addr
        raise ValueError(addr)
    except Exception:
        raise argparse.ArgumentTypeError("malformed IP address: {}".format(addr)) 
Example 68
Project: AvereSDK   Author: Azure   File: vfxt.py    MIT License 5 votes vote down vote up
def _validate_url(url):
    parsed = urlparse.urlparse(url)
    if parsed.hostname:
        return url
    raise argparse.ArgumentTypeError("malformed URL: {}".format(url)) 
Example 69
Project: AvereSDK   Author: Azure   File: vfxt.py    MIT License 5 votes vote down vote up
def _validate_ascii(s):
    try:
        _ = s.encode('ascii')
        return s
    except Exception:
        raise argparse.ArgumentTypeError("Value must be ASCII: {}".format(s)) 
Example 70
Project: AvereSDK   Author: Azure   File: vfxt.py    MIT License 5 votes vote down vote up
def _validate_writeable_path(p):
    f = None
    try:
        f = open(p, 'wb')
        return p
    except Exception as e:
        raise argparse.ArgumentTypeError("Invalid file {}: {}".format(p, e))
    finally:
        if f:
            f.close() 
Example 71
Project: PokeInkDis   Author: llakssz   File: PokeInkDis.py    GNU General Public License v3.0 5 votes vote down vote up
def poke_check(string):
    try:
        value = int(string)
        if (value < 1) or (value > total_pokes):
            msg = "{0} is not valid. Choose a number from 1 to {1}".format(string, total_pokes)
            raise argparse.ArgumentTypeError(msg)
        return value
    except ValueError:
        msg = "{0} is not valid. Choose a number from 1 to {1}".format(string, total_pokes)
        raise argparse.ArgumentTypeError(msg) 
Example 72
Project: ConvLab   Author: ConvLab   File: run_woz.py    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 73
Project: ConvLab   Author: ConvLab   File: util.py    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 74
Project: ConvLab   Author: ConvLab   File: util.py    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 75
Project: VMED   Author: thaihungle   File: qa_task.py    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 76
Project: nlp-notebooks   Author: eric-haibin-lin   File: ner_utils.py    Apache License 2.0 5 votes vote down vote up
def str2bool(v):
    """Utility function for parsing boolean in argparse

    https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse

    :param v: value of the argument
    :return:
    """
    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 77
Project: bpb   Author: black-percentage-bot   File: bpb.py    Do What The F*ck You Want To Public License 5 votes vote down vote up
def check_offline(p):
	if (os.path.isfile(p) or os.path.isdir(p)) and os.access(p, os.R_OK):
		return p
	else:
		raise argparse.ArgumentTypeError("\""+str(p)+"\" is not a directory, a file or it's not readable.")

# parse valid url from string
# only the first link in the string will be returned 
Example 78
Project: custodia   Author: latchset   File: args.py    GNU General Public License v3.0 5 votes vote down vote up
def instance_name(string):
    """Check for valid instance name
    """
    invalid = ':/@'
    if set(string).intersection(invalid):
        msg = 'Invalid instance name {}'.format(string)
        raise argparse.ArgumentTypeError(msg)
    return string 
Example 79
Project: custodia   Author: latchset   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def server_check(arg):
    """Check and format --server arg
    """
    if arg.startswith(('http://', 'https://', 'http+unix://')):
        return arg
    if arg.startswith('./'):
        arg = os.path.abspath(arg)
    elif not arg.startswith('/'):
        raise argparse.ArgumentTypeError(
            'Unix socket path must start with / or ./')
    # assume it is a unix socket
    return 'http+unix://{}'.format(url_escape(arg, '')) 
Example 80
Project: Parallel.GAMIT   Author: demiangomez   File: DownloadSources.py    GNU General Public License v3.0 4 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(description='Archive operations Main Program')

    parser.add_argument('stnlist', type=str, nargs='+', metavar='all|net.stnm',
                        help="List of networks/stations to process given in [net].[stnm] format or just [stnm] (separated by spaces; if [stnm] is not unique in the database, all stations with that name will be processed). Use keyword 'all' to process all stations in the database. If [net].all is given, all stations from network [net] will be processed. Alternatevily, a file with the station list can be provided.")

    parser.add_argument('-date', '--date_range', nargs='+', action=required_length(1,2), metavar='date_start|date_end', help="Date range to check given as [date_start] or [date_start] and [date_end]. Allowed formats are yyyy.doy or yyyy/mm/dd..")
    parser.add_argument('-win', '--window', nargs=1, metavar='days', type=int,
                        help="Download data from a given time window determined by today - {days}.")

    try:
        args = parser.parse_args()

        cnn = dbConnection.Cnn('gnss_data.cfg')
        Config = pyOptions.ReadOptions('gnss_data.cfg')

        if len(args.stnlist) == 1 and os.path.isfile(args.stnlist[0]):
            print ' >> Station list read from ' + args.stnlist[0]
            stnlist = [line.strip() for line in open(args.stnlist[0], 'r')]
            stnlist = [{'NetworkCode': item.split('.')[0], 'StationCode': item.split('.')[1]} for item in stnlist]
        else:
            stnlist = Utils.process_stnlist(cnn, args.stnlist)

        print ' >> Selected station list:'
        print_columns([item['NetworkCode'] + '.' + item['StationCode'] for item in stnlist])

        dates = []

        try:
            if args.window:
                # today - ndays
                d = pyDate.Date(year=datetime.now().year, month=datetime.now().month, day=datetime.now().day)
                dates = [d-int(args.window[0]), d]
            else:
                dates = process_date(args.date_range)

        except ValueError as e:
            parser.error(str(e))

        if dates[0] < pyDate.Date(gpsWeek=650, gpsWeekDay=0):
            dates = [pyDate.Date(gpsWeek=650, gpsWeekDay=0),
                     pyDate.Date(year=datetime.now().year, month=datetime.now().month, day=datetime.now().day)]

        # go through the dates
        drange = np.arange(dates[0].mjd, dates[1].mjd + 1, 1)

        download_data(cnn, Config, stnlist, drange)

    except argparse.ArgumentTypeError as e:
        parser.error(str(e))