Python argparse 模块,ArgumentError() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用argparse.ArgumentError()

项目:iot    作者:akademikbilisim    | 项目源码 | 文件源码
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',
                '32m-c2': '4MB-c2'
            }[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)
项目:iot    作者:akademikbilisim    | 项目源码 | 文件源码
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)


# Binary stub code (see flasher_stub dir for source & details)
项目:phatsniffer    作者:larsjuhljensen    | 项目源码 | 文件源码
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.
项目:CVE-2016-6366    作者:RiskSense-Ops    | 项目源码 | 文件源码
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))
项目:nodemcu-pyflasher    作者:marcelstoer    | 项目源码 | 文件源码
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)
项目:nodemcu-pyflasher    作者:marcelstoer    | 项目源码 | 文件源码
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)
项目:Skynet2.0    作者:Skynet2-0    | 项目源码 | 文件源码
def main(argv):
    parser = argparse.ArgumentParser(description='Prototype 2 of the Autonomous self-replicating code.')
    try:
        parser.add_argument('-t', '--usetestserver', help='circumvent dna and use testserver defined in settings.json')
        parser.add_argument('-x', '--exitnode', help='Enable the agents\' Tribler Exit Node functionality')

        parser.add_help = True
        args = parser.parse_args(argv)

    except argparse.ArgumentError:
        parser.print_help()
        sys.exit(2)

    #return whether -as boolean- the set value, return default if not set
    #defaults are development mode equivalent
    usetestserver = False if args.usetestserver in ['False', 'false'] else True
    exitnode = True if args.exitnode in ['True', 'true'] else False

    Prototype2(exitnode, usetestserver)
项目:osc-lib    作者:openstack    | 项目源码 | 文件源码
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, %(min)s is not less than %(max)s")
                raise argparse.ArgumentError(self, msg % {
                    'min': range[0],
                    'max': range[1],
                })
        else:
            # Too many values
            msg = _("Invalid range, too many values")
            raise argparse.ArgumentError(self, msg)
项目:AshsSDK    作者:thehappydinoa    | 项目源码 | 文件源码
def _check_value(self, action, value):
        """
        It's probably not a great idea to override a "hidden" method
        but the default behavior is pretty ugly and there doesn't
        seem to be any other way to change it.
        """
        # converted value must be one of the choices (if specified)
        if action.choices is not None and value not in action.choices:
            msg = ['Invalid choice, valid choices are:\n']
            for i in range(len(action.choices))[::self.ChoicesPerLine]:
                current = []
                for choice in action.choices[i:i+self.ChoicesPerLine]:
                    current.append('%-40s' % choice)
                msg.append(' | '.join(current))
            possible = get_close_matches(value, action.choices, cutoff=0.8)
            if possible:
                extra = ['\n\nInvalid choice: %r, maybe you meant:\n' % value]
                for word in possible:
                    extra.append('  * %s' % word)
                msg.extend(extra)
            raise argparse.ArgumentError(action, '\n'.join(msg))
项目:nbhosting    作者:parmentelat    | 项目源码 | 文件源码
def __call__(self, parser, namespace, value, option_string=None):
        pieces = value.split('-')
        if not (0 < len(pieces) <= 3):
            raise argparse.ArgumentError("wrong syntax in IntsRange with {}"
                                         .format(value))
        try:
            if len(pieces) == 1:
                self.result.append(int(pieces[0]))
            elif len(pieces) == 2:
                a, b = (int(x) for x in pieces)
                self.result += list(range(a, b+1))
            else:
                a, b, c = (int(x) for x in pieces)
                self.result += list(range(a, b+1, c))
            self.result = sorted(set(self.result))
        except ValueError as e:
            raise argparse.ArgumentTypeError(value, "IntsRange requires integers")
        setattr(namespace, self.dest, self.result)

#################### unit test
项目:codal    作者:lancaster-university    | 项目源码 | 文件源码
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.
项目:AnalyticContainer    作者:DataKitchen    | 项目源码 | 文件源码
def parse_command_line(self, parser):
        try:
            if parser is not None:
                mutually_exclusive_group = parser.add_mutually_exclusive_group()
                mutually_exclusive_group.add_argument('--rude', '-rude', action='store_true', default=False, dest='rude',
                                                      help='Return something rude')
                results = parser.parse_args()
                if results.rude is True:
                    ACLogger.log_and_print("ACBase ... print rude words")
        except argparse.ArgumentError as e:
            s = 'ACBase:  During processing, caught an unknown exception. type: %s ; args: %s ; message: %s' % (
            type(e), repr(e.args), e.message)
            ACLogger.log_and_print_error(s)
            self.set_container_status(CONTAINER_STATUS_ERROR)
            return False
        except Exception as e:
            s = 'ACBase:  During processing, caught an unknown exception:  %s %s' % (type(e), e.args)
            ACLogger.log_and_print_error(s)
            self.set_container_status(CONTAINER_STATUS_ERROR)
            return False

        return True
项目:atropos    作者:jdidion    | 项目源码 | 文件源码
def _do_call(
            self, string, delim=",", data_type=None, choices=None,
            min_len=None, max_len=None):
        if isinstance(string, str):
            vals = string.split(delim) if delim else (string,)
        else:
            vals = string

        if vals[0] == "*" and choices is not None:
            vals = choices

        if data_type:
            vals = [data_type(v) for v in vals]

        if min_len and len(vals) < min_len:
            raise ArgumentError(
                self, "there must be at least {} values".format(min_len))

        if max_len and len(vals) > max_len:
            raise ArgumentError(
                self, "there can be at most {} values".format(max_len))

        return vals
项目:iot    作者:karakaplanm    | 项目源码 | 文件源码
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',
                '32m-c2': '4MB-c2'
            }[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)
项目:iot    作者:karakaplanm    | 项目源码 | 文件源码
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)


# Binary stub code (see flasher_stub dir for source & details)
项目:eclcli    作者:nttcom    | 项目源码 | 文件源码
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)
项目:azure-cli    作者:Azure    | 项目源码 | 文件源码
def validate_cert(namespace):
    params = [namespace.cert_data, namespace.cert_password]
    if all([not x for x in params]):
        # no cert supplied -- use HTTP
        if not namespace.frontend_port:
            namespace.frontend_port = 80
    else:
        # cert supplied -- use HTTPS
        if not all(params):
            raise argparse.ArgumentError(
                None, 'To use SSL certificate, you must specify both the filename and password')

        # extract the certificate data from the provided file
        namespace.cert_data = read_base_64_file(namespace.cert_data)

        try:
            # change default to frontend port 443 for https
            if not namespace.frontend_port:
                namespace.frontend_port = 443
        except AttributeError:
            # app-gateway ssl-cert create does not have these fields and that is okay
            pass
项目:bootloader_instrumentation_suite    作者:bx    | 项目源码 | 文件源码
def __call__(self, parser, namespace, values, option_string=None):
            stagename = values[0]
            f = os.path.abspath(values[1])
            d = os.path.abspath(values[2])
            if stagename not in self.stagenames:
                raise argparse.ArgumentError(self,
                                             "%s not a valid stage, must be one of %s" %
                                             (stagename, str(self.stagenames)))
            if self.dest == 'importpolicy':
                setattr(namespace, "doimport", True)
            for s in self.stagenames:
                if s == stagename:
                    getattr(namespace, self.dest)[s] = (f, d)
                else:
                    if s not in getattr(namespace, self.dest).iterkeys():
                        getattr(namespace, self.dest)[s] = self.sdefaults[s]
项目:qubes-core-admin-client    作者:QubesOS    | 项目源码 | 文件源码
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)
项目:qubes-core-admin-client    作者:QubesOS    | 项目源码 | 文件源码
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)
项目:johnny-five-esp8266    作者:anaganisk    | 项目源码 | 文件源码
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.
项目:rvmi-rekall    作者:fireeye    | 项目源码 | 文件源码
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
项目:lambda-podcast    作者:marekq    | 项目源码 | 文件源码
def __call__(self, parser, namespace, values, option_string=None):

        values = values.split(':')
        level, logger = values if len(values) > 1 else (values[0],
                                                        self.main_logger)

        logger = logging.getLogger(logger)
        try:
            logger.setLevel(logging._levelNames[level.upper()])
        except KeyError:
            msg = "invalid level choice: %s (choose from %s)" % \
                   (level, parser.log_levels)
            raise argparse.ArgumentError(self, msg)

        super(LoggingAction, self).__call__(parser, namespace, values,
                                            option_string)
项目:cotcha    作者:hevnsnt    | 项目源码 | 文件源码
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)
项目:cotcha    作者:hevnsnt    | 项目源码 | 文件源码
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).' % values)
        setattr(namespace, self.dest, value)
项目:appr    作者:app-registry    | 项目源码 | 文件源码
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)
项目:privcount    作者:privcount    | 项目源码 | 文件源码
def __call__(self, parser, namespace, values, option_string=None):
        # extract the path to our data, and the label for the legend
        datapath = os.path.abspath(os.path.expanduser(values[0]))
        label = values[1]
        # check the path exists
        if not os.path.exists(datapath): raise argparse.ArgumentError(self, "The supplied path to the plot data does not exist: '{0}'".format(datapath))
        # remove the default
        if "_didremovedefault" not in namespace:
            setattr(namespace, self.dest, [])
            setattr(namespace, "_didremovedefault", True)
        # append out new experiment path
        dest = getattr(namespace, self.dest)
        dest.append((datapath, label))
项目:pydrm    作者:notro    | 项目源码 | 文件源码
def __call__(self, parser, namespace, values, option_string=None):
        if not hasattr(namespace, 'props'):
            namespace.props = []

        try:
            obj_id, prop_name, value = values.split(':')
        except:
            raise argparse.ArgumentError(self, "could not parse '%s'" % values)

        try:
            obj_id = int(obj_id)
        except ValueError:
            raise argparse.ArgumentError(self, "obj_id=%s is not an int" % obj_id)

        namespace.props.append([obj_id, prop_name, value])
项目:ParlAI    作者:facebookresearch    | 项目源码 | 文件源码
def add_cmdline_args(argparser):
        RemoteAgentAgent.add_cmdline_args(argparser)
        try:
            ParsedRemoteAgent.dictionary_class().add_cmdline_args(argparser)
        except argparse.ArgumentError:
            # don't freak out if the dictionary has already been added
            pass
项目:eyeD3    作者:nicfit    | 项目源码 | 文件源码
def __call__(self, parser, namespace, values, option_string=None):
        values = values.split(':')
        level, logger = values if len(values) > 1 else (values[0],
                                                        self.main_logger)

        logger = logging.getLogger(logger)
        try:
            logger.setLevel(logging._nameToLevel[level.upper()])
        except KeyError:
            msg = "invalid level choice: %s (choose from %s)" % \
                   (level, parser.log_levels)
            raise argparse.ArgumentError(self, msg)

        super(LoggingAction, self).__call__(parser, namespace, values,
                                            option_string)
项目:CVE-2016-6366    作者:RiskSense-Ops    | 项目源码 | 文件源码
def parse_error(msg):
        '''

        '''
        raise argparse.ArgumentError(None, msg)
项目:SlackJira    作者:Rastii    | 项目源码 | 文件源码
def __call__(self, parser, namespace, values, option_string=None):
        file_location = values if values else self.default

        config = ConfigParser.ConfigParser()
        try:
            with open(file_location) as fp:
                config.readfp(fp)
        except (IOError, ConfigParser.Error) as e:
            raise argparse.ArgumentError(self, "Unable to read URL file: {}".format(e))

        setattr(namespace, self.dest, config)
项目:TCP-IP    作者:JackZ0    | 项目源码 | 文件源码
def __call__(self, parser, namespace, pref_challs, option_string=None):
        try:
            challs = parse_preferred_challenges(pref_challs.split(","))
        except errors.Error as error:
            raise argparse.ArgumentError(self, str(error))
        namespace.pref_challs.extend(challs)
项目:TCP-IP    作者:JackZ0    | 项目源码 | 文件源码
def __call__(self, parser, namespace, values, option_string=None):
        renew_hook_set = namespace.deploy_hook != namespace.renew_hook
        if renew_hook_set and namespace.renew_hook != values:
            raise argparse.ArgumentError(
                self, "conflicts with --renew-hook value")
        namespace.deploy_hook = namespace.renew_hook = values
项目:TCP-IP    作者:JackZ0    | 项目源码 | 文件源码
def __call__(self, parser, namespace, values, option_string=None):
        deploy_hook_set = namespace.deploy_hook is not None
        if deploy_hook_set and namespace.deploy_hook != values:
            raise argparse.ArgumentError(
                self, "conflicts with --deploy-hook value")
        namespace.renew_hook = values
项目:TCP-IP    作者:JackZ0    | 项目源码 | 文件源码
def test_preferred_challenges(self):
        short_args = ['--preferred-challenges', 'http, tls-sni-01, dns']
        namespace = self.parse(short_args)

        expected = [challenges.HTTP01.typ,
                    challenges.TLSSNI01.typ, challenges.DNS01.typ]
        self.assertEqual(namespace.pref_challs, expected)

        short_args = ['--preferred-challenges', 'jumping-over-the-moon']
        # argparse.ArgumentError makes argparse print more information
        # to stderr and call sys.exit()
        with mock.patch('sys.stderr'):
            self.assertRaises(SystemExit, self.parse, short_args)
项目:TCP-IP    作者:JackZ0    | 项目源码 | 文件源码
def _convert_and_validate(self, data):
        """Validate the value of supported challenges provided by the user.

        References to "dvsni" are automatically converted to "tls-sni-01".

        :param str data: comma delimited list of challenge types

        :returns: validated and converted list of challenge types
        :rtype: str

        """
        challs = data.split(",")

        # tls-sni-01 was dvsni during private beta
        if "dvsni" in challs:
            logger.info(
                "Updating legacy standalone_supported_challenges value")
            challs = [challenges.TLSSNI01.typ if chall == "dvsni" else chall
                      for chall in challs]
            data = ",".join(challs)

        unrecognized = [name for name in challs
                        if name not in challenges.Challenge.TYPES]

        # argparse.ArgumentErrors raised out of argparse.Action objects
        # are caught by argparse which prints usage information and the
        # error that occurred before calling sys.exit.
        if unrecognized:
            raise argparse.ArgumentError(
                self,
                "Unrecognized challenges: {0}".format(", ".join(unrecognized)))

        choices = set(chall.typ for chall in SUPPORTED_CHALLENGES)
        if not set(challs).issubset(choices):
            raise argparse.ArgumentError(
                self,
                "Plugin does not support the following (valid) "
                "challenges: {0}".format(", ".join(set(challs) - choices)))

        return data
项目:nodemcu-pyflasher    作者:marcelstoer    | 项目源码 | 文件源码
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))

        # 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)
项目:seproxer    作者:Rastii    | 项目源码 | 文件源码
def __call__(self, parser, namespace, values, option_string=None):
        _ = parser, option_string  # NOQA

        try:
            result = self._enum_type[values]
        except KeyError:
            raise argparse.ArgumentError(
                self, "{} not a valid choice of {}".format(values, self.choices))

        setattr(namespace, self.dest, result)
项目:seproxer    作者:Rastii    | 项目源码 | 文件源码
def __call__(self, parser, namespace, values, option_string=None):
        try:
            with open(values) as fp:
                urls = [url.strip() for url in fp.readlines() if url]
        except IOError as e:
            raise argparse.ArgumentError(self, "Unable to read URL file: {}".format(e))

        setattr(namespace, self.dest, urls)
项目:seproxer    作者:Rastii    | 项目源码 | 文件源码
def get_parsed_args(args=None):
    parser = argparse.ArgumentParser(
        usage="""
        %(prog)s [options] URL_FILE

        Example with cookie injection
        -----------------------------
        %(prog)s --set-headers ":~q ~d example.com:Cookie:Nomz" \\
                  --strip-headers ":~d example.com:Cookie" \\
                  test_urls.txt

            Injects the Cookie=Nomz HEADER into all example.com DOMAIN REQUESTS
            (note that ~q matches requests that don't have a response yet and ~d matches domain)
            Please refer to the mitmproxy docs for filter expressions:
            http://docs.mitmproxy.org/en/stable/features/filters.html

            Additionally, this example will strip the Cookie header in the saved flows.
        """.strip()
    )
    parser.add_argument(
        "test_urls",
        metavar="URL_FILE",
        type=str,
        action=UrlFile,
        help="Specify a file that contains URLs separated by newlines"
    )

    add_selenium_options(parser)
    add_proxy_options(parser)
    add_state_options(parser)
    add_validator_options(parser)
    add_storage_options(parser)

    try:
        return parser.parse_args(args=args)
    except argparse.ArgumentError as e:
        raise CmdlineError(e)
项目:flasky    作者:RoseOu    | 项目源码 | 文件源码
def __call__(self, value):
        # Session name can be a path or just a name.
        if (os.path.sep not in value
                and not VALID_SESSION_NAME_PATTERN.search(value)):
            raise ArgumentError(None, self.error_message)
        return value
项目:tflearn    作者:tflearn    | 项目源码 | 文件源码
def CommandLine(args=None):
    '''
    Main command line.  Accepts args, to allow for simple unit testing.
    '''
    flags = tf.app.flags
    FLAGS = flags.FLAGS
    if args:
        FLAGS.__init__()
        FLAGS.__dict__.update(args)

    try:
        flags.DEFINE_string("model_type", "wide+deep","Valid model types: {'wide', 'deep', 'wide+deep'}.")
        flags.DEFINE_string("run_name", None, "name for this run (defaults to model type)")
        flags.DEFINE_string("load_weights", None, "filename with initial weights to load")
        flags.DEFINE_string("checkpoints_dir", None, "name of directory where checkpoints should be saved")
        flags.DEFINE_integer("n_epoch", 200, "Number of training epoch steps")
        flags.DEFINE_integer("snapshot_step", 100, "Step number when snapshot (and validation testing) is done")
        flags.DEFINE_float("wide_learning_rate", 0.001, "learning rate for the wide part of the model")
        flags.DEFINE_float("deep_learning_rate", 0.001, "learning rate for the deep part of the model")
        flags.DEFINE_boolean("verbose", False, "Verbose output")
    except argparse.ArgumentError:
        pass    # so that CommandLine can be run more than once, for testing

    twad = TFLearnWideAndDeep(model_type=FLAGS.model_type, verbose=FLAGS.verbose, 
                              name=FLAGS.run_name, wide_learning_rate=FLAGS.wide_learning_rate,
                              deep_learning_rate=FLAGS.deep_learning_rate,
                              checkpoints_dir=FLAGS.checkpoints_dir)
    twad.load_data()
    if FLAGS.load_weights:
        print ("Loading initial weights from %s" % FLAGS.load_weights)
        twad.model.load(FLAGS.load_weights)
    twad.train(n_epoch=FLAGS.n_epoch, snapshot_step=FLAGS.snapshot_step)
    twad.evaluate()
    return twad

#-----------------------------------------------------------------------------
# unit tests
项目:r360-py    作者:route360    | 项目源码 | 文件源码
def source(arg):
    # For simplity, assume arg is a pair of integers
    # separated by a comma. If you want to do more
    # validation, raise argparse.ArgumentError if you
    # encounter a problem.
    return [float(x) for x in arg.split(';')]
项目:relaax    作者:deeplearninc    | 项目源码 | 文件源码
def str2bool(v):
        if v.lower() in ('yes', 'true', 't', 'y', '1'):
            return True
        if v.lower() in ('no', 'false', 'f', 'n', '0'):
            return False
        else:
            raise argparse.ArgumentError('Boolean value expected.')
项目:isar    作者:ilbers    | 项目源码 | 文件源码
def error(self, message):
        raise ArgumentError(None, message)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_conflicting_parents(self):
        self.assertRaises(
            argparse.ArgumentError,
            argparse.ArgumentParser,
            parents=[self.w_parent, self.wxyz_parent])
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_conflicting_parents_mutex(self):
        self.assertRaises(
            argparse.ArgumentError,
            argparse.ArgumentParser,
            parents=[self.abcd_parent, self.ab_mutex_parent])
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_conflict_error(self):
        parser = argparse.ArgumentParser()
        parser.add_argument('-x')
        self.assertRaises(argparse.ArgumentError,
                          parser.add_argument, '-x')
        parser.add_argument('--spam')
        self.assertRaises(argparse.ArgumentError,
                          parser.add_argument, '--spam')
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_test_argparse_module_encoding(self):
        self._test_module_encoding(__file__)

# ===================
# ArgumentError tests
# ===================