Python argparse.ArgumentError() Examples
The following are 30 code examples for showing how to use argparse.ArgumentError(). 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 check out the related API usage on the sidebar.
You may also want to check out all available functions/classes of the module
argparse
, or try the search function
.
Example 1
Project: rekall Author: google File: args.py License: GNU General Public License v2.0 | 6 votes |
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
Project: LSDMappingTools Author: LSDtopotools File: PlotBasicRasters.py License: MIT License | 6 votes |
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 3
Project: nodemcu-pyflasher Author: marcelstoer File: esptool.py License: MIT License | 6 votes |
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 4
Project: nodemcu-pyflasher Author: marcelstoer File: esptool.py License: MIT License | 6 votes |
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 5
Project: phatsniffer Author: larsjuhljensen File: esptool.py License: MIT License | 6 votes |
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 6
Project: appr Author: app-registry File: cli.py License: Apache License 2.0 | 6 votes |
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 7
Project: torchsupport Author: mjendrusch File: argparse.py License: MIT License | 6 votes |
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 8
Project: cliff Author: openstack File: test_app.py License: Apache License 2.0 | 6 votes |
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 9
Project: qubes-core-admin Author: QubesOS File: __init__.py License: GNU Lesser General Public License v2.1 | 6 votes |
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 10
Project: qubes-core-admin Author: QubesOS File: __init__.py License: GNU Lesser General Public License v2.1 | 6 votes |
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 11
Project: parserator Author: datamade File: main.py License: MIT License | 6 votes |
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 12
Project: WebPocket Author: TuuuNya File: argparse_completer.py License: GNU General Public License v3.0 | 6 votes |
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 13
Project: eclcli Author: nttcom File: parseractions.py License: Apache License 2.0 | 6 votes |
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 14
Project: esptool Author: espressif File: esptool.py License: GNU General Public License v2.0 | 6 votes |
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 15
Project: esptool Author: espressif File: esptool.py License: GNU General Public License v2.0 | 6 votes |
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 16
Project: CVE-2016-6366 Author: RiskSense-Ops File: sploit.py License: MIT License | 6 votes |
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 17
Project: ParlAI Author: facebookresearch File: params.py License: MIT License | 6 votes |
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 18
Project: ParlAI Author: facebookresearch File: params.py License: MIT License | 6 votes |
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 19
Project: redditswapbot Author: thelectronicnub File: flair_sql_import.py License: GNU General Public License v3.0 | 5 votes |
def extant_file(x): if not os.path.exists(x): raise argparse.ArgumentError("{0} does not exist".format(x)) return x
Example 20
Project: redditswapbot Author: thelectronicnub File: flair_sub_import.py License: GNU General Public License v3.0 | 5 votes |
def extant_file(x): if not os.path.exists(x): raise argparse.ArgumentError("{0} does not exist".format(x)) return x
Example 21
Project: simnibs Author: simnibs File: mni2subject_coords.py License: GNU General Public License v3.0 | 5 votes |
def main(): args = parse_arguments(sys.argv[1:]) m2m_dir = os.path.abspath(os.path.realpath(os.path.expanduser(args.m2mpath))) if not os.path.isdir(m2m_dir): raise IOError('Could not find directory: {0}'.format(args.m2mpath)) if args.out is not None: fn_out = os.path.abspath(os.path.realpath(os.path.expanduser(args.out))) fn_geo = os.path.splitext(fn_out)[0] + '.geo' else: fn_out = None fn_geo = None if args.coords is not None: coords = [float(d) for d in args.coords] elif args.csv is not None: coords = os.path.abspath(os.path.realpath(os.path.expanduser(args.csv))) if not os.path.isfile(coords): raise IOError('Could not find CSV file: {0}'.format(args.csv)) else: raise argparse.ArgumentTypeError( 'Plase use either -c or -s') if args.coords is not None and args.csv is not None: raise argparse.ArgumentError( 'Please use only -c or -s') coords = transformations.warp_coordinates( coords, m2m_dir, transformation_direction='mni2subject', out_name=fn_out, transformation_type=args.t, out_geo=fn_geo)[1] if fn_out is None: np.set_printoptions(precision=2, formatter={'float': lambda x: '{0:.2f}'.format(x)}) print('Transformed coodinates:\n{0}'.format(coords.squeeze()))
Example 22
Project: simnibs Author: simnibs File: subject2mni_coords.py License: GNU General Public License v3.0 | 5 votes |
def main(): args = parse_arguments(sys.argv[1:]) m2m_dir = os.path.abspath(os.path.realpath(os.path.expanduser(args.m2mpath))) if not os.path.isdir(m2m_dir): raise IOError('Could not find directory: {0}'.format(args.m2mpath)) if args.out is not None: fn_out = os.path.abspath(os.path.realpath(os.path.expanduser(args.out))) fn_geo = os.path.splitext(fn_out)[0] + '.geo' else: fn_out = None fn_geo = None if args.coords is not None: coords = np.array([float(d) for d in args.coords]) elif args.csv is not None: coords = os.path.abspath(os.path.realpath(os.path.expanduser(args.csv))) if not os.path.isfile(coords): raise IOError('Could not find CSV file: {0}'.format(args.csv)) else: raise argparse.ArgumentTypeError( 'Plase use either -c or -s') if args.coords is not None and args.csv is not None: raise argparse.ArgumentError( 'Please use only -c or -s') coords = transformations.warp_coordinates( coords, m2m_dir, transformation_direction='subject2mni', out_name=fn_out, transformation_type=args.t, out_geo=fn_geo)[1] if fn_out is None: np.set_printoptions(precision=2, formatter={'float': lambda x: '{0:.2f}'.format(x)}) print('Transformed coodinates:\n{0}'.format(coords.squeeze()))
Example 23
Project: spectacles Author: spectacles-ci File: cli.py License: MIT License | 5 votes |
def parse_config(self, path: str) -> dict: """Loads a YAML config file, returning its dictionary format. Args: path: Path to the config file to be loaded. Returns: dict: Dictionary representation of the config file. """ try: with Path(path).open("r") as file: return yaml.safe_load(file) except (FileNotFoundError, ParserError) as error: raise argparse.ArgumentError(self, error)
Example 24
Project: knack Author: microsoft File: arguments.py License: MIT License | 5 votes |
def __call__(self, parser, namespace, values, option_string=None): raise argparse.ArgumentError(None, 'unrecognized argument: {} {}'.format( option_string, values or ''))
Example 25
Project: blackbox-attacks Author: sunblaze-ucb File: mnist.py License: MIT License | 5 votes |
def set_mnist_flags(): try: flags.DEFINE_integer('BATCH_SIZE', 64, 'Size of training batches') except argparse.ArgumentError: pass flags.DEFINE_integer('NUM_CLASSES', 10, 'Number of classification classes') flags.DEFINE_integer('IMAGE_ROWS', 28, 'Input row dimension') flags.DEFINE_integer('IMAGE_COLS', 28, 'Input column dimension') flags.DEFINE_integer('NUM_CHANNELS', 1, 'Input depth dimension')
Example 26
Project: ocdev Author: owncloudarchive File: validators.py License: GNU General Public License v3.0 | 5 votes |
def __call__(self, string): match = re.match(self.regex, string) if not match: raise argparse.ArgumentError(None, self.errorMsg) return string
Example 27
Project: nodemcu-pyflasher Author: marcelstoer File: esptool.py License: MIT License | 5 votes |
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: 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)) # Sort the addresses and check for overlapping end = 0 for address, argfile in sorted(pairs): argfile.seek(0,2) # seek to end size = argfile.tell() argfile.seek(0) sector_start = address & ~(ESPLoader.FLASH_SECTOR_SIZE - 1) sector_end = ((address + size + ESPLoader.FLASH_SECTOR_SIZE - 1) & ~(ESPLoader.FLASH_SECTOR_SIZE - 1)) - 1 if sector_start < end: message = 'Detected overlap at address: 0x%x for file: %s' % (address, argfile.name) raise argparse.ArgumentError(self, message) end = sector_end setattr(namespace, self.dest, pairs) # Binary stub code (see flasher_stub dir for source & details)
Example 28
Project: pyuavcan Author: UAVCAN File: publish.py License: MIT License | 5 votes |
def execute(self, args: argparse.Namespace, subsystems: typing.Sequence[object]) -> int: import pyuavcan.application node, = subsystems assert isinstance(node, pyuavcan.application.Node) with contextlib.closing(node): node.heartbeat_publisher.priority = args.priority node.heartbeat_publisher.period = \ min(pyuavcan.application.heartbeat_publisher.Heartbeat.MAX_PUBLICATION_PERIOD, args.period) raw_ss = args.subject_spec if len(raw_ss) % 2 != 0: raise argparse.ArgumentError('Mismatching arguments: ' 'each subject specifier must be matched with its field specifier.') publications: typing.List[Publication] = [] for subject_spec, field_spec in (raw_ss[i:i + 2] for i in range(0, len(raw_ss), 2)): publications.append(Publication(subject_spec=subject_spec, field_spec=field_spec, presentation=node.presentation, priority=args.priority, send_timeout=args.period)) _logger.info('Publication set: %r', publications) try: asyncio.get_event_loop().run_until_complete(self._run(node=node, count=int(args.count), period=float(args.period), publications=publications)) except KeyboardInterrupt: pass if _logger.isEnabledFor(logging.INFO): _logger.info('%s', node.presentation.transport.sample_statistics()) for s in node.presentation.transport.output_sessions: ds = s.specifier.data_specifier if isinstance(ds, pyuavcan.transport.MessageDataSpecifier): _logger.info('Subject %d: %s', ds.subject_id, s.sample_statistics()) return 0
Example 29
Project: ironpython2 Author: IronLanguages File: test_argparse.py License: Apache License 2.0 | 5 votes |
def test_conflicting_parents(self): self.assertRaises( argparse.ArgumentError, argparse.ArgumentParser, parents=[self.w_parent, self.wxyz_parent])
Example 30
Project: ironpython2 Author: IronLanguages File: test_argparse.py License: Apache License 2.0 | 5 votes |
def test_conflicting_parents_mutex(self): self.assertRaises( argparse.ArgumentError, argparse.ArgumentParser, parents=[self.abcd_parent, self.ab_mutex_parent])