def parse_error(msg):
'''
'''
raise argparse.ArgumentError(None, msg)
python类ArgumentError()的实例源码
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)
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)
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
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
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)
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
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)
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)
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)
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)
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
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
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(';')]
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.')
def error(self, message):
raise ArgumentError(None, message)
def test_conflicting_parents(self):
self.assertRaises(
argparse.ArgumentError,
argparse.ArgumentParser,
parents=[self.w_parent, self.wxyz_parent])
def test_conflicting_parents_mutex(self):
self.assertRaises(
argparse.ArgumentError,
argparse.ArgumentParser,
parents=[self.abcd_parent, self.ab_mutex_parent])
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')
def test_test_argparse_module_encoding(self):
self._test_module_encoding(__file__)
# ===================
# ArgumentError tests
# ===================