Python argparse.ArgumentError() Examples

The following are 30 code examples of argparse.ArgumentError(). 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: args.py    From rekall with GNU General Public License v2.0 7 votes vote down vote up
def parse_int(self, value):
        # Support suffixes
        multiplier = 1
        m = re.search("(.*)(Mb|mb|kb|m|M|k|g|G|Gb)", value)
        if m:
            value = m.group(1)
            suffix = m.group(2).lower()
            if suffix in ("gb", "g"):
                multiplier = 1024 * 1024 * 1024
            elif suffix in ("mb", "m"):
                multiplier = 1024 * 1024
            elif suffix in ("kb", "k"):
                multiplier = 1024

        try:
            if value.startswith("0x"):
                value = int(value, 16) * multiplier
            else:
                value = int(value) * multiplier
        except ValueError:
            raise argparse.ArgumentError(self, "Invalid integer value")

        return value 
Example #2
Source File: test_app.py    From cliff with Apache License 2.0 6 votes vote down vote up
def test_conflicting_option_should_throw(self):
        class MyApp(application.App):
            def __init__(self):
                super(MyApp, self).__init__(
                    description='testing',
                    version='0.1',
                    command_manager=commandmanager.CommandManager('tests'),
                )

            def build_option_parser(self, description, version):
                parser = super(MyApp, self).build_option_parser(description,
                                                                version)
                parser.add_argument(
                    '-h', '--help',
                    default=self,  # tricky
                    help="Show help message and exit.",
                )

        self.assertRaises(
            argparse.ArgumentError,
            MyApp,
        ) 
Example #3
Source File: PlotBasicRasters.py    From LSDMappingTools with MIT License 6 votes vote down vote up
def MakeBasemapDirectory(this_dir):
    # check if a raster directory exists. If not then make it.
    basemap_directory = this_dir+'basemap_plots/'
    print("I am printing to a raster directory:")
    print(basemap_directory)
    if not os.path.isdir(basemap_directory):
        os.makedirs(basemap_directory)    

#=============================================================================
# The normal float parsing doesn't work if on of the floats is 
# negative so I need to do this malarky -- SMM 2/03/2019
# see
# https://stackoverflow.com/questions/9025204/python-argparse-issue-with-optional-arguments-which-are-negative-numbers
#=============================================================================  
#def two_floats(value):
#    values = value.split()
#    if len(values) != 2:
#        raise argparse.ArgumentError
#    values = map(float, values)
#    return values       
        
#=============================================================================
# This parses a comma separated string
#============================================================================= 
Example #4
Source File: params.py    From ParlAI with MIT License 6 votes vote down vote up
def add_model_subargs(self, model):
        """
        Add arguments specific to a particular model.
        """
        agent = load_agent_module(model)
        try:
            if hasattr(agent, 'add_cmdline_args'):
                agent.add_cmdline_args(self)
        except argparse.ArgumentError:
            # already added
            pass
        try:
            if hasattr(agent, 'dictionary_class'):
                s = class2str(agent.dictionary_class())
                self.set_defaults(dict_class=s)
        except argparse.ArgumentError:
            # already added
            pass 
Example #5
Source File: params.py    From ParlAI with MIT License 6 votes vote down vote up
def add_image_args(self, image_mode):
        """
        Add additional arguments for handling images.
        """
        try:
            parlai = self.add_argument_group('ParlAI Image Preprocessing Arguments')
            parlai.add_argument(
                '--image-size',
                type=int,
                default=256,
                help='resizing dimension for images',
                hidden=True,
            )
            parlai.add_argument(
                '--image-cropsize',
                type=int,
                default=224,
                help='crop dimension for images',
                hidden=True,
            )
        except argparse.ArgumentError:
            # already added
            pass 
Example #6
Source File: esptool.py    From nodemcu-pyflasher with MIT License 6 votes vote down vote up
def __call__(self, parser, namespace, values, option_string=None):
        try:
            value = {
                '2m': '256KB',
                '4m': '512KB',
                '8m': '1MB',
                '16m': '2MB',
                '32m': '4MB',
                '16m-c1': '2MB-c1',
                '32m-c1': '4MB-c1',
            }[values[0]]
            print("WARNING: Flash size arguments in megabits like '%s' are deprecated." % (values[0]))
            print("Please use the equivalent size '%s'." % (value))
            print("Megabit arguments may be removed in a future release.")
        except KeyError:
            value = values[0]

        known_sizes = dict(ESP8266ROM.FLASH_SIZES)
        known_sizes.update(ESP32ROM.FLASH_SIZES)
        if self._auto_detect:
            known_sizes['detect'] = 'detect'
        if value not in known_sizes:
            raise argparse.ArgumentError(self, '%s is not a known flash size. Known sizes: %s' % (value, ", ".join(known_sizes.keys())))
        setattr(namespace, self.dest, value) 
Example #7
Source File: esptool.py    From nodemcu-pyflasher with MIT License 6 votes vote down vote up
def __call__(self, parser, namespace, value, option_string=None):
        if value.upper() == "SPI":
            value = 0
        elif value.upper() == "HSPI":
            value = 1
        elif "," in value:
            values = value.split(",")
            if len(values) != 5:
                raise argparse.ArgumentError(self, '%s is not a valid list of comma-separate pin numbers. Must be 5 numbers - CLK,Q,D,HD,CS.' % value)
            try:
                values = tuple(int(v,0) for v in values)
            except ValueError:
                raise argparse.ArgumentError(self, '%s is not a valid argument. All pins must be numeric values' % values)
            if any([v for v in values if v > 33 or v < 0]):
                raise argparse.ArgumentError(self, 'Pin numbers must be in the range 0-33.')
            # encode the pin numbers as a 32-bit integer with packed 6-bit values, the same way ESP32 ROM takes them
            # TODO: make this less ESP32 ROM specific somehow...
            clk,q,d,hd,cs = values
            value = (hd << 24) | (cs << 18) | (d << 12) | (q << 6) | clk
        else:
            raise argparse.ArgumentError(self, '%s is not a valid spi-connection value. ' +
                                         'Values are SPI, HSPI, or a sequence of 5 pin numbers CLK,Q,D,HD,CS).' % value)
        setattr(namespace, self.dest, value) 
Example #8
Source File: esptool.py    From phatsniffer with MIT License 6 votes vote down vote up
def __call__(self, parser, namespace, values, option_string=None):
        # validate pair arguments
        pairs = []
        for i in range(0,len(values),2):
            try:
                address = int(values[i],0)
            except ValueError as e:
                raise argparse.ArgumentError(self,'Address "%s" must be a number' % values[i])
            try:
                argfile = open(values[i + 1], 'rb')
            except IOError as e:
                raise argparse.ArgumentError(self, e)
            except IndexError:
                raise argparse.ArgumentError(self,'Must be pairs of an address and the binary filename to write there')
            pairs.append((address, argfile))
        setattr(namespace, self.dest, pairs)


# This is "wrapped" stub_flasher.c, to  be loaded using run_stub. 
Example #9
Source File: sploit.py    From CVE-2016-6366 with MIT License 6 votes vote down vote up
def _parse(self, args):
        '''

        '''
        

        self.pre_parse(args)
        

        self.parser.parse_args(args[1:], self.params)
        

        try:
            self.post_parse()
        except argparse.ArgumentError, e:

            self.parser.error(str(e)) 
Example #10
Source File: esptool.py    From esptool with GNU General Public License v2.0 6 votes vote down vote up
def __call__(self, parser, namespace, value, option_string=None):
        if value.upper() == "SPI":
            value = 0
        elif value.upper() == "HSPI":
            value = 1
        elif "," in value:
            values = value.split(",")
            if len(values) != 5:
                raise argparse.ArgumentError(self, '%s is not a valid list of comma-separate pin numbers. Must be 5 numbers - CLK,Q,D,HD,CS.' % value)
            try:
                values = tuple(int(v,0) for v in values)
            except ValueError:
                raise argparse.ArgumentError(self, '%s is not a valid argument. All pins must be numeric values' % values)
            if any([v for v in values if v > 33 or v < 0]):
                raise argparse.ArgumentError(self, 'Pin numbers must be in the range 0-33.')
            # encode the pin numbers as a 32-bit integer with packed 6-bit values, the same way ESP32 ROM takes them
            # TODO: make this less ESP32 ROM specific somehow...
            clk,q,d,hd,cs = values
            value = (hd << 24) | (cs << 18) | (d << 12) | (q << 6) | clk
        else:
            raise argparse.ArgumentError(self, '%s is not a valid spi-connection value. ' +
                                         'Values are SPI, HSPI, or a sequence of 5 pin numbers CLK,Q,D,HD,CS).' % value)
        setattr(namespace, self.dest, value) 
Example #11
Source File: parseractions.py    From eclcli with Apache License 2.0 6 votes vote down vote up
def __call__(self, parser, namespace, values, option_string=None):
        range = values.split(':')
        if len(range) == 0:
            # Nothing passed, return a zero default
            setattr(namespace, self.dest, (0, 0))
        elif len(range) == 1:
            # Only a single value is present
            setattr(namespace, self.dest, (int(range[0]), int(range[0])))
        elif len(range) == 2:
            # Range of two values
            if int(range[0]) <= int(range[1]):
                setattr(namespace, self.dest, (int(range[0]), int(range[1])))
            else:
                msg = "Invalid range, %s is not less than %s" % \
                    (range[0], range[1])
                raise argparse.ArgumentError(self, msg)
        else:
            # Too many values
            msg = "Invalid range, too many values"
            raise argparse.ArgumentError(self, msg) 
Example #12
Source File: cli.py    From appr with Apache License 2.0 6 votes vote down vote up
def cli():
    try:
        parser = get_parser(all_commands())
        unknown = None
        args, unknown = parser.parse_known_args()
        set_cmd_env(args.env)
        if args.parse_unknown:
            args.func(args, unknown)
        else:
            args = parser.parse_args()
            args.func(args)

    except (argparse.ArgumentTypeError, argparse.ArgumentError) as exc:
        if os.getenv("APPR_DEBUG", "false") == "true":
            raise
        else:
            parser.error(exc.message) 
Example #13
Source File: __init__.py    From qubes-core-admin with GNU Lesser General Public License v2.1 6 votes vote down vote up
def __init__(self, option_strings, nargs=1, dest='vmnames', help=None,
                 **kwargs):
        if help is None:
            if nargs == argparse.OPTIONAL:
                help = 'at most one domain name'
            elif nargs == 1:
                help = 'a domain name'
            elif nargs == argparse.ZERO_OR_MORE:
                help = 'zero or more domain names'
            elif nargs == argparse.ONE_OR_MORE:
                help = 'one or more domain names'
            elif nargs > 1:
                help = '%s domain names' % nargs
            else:
                raise argparse.ArgumentError(
                    nargs, "Passed unexpected value {!s} as {!s} nargs ".format(
                        nargs, dest))

        super(VmNameAction, self).__init__(option_strings, dest=dest, help=help,
                                           nargs=nargs, **kwargs) 
Example #14
Source File: __init__.py    From qubes-core-admin with GNU Lesser General Public License v2.1 6 votes vote down vote up
def __init__(self, option_strings, nargs=1, dest='vmnames', help=None,
                 **kwargs):
        # pylint: disable=redefined-builtin
        if help is None:
            if nargs == argparse.OPTIONAL:
                help = 'at most one running domain'
            elif nargs == 1:
                help = 'running domain name'
            elif nargs == argparse.ZERO_OR_MORE:
                help = 'zero or more running domains'
            elif nargs == argparse.ONE_OR_MORE:
                help = 'one or more running domains'
            elif nargs > 1:
                help = '%s running domains' % nargs
            else:
                raise argparse.ArgumentError(
                    nargs, "Passed unexpected value {!s} as {!s} nargs ".format(
                        nargs, dest))
        super(RunningVmNameAction, self).__init__(
            option_strings, dest=dest, help=help, nargs=nargs, **kwargs) 
Example #15
Source File: argparse.py    From torchsupport with MIT License 6 votes vote down vote up
def add_kwarg_parse(parser, kwarg, doc, namespace=None):
  """
  Logic to add a parser flag for a kwarg stored in a Parameter object
  Supports namespacing
  """
  if namespace is None:
    namespace = ""
  name = kwarg.name
  typ = _maybe(kwarg.annotation, str)
  default = _maybe(kwarg.default, None)
  try:
    parser.add_argument(f"--{name}", default=None, type=typ, help=doc)
  except argparse.ArgumentError:
    pass
  parser.add_argument(f"--{namespace}-{name}", default=None, type=typ, help=doc)
  return default 
Example #16
Source File: main.py    From parserator with MIT License 6 votes vote down vote up
def __call__(self, parser, namespace, string, option_string):
        try:
            with open(string, 'r') as f:
                tree = etree.parse(f)
                xml = tree.getroot()
        except (OSError, IOError):
            xml = None
        except etree.XMLSyntaxError as e:
            if 'Document is empty' not in str(e):
                raise argparse.ArgumentError(self,
                                             "%s does not seem to be a valid xml file"
                                             % string)
            xml = None

        setattr(namespace, self.dest, string)
        setattr(namespace, 'xml', xml) 
Example #17
Source File: argparse_completer.py    From WebPocket with GNU General Public License v3.0 6 votes vote down vote up
def _match_argument(self, action, arg_strings_pattern) -> int:
        # match the pattern for this action to the arg strings
        nargs_pattern = self._get_nargs_pattern(action)
        match = _re.match(nargs_pattern, arg_strings_pattern)

        # raise an exception if we weren't able to find a match
        if match is None:
            if isinstance(action, _RangeAction) and \
                    action.nargs_min is not None and action.nargs_max is not None:
                raise ArgumentError(action,
                                    'Expected between {} and {} arguments'.format(action.nargs_min, action.nargs_max))

        return super(ACArgumentParser, self)._match_argument(action, arg_strings_pattern)

    # This is the official python implementation with a 5 year old patch applied
    # See the comment below describing the patch 
Example #18
Source File: esptool.py    From esptool with GNU General Public License v2.0 6 votes vote down vote up
def __call__(self, parser, namespace, values, option_string=None):
        try:
            value = {
                '2m': '256KB',
                '4m': '512KB',
                '8m': '1MB',
                '16m': '2MB',
                '32m': '4MB',
                '16m-c1': '2MB-c1',
                '32m-c1': '4MB-c1',
            }[values[0]]
            print("WARNING: Flash size arguments in megabits like '%s' are deprecated." % (values[0]))
            print("Please use the equivalent size '%s'." % (value))
            print("Megabit arguments may be removed in a future release.")
        except KeyError:
            value = values[0]

        known_sizes = dict(ESP8266ROM.FLASH_SIZES)
        known_sizes.update(ESP32ROM.FLASH_SIZES)
        if self._auto_detect:
            known_sizes['detect'] = 'detect'
            known_sizes['keep'] = 'keep'
        if value not in known_sizes:
            raise argparse.ArgumentError(self, '%s is not a known flash size. Known sizes: %s' % (value, ", ".join(known_sizes.keys())))
        setattr(namespace, self.dest, value) 
Example #19
Source File: cli.py    From pakala with GNU General Public License v3.0 5 votes vote down vote up
def ethWeiAmount(arg):
    m = re.match(r"^([0-9.]+) ?(\w+)$", arg)
    if m is None:
        raise argparse.ArgumentError(
            "The argument must be in the form '1 ether' for example."
        )
    return Web3.toWei(float(m.group(1)), m.group(2)) 
Example #20
Source File: gencon-hotel-check.py    From gencon-hotel-check with GNU General Public License v3.0 5 votes vote down vote up
def __call__(self, parser, namespace, values, option_string = None):
		for pattern in (
			'^https://book.passkey.com/reg/([0-9A-Z]{8}-[0-9A-Z]{4})/([0-9a-f]{1,64})$',
			'^https://book.passkey.com/event/[0-9]+/owner/[0-9]+/r/([0-9A-Z]{8})/([0-9a-f]{32})',
		):
			m = reCompile(pattern).match(values)
			if m:
				setattr(namespace, self.dest, m.groups())
				return
		raise ArgumentError(self, "invalid passkey url: '%s'" % values) 
Example #21
Source File: main.py    From parserator with MIT License 5 votes vote down vote up
def __call__(self, parser, namespace, model_file, option_string):
        module = namespace.module

        if hasattr(module, 'MODEL_FILES'):
            try:
                model_path = module.__name__ + '/'  +module.MODEL_FILES[model_file]
            except KeyError:
                msg = """
                      Invalid --modelfile argument
                      Models available: %s"""
                raise argparse.ArgumentTypeError(text.dedent(msg) % module.MODEL_FILES)
        else:
            raise argparse.ArgumentError(self, 'This parser does not allow for multiple models')

        setattr(namespace, self.dest, model_path) 
Example #22
Source File: humanhash.py    From django-q with MIT License 5 votes vote down vote up
def __init__(self, wordlist=DEFAULT_WORDLIST):
        if len(wordlist) != 256:
            raise ArgumentError("Wordlist must have exactly 256 items")
        self.wordlist = wordlist 
Example #23
Source File: init.py    From pipenv with MIT License 5 votes vote down vote up
def run(self, options):
        pipfile_path = os.path.join(options.project, "Pipfile")
        if os.path.exists(pipfile_path):
            raise argparse.ArgumentError(
                "{0!r} is already a Pipfile project".format(options.project),
            )
        return init_project(
            root=options.project, python_version=options.python_version
        ) 
Example #24
Source File: params.py    From ParlAI with MIT License 5 votes vote down vote up
def add_task_args(self, task):
        """
        Add arguments specific to the specified task.
        """
        for t in ids_to_tasks(task).split(','):
            agent = load_teacher_module(t)
            try:
                if hasattr(agent, 'add_cmdline_args'):
                    agent.add_cmdline_args(self)
            except argparse.ArgumentError:
                # already added
                pass 
Example #25
Source File: test_argparse.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_conflicting_parents(self):
        self.assertRaises(
            argparse.ArgumentError,
            argparse.ArgumentParser,
            parents=[self.w_parent, self.wxyz_parent]) 
Example #26
Source File: params.py    From ParlAI with MIT License 5 votes vote down vote up
def add_world_args(self, task, interactive_task, selfchat_task):
        """
        Add arguments specific to the world.
        """
        world_class = load_world_module(
            task, interactive_task=interactive_task, selfchat_task=selfchat_task
        )
        if world_class is not None and hasattr(world_class, 'add_cmdline_args'):
            try:
                world_class.add_cmdline_args(self)
            except argparse.ArgumentError:
                # already added
                pass 
Example #27
Source File: cli.py    From scanpy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __getitem__(self, k: str) -> ArgumentParser:
        try:
            return self.parser_map[k]
        except KeyError:
            if which(f'{self.command}-{k}'):
                return _DelegatingParser(self, k)
            # Only here is the command list retrieved
            raise ArgumentError(
                self.action, f'No command “{k}”. Choose from {set(self)}'
            ) 
Example #28
Source File: options.py    From pipenv with MIT License 5 votes vote down vote up
def __init__(self, root, *args, **kwargs):
        root = vistir.compat.Path(root).absolute()
        pipfile = root.joinpath("Pipfile")
        if not pipfile.is_file():
            raise argparse.ArgumentError(
                "project", "{0!r} is not a Pipfile project".format(root),
            )
        try:
            super(Project, self).__init__(root.as_posix(), *args, **kwargs)
        except tomlkit.exceptions.ParseError as e:
            raise argparse.ArgumentError(
                "project", "failed to parse Pipfile: {0!r}".format(str(e)),
            ) 
Example #29
Source File: compress_fast5.py    From ont_fast5_api with Mozilla Public License 2.0 5 votes vote down vote up
def main():
    parser = ArgumentParser("Tool for changing the compression of Fast5 files")
    parser.add_argument('-i', '--input_path', required=True,
                        help='Folder containing single read fast5 files')

    output_group = parser.add_mutually_exclusive_group(required=True)
    save_arg = output_group.add_argument('-s', '--save_path', default=None,
                                         help="Folder to output multi read files to")
    output_group.add_argument('--in_place', action='store_true',
                              help='Replace the old files with new files in place')

    parser.add_argument('-c', '--compression', required=True, choices=list(COMPRESSION_MAP.keys()),
                        help="Target output compression type")
    parser.add_argument('-t', '--threads', type=int, default=1, required=False,
                        help="Maximum number of threads to use")
    parser.add_argument('--recursive', action='store_true',
                        help="Search recursively through folders for single_read fast5 files")
    parser.add_argument('--ignore_symlinks', action='store_true',
                        help="Ignore symlinks when searching recursively for fast5 files")
    parser.add_argument('-v', '--version', action='version', version=__version__)
    args = parser.parse_args()

    if args.input_path == args.save_path:
        raise ArgumentError(save_arg, "--input_path and --save_path must be different locations, or use --in_place")

    compress_batch(input_folder=args.input_path,
                   output_folder=args.save_path,
                   target_compression=COMPRESSION_MAP[args.compression],
                   threads=args.threads,
                   recursive=args.recursive,
                   follow_symlinks=not args.ignore_symlinks,
                   in_place=args.in_place) 
Example #30
Source File: gencon-hotel-check.py    From gencon-hotel-check with GNU General Public License v3.0 5 votes vote down vote up
def __call__(self, parser, namespace, values, option_string = None):
		raise ArgumentError(self, "option no longer exists. Existing reservation lookups are now done with your hash instead of your surname")