python类ArgumentError()的实例源码

sploit.py 文件源码 项目:CVE-2016-6366 作者: RiskSense-Ops 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def parse_error(msg):
        '''

        '''
        raise argparse.ArgumentError(None, msg)
runner.py 文件源码 项目:SlackJira 作者: Rastii 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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)
cli.py 文件源码 项目:TCP-IP 作者: JackZ0 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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)
cli.py 文件源码 项目:TCP-IP 作者: JackZ0 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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
cli.py 文件源码 项目:TCP-IP 作者: JackZ0 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
cli_test.py 文件源码 项目:TCP-IP 作者: JackZ0 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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)
standalone.py 文件源码 项目:TCP-IP 作者: JackZ0 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
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
esptool.py 文件源码 项目:nodemcu-pyflasher 作者: marcelstoer 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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)
cmdline.py 文件源码 项目:seproxer 作者: Rastii 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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)
cmdline.py 文件源码 项目:seproxer 作者: Rastii 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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)
cmdline.py 文件源码 项目:seproxer 作者: Rastii 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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)
input.py 文件源码 项目:flasky 作者: RoseOu 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
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
recommender_wide_and_deep.py 文件源码 项目:tflearn 作者: tflearn 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
__main__.py 文件源码 项目:r360-py 作者: route360 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
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(';')]
base_config.py 文件源码 项目:relaax 作者: deeplearninc 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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.')
ksparser.py 文件源码 项目:isar 作者: ilbers 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def error(self, message):
        raise ArgumentError(None, message)
test_argparse.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def test_conflicting_parents(self):
        self.assertRaises(
            argparse.ArgumentError,
            argparse.ArgumentParser,
            parents=[self.w_parent, self.wxyz_parent])
test_argparse.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def test_conflicting_parents_mutex(self):
        self.assertRaises(
            argparse.ArgumentError,
            argparse.ArgumentParser,
            parents=[self.abcd_parent, self.ab_mutex_parent])
test_argparse.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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')
test_argparse.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def test_test_argparse_module_encoding(self):
        self._test_module_encoding(__file__)

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


问题


面经


文章

微信
公众号

扫码关注公众号