当前位置: 首页>>代码示例>>Python>>正文


Python argparse.ArgumentError方法代码示例

本文整理汇总了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 
开发者ID:google,项目名称:rekall,代码行数:25,代码来源:args.py

示例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
#============================================================================= 
开发者ID:LSDtopotools,项目名称:LSDMappingTools,代码行数:26,代码来源:PlotBasicRasters.py

示例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) 
开发者ID:marcelstoer,项目名称:nodemcu-pyflasher,代码行数:26,代码来源:esptool.py

示例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. 
开发者ID:larsjuhljensen,项目名称:phatsniffer,代码行数:21,代码来源:esptool.py

示例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) 
开发者ID:app-registry,项目名称:appr,代码行数:19,代码来源:cli.py

示例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 
开发者ID:mjendrusch,项目名称:torchsupport,代码行数:18,代码来源:argparse.py

示例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,
        ) 
开发者ID:openstack,项目名称:cliff,代码行数:24,代码来源:test_app.py

示例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) 
开发者ID:QubesOS,项目名称:qubes-core-admin,代码行数:22,代码来源:__init__.py

示例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) 
开发者ID:datamade,项目名称:parserator,代码行数:18,代码来源:main.py

示例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 
开发者ID:TuuuNya,项目名称:WebPocket,代码行数:18,代码来源:argparse_completer.py

示例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) 
开发者ID:nttcom,项目名称:eclcli,代码行数:22,代码来源:parseractions.py

示例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) 
开发者ID:espressif,项目名称:esptool,代码行数:27,代码来源:esptool.py

示例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)) 
开发者ID:RiskSense-Ops,项目名称:CVE-2016-6366,代码行数:19,代码来源:sploit.py

示例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 
开发者ID:facebookresearch,项目名称:ParlAI,代码行数:20,代码来源:params.py

示例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 
开发者ID:facebookresearch,项目名称:ParlAI,代码行数:25,代码来源:params.py


注:本文中的argparse.ArgumentError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。