當前位置: 首頁>>代碼示例>>Python>>正文


Python optparse.OptionError方法代碼示例

本文整理匯總了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 
開發者ID:sofia-netsurv,項目名稱:python-netsurv,代碼行數:20,代碼來源:config.py

示例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) 
開發者ID:krintoxi,項目名稱:NoobSec-Toolkit,代碼行數:18,代碼來源:cloak.py

示例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) 
開發者ID:nasa,項目名稱:CrisisMappingToolkit,代碼行數:22,代碼來源:daily_detector.py

示例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 
開發者ID:Calysto,項目名稱:metakernel,代碼行數:24,代碼來源:magic.py

示例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('-')) 
開發者ID:zheller,項目名稱:flake8-quotes,代碼行數:21,代碼來源:__init__.py

示例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('-')) 
開發者ID:AtomLinter,項目名稱:linter-pylama,代碼行數:36,代碼來源:options.py

示例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) 
開發者ID:AtomLinter,項目名稱:linter-pylama,代碼行數:14,代碼來源:config.py

示例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 
開發者ID:AtomLinter,項目名稱:linter-pylama,代碼行數:14,代碼來源:config.py

示例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) 
開發者ID:AtomLinter,項目名稱:linter-pylama,代碼行數:10,代碼來源:config.py

示例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
        ) 
開發者ID:sofia-netsurv,項目名稱:python-netsurv,代碼行數:11,代碼來源:config.py

示例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) 
開發者ID:krintoxi,項目名稱:NoobSec-Toolkit,代碼行數:17,代碼來源:safe2bin.py

示例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) 
開發者ID:nasa,項目名稱:CrisisMappingToolkit,代碼行數:35,代碼來源:detect_flood_cmd.py

示例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') 
開發者ID:j-bennet,項目名稱:wharfee,代碼行數:15,代碼來源:options.py

示例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 
開發者ID:j-bennet,項目名稱:wharfee,代碼行數:15,代碼來源:test_options.py

示例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) 
開發者ID:Akagi201,項目名稱:learning-python,代碼行數:59,代碼來源:xosVer.py


注:本文中的optparse.OptionError方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。