本文整理汇总了Python中optparse.OptionError方法的典型用法代码示例。如果您正苦于以下问题:Python optparse.OptionError方法的具体用法?Python optparse.OptionError怎么用?Python optparse.OptionError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类optparse
的用法示例。
在下文中一共展示了optparse.OptionError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _check_choice
# 需要导入模块: import optparse [as 别名]
# 或者: from optparse import OptionError [as 别名]
def _check_choice(self):
if self.type in ("choice", "multiple_choice"):
if self.choices is None:
raise optparse.OptionError(
"must supply a list of choices for type 'choice'", self
)
if not isinstance(self.choices, (tuple, list)):
raise optparse.OptionError(
"choices must be a list of strings ('%s' supplied)"
% str(type(self.choices)).split("'")[1],
self,
)
elif self.choices is not None:
raise optparse.OptionError(
"must not supply choices for type %r" % self.type, self
)
# pylint: disable=unsupported-assignment-operation
示例2: main
# 需要导入模块: import optparse [as 别名]
# 或者: from optparse import OptionError [as 别名]
def main():
usage = '%s [-d] -i <input file> [-o <output file>]' % sys.argv[0]
parser = OptionParser(usage=usage, version='0.1')
try:
parser.add_option('-d', dest='decrypt', action="store_true", help='Decrypt')
parser.add_option('-i', dest='inputFile', help='Input file')
parser.add_option('-o', dest='outputFile', help='Output file')
(args, _) = parser.parse_args()
if not args.inputFile:
parser.error('Missing the input file, -h for help')
except (OptionError, TypeError), e:
parser.error(e)
示例3: main
# 需要导入模块: import optparse [as 别名]
# 或者: from optparse import OptionError [as 别名]
def main(argsIn):
#logger = logging.getLogger() TODO: Switch to using a logger!
try:
usage = "usage: daily_detector.py [--help]\n "
parser = optparse.OptionParser(usage=usage)
parser.add_option("--archive-results", dest="archiveResults", action="store_true", default=False,
help="Archive results so they can be found by the web API.")
parser.add_option("--manual", dest="showManual", action="store_true", default=False,
help="Display more usage information about the tool.")
(options, args) = parser.parse_args(argsIn)
if options.showManual:
print manual
return 0
except optparse.OptionError, msg:
raise Usage(msg)
示例4: option
# 需要导入模块: import optparse [as 别名]
# 或者: from optparse import OptionError [as 别名]
def option(*args, **kwargs):
"""Return decorator that adds a magic option to a function.
"""
def decorator(func):
help_text = ""
if not getattr(func, 'has_options', False):
func.has_options = True
func.options = []
help_text += 'Options:\n-------\n'
try:
option = optparse.Option(*args, **kwargs)
except optparse.OptionError:
help_text += args[0] + "\n"
else:
help_text += _format_option(option) + "\n"
func.options.append(option)
if func.__doc__:
func.__doc__ += _indent(func.__doc__, help_text)
else:
func.__doc__ = help_text
return func
return decorator
示例5: _register_opt
# 需要导入模块: import optparse [as 别名]
# 或者: from optparse import OptionError [as 别名]
def _register_opt(parser, *args, **kwargs):
"""
Handler to register an option for both Flake8 3.x and 2.x.
This is based on:
https://github.com/PyCQA/flake8/blob/3.0.0b2/docs/source/plugin-development/cross-compatibility.rst#option-handling-on-flake8-2-and-3
It only supports `parse_from_config` from the original function and it
uses the `Option` object returned to get the string.
"""
try:
# Flake8 3.x registration
parser.add_option(*args, **kwargs)
except (optparse.OptionError, TypeError):
# Flake8 2.x registration
parse_from_config = kwargs.pop('parse_from_config', False)
option = parser.add_option(*args, **kwargs)
if parse_from_config:
parser.config_options.append(option.get_opt_string().lstrip('-'))
示例6: register
# 需要导入模块: import optparse [as 别名]
# 或者: from optparse import OptionError [as 别名]
def register(parser, *args, **kwargs):
r"""Register an option for the Option Parser provided by Flake8.
:param parser:
The option parser being used by Flake8 to handle command-line options.
:param \*args:
Positional arguments that you might otherwise pass to ``add_option``.
:param \*\*kwargs:
Keyword arguments you might otherwise pass to ``add_option``.
"""
try:
# Flake8 3.x registration
parser.add_option(*args, **kwargs)
except (optparse.OptionError, TypeError):
# Flake8 2.x registration
# Pop Flake8 3 parameters out of the kwargs so they don't cause a
# conflict.
parse_from_config = kwargs.pop('parse_from_config', False)
comma_separated_list = kwargs.pop('comma_separated_list', False)
normalize_paths = kwargs.pop('normalize_paths', False)
# In the unlikely event that the developer has specified their own
# callback, let's pop that and deal with that as well.
base_callback = kwargs.pop('callback', store_callback)
callback = generate_callback_from(comma_separated_list,
normalize_paths,
base_callback)
kwargs['callback'] = callback
kwargs['action'] = 'callback'
# We've updated our args and kwargs and can now rather confidently
# call add_option.
option = parser.add_option(*args, **kwargs)
if parse_from_config:
parser.config_options.append(option.get_opt_string().lstrip('-'))
示例7: _check_choice
# 需要导入模块: import optparse [as 别名]
# 或者: from optparse import OptionError [as 别名]
def _check_choice(self):
if self.type in ("choice", "multiple_choice"):
if self.choices is None:
raise optparse.OptionError(
"must supply a list of choices for type 'choice'", self)
elif not isinstance(self.choices, (tuple, list)):
raise optparse.OptionError(
"choices must be a list of strings ('%s' supplied)"
% str(type(self.choices)).split("'")[1], self)
elif self.choices is not None:
raise optparse.OptionError(
"must not supply choices for type %r" % self.type, self)
示例8: load_config_file
# 需要导入模块: import optparse [as 别名]
# 或者: from optparse import OptionError [as 别名]
def load_config_file(self):
"""dispatch values previously read from a configuration file to each
options provider)
"""
parser = self.cfgfile_parser
for section in parser.sections():
for option, value in parser.items(section):
try:
self.global_set_option(option, value)
except (KeyError, optparse.OptionError):
# TODO handle here undeclared options appearing in the config file
continue
示例9: get_option_def
# 需要导入模块: import optparse [as 别名]
# 或者: from optparse import OptionError [as 别名]
def get_option_def(self, opt):
"""return the dictionary defining an option given its name"""
assert self.options
for option in self.options:
if option[0] == opt:
return option[1]
raise optparse.OptionError('no such option %s in section %r'
% (opt, self.name), opt)
示例10: get_option_def
# 需要导入模块: import optparse [as 别名]
# 或者: from optparse import OptionError [as 别名]
def get_option_def(self, opt):
"""return the dictionary defining an option given its name"""
assert self.options
for option in self.options:
if option[0] == opt:
return option[1]
raise optparse.OptionError(
"no such option %s in section %r" % (opt, self.name), opt
)
示例11: main
# 需要导入模块: import optparse [as 别名]
# 或者: from optparse import OptionError [as 别名]
def main():
usage = '%s -i <input file> [-o <output file>]' % sys.argv[0]
parser = OptionParser(usage=usage, version='0.1')
try:
parser.add_option('-i', dest='inputFile', help='Input file')
parser.add_option('-o', dest='outputFile', help='Output file')
(args, _) = parser.parse_args()
if not args.inputFile:
parser.error('Missing the input file, -h for help')
except (OptionError, TypeError), e:
parser.error(e)
示例12: main
# 需要导入模块: import optparse [as 别名]
# 或者: from optparse import OptionError [as 别名]
def main(argsIn):
#logger = logging.getLogger() TODO: Switch to using a logger!
# Be careful passing in negative number arguments!
try:
usage = "usage: detect_flood_cmd.py <output_folder> <date: YYYY-MM-DD> <minLon> <minLat> <maxLon> <maxLat> [--help]\n "
parser = optparse.OptionParser(usage=usage)
parser.add_option("--save-inputs", dest="saveInputs", action="store_true", default=False,
help="Save the input images to disk for debugging.")
parser.add_option("--search-days", dest="searchRangeDays", default=5, type="int",
help="The number of days around the requested date so search for input images.")
parser.add_option("--max-cloud-percentage", dest="maxCloudPercentage", default=0.05, type="float",
help="Only allow images with this percentage of cloud cover.")
parser.add_option("--min-sensor-coverage", dest="minCoverage", default=0.80, type="float",
help="Only use sensor images that cover this percentage of the target region.")
parser.add_option("--manual", dest="showManual", action="store_true", default=False,
help="Display more usage information about the tool.")
(options, args) = parser.parse_args(argsIn)
if options.showManual:
print manual
return 0
if len(args) < 5:
print usage
raise Exception('Not enough arguments provided!')
except optparse.OptionError, msg:
raise Usage(msg)
示例13: assert_option_format
# 需要导入模块: import optparse [as 别名]
# 或者: from optparse import OptionError [as 别名]
def assert_option_format(self):
"""
I don't want environment vars to be provided as
"-e KEY VALUE", I want "-e KEY=VALUE" instead.
Would argparse help here?
"""
dict_values = vars(self.values)
if 'environment' in dict_values and dict_values['environment']:
for envar in dict_values['environment']:
if '=' not in envar:
raise OptionError(
'Usage: -e KEY1=VALUE1 -e KEY2=VALUE2...',
'-e')
示例14: test_parse_multiple_args_without_equal
# 需要导入模块: import optparse [as 别名]
# 或者: from optparse import OptionError [as 别名]
def test_parse_multiple_args_without_equal():
"""
Parsing multiple -e options to "run".
:return:
"""
text = 'run --name boo -e FOO 1 -e BOO 2 ubuntu'
tokens = shlex_split(text) if text else ['']
cmd = tokens[0]
params = tokens[1:]
with pytest.raises(OptionError) as ex:
parse_command_options(cmd, params)
assert 'KEY=VALUE' in ex.message
示例15: main
# 需要导入模块: import optparse [as 别名]
# 或者: from optparse import OptionError [as 别名]
def main():
print (r" ")
print (r" \ \ / / ")
print (r"__ _____ __\ \ / /__ _ __ ")
print (r"\ \/ / _ \/ __\ \/ / _ \ '__|")
print (r" > < (_) \__ \\ / __/ | ")
print (r"/_/\_\___/|___/ \/ \___|_| ")
print (r" ")
IS_WIN = subprocess.mswindows
_ = os.path.normpath(sys.argv[0])
usage = "%s%s <options>" % ("python" if not IS_WIN else "", \
"\"%s\"" % _ if " " in _ else _)
print ("Version: {0}".format(__version__))
parser = OptionParser(usage=usage)
try:
parser.add_option("--hh", dest="help",
action="store_true",
help="Show help message and exit")
parser.add_option("-i", dest="ip",
help="Single IP scan mode (eg:192.168.1.11)")
parser.add_option("-p", dest="ips",
help="Batch IP scan mode (eg:192.168.1.10/20)")
parser.add_option("-o", dest="output",
help="Save results to a file",
default = False)
parser.add_option("--timeout", dest="timeout", type="int",
help="Seconds to wait before timeout connection "
"(default 2)", default = 2)
args = []
for arg in sys.argv:
args.append(arg)
(args, _) = parser.parse_args(args)
if not any((args.ip, args.ips)):
errMsg = "use -h for help"
parser.error(errMsg)
for i in xrange(len(sys.argv)):
try:
if sys.argv[i] == '-i':
reip = re.compile(r'(?<![\.\d])(?:\d{1,3}\.){3}\d{1,3}(?![\.\d])')
for ip in reip.findall(args.ip):ip
xosVer(ip, args.timeout, args.output)
elif sys.argv[i] == '-p':
reip = re.compile(r'(?<![\.\d])(?:\d{1,3}\.){3}\d{1,3}(?![\.\d])/\d{1,3}')
for ip in reip.findall(args.ips):ip
ip = ip.split('/')
exIp = ip[0][:ip[0].rfind('.') + 1]
sIp = int(ip[0][ip[0].rfind('.') + 1:], 10)
eIp = int(ip[1], 10) + 1
for i in xrange(sIp, eIp):
xosVer(exIp + str(i), args.timeout, args.output)
except Exception, e:
print ("\r\noption %s invalid value: %s" % (sys.argv[i], sys.argv[i + 1]))
print ("\r\nuse -h for help")
except (OptionError,TypeError), e:
parser.error(e)