本文整理汇总了Python中argparse.ArgumentError方法的典型用法代码示例。如果您正苦于以下问题:Python argparse.ArgumentError方法的具体用法?Python argparse.ArgumentError怎么用?Python argparse.ArgumentError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类argparse
的用法示例。
在下文中一共展示了argparse.ArgumentError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: parse_int
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentError [as 别名]
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
示例2: MakeBasemapDirectory
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentError [as 别名]
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
#=============================================================================
示例3: __call__
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentError [as 别名]
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)
示例4: __call__
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentError [as 别名]
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.
示例5: cli
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentError [as 别名]
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)
示例6: add_kwarg_parse
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentError [as 别名]
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
示例7: test_conflicting_option_should_throw
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentError [as 别名]
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,
)
示例8: __init__
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentError [as 别名]
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)
示例9: __call__
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentError [as 别名]
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)
示例10: _match_argument
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentError [as 别名]
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
示例11: __call__
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentError [as 别名]
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)
示例12: __call__
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentError [as 别名]
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)
示例13: _parse
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentError [as 别名]
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))
示例14: add_model_subargs
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentError [as 别名]
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
示例15: add_image_args
# 需要导入模块: import argparse [as 别名]
# 或者: from argparse import ArgumentError [as 别名]
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