Python optparse.OptionError() Examples

The following are 27 code examples of optparse.OptionError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module optparse , or try the search function .
Example #1
Source File: __init__.py    From flake8-quotes with MIT License 6 votes vote down vote up
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('-')) 
Example #2
Source File: config.py    From python-netsurv with MIT License 6 votes vote down vote up
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 
Example #3
Source File: cloak.py    From EasY_HaCk with Apache License 2.0 6 votes vote down vote up
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) 
Example #4
Source File: config.py    From python-netsurv with MIT License 6 votes vote down vote up
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 
Example #5
Source File: cloak.py    From POC-EXP with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #6
Source File: magic.py    From metakernel with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #7
Source File: cloak.py    From NoobSec-Toolkit with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #8
Source File: daily_detector.py    From CrisisMappingToolkit with Apache License 2.0 6 votes vote down vote up
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) 
Example #9
Source File: cloak.py    From NoobSec-Toolkit with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #10
Source File: cloak.py    From NoobSec-Toolkit with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #11
Source File: test_options.py    From wharfee with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 
Example #12
Source File: options.py    From linter-pylama with MIT License 5 votes vote down vote up
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('-')) 
Example #13
Source File: options.py    From wharfee with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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') 
Example #14
Source File: safe2bin.py    From EasY_HaCk with Apache License 2.0 5 votes vote down vote up
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) 
Example #15
Source File: safe2bin.py    From POC-EXP with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #16
Source File: detect_flood_cmd.py    From CrisisMappingToolkit with Apache License 2.0 5 votes vote down vote up
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) 
Example #17
Source File: safe2bin.py    From NoobSec-Toolkit with GNU General Public License v2.0 5 votes vote down vote up
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) 
Example #18
Source File: safe2bin.py    From NoobSec-Toolkit with GNU General Public License v2.0 5 votes vote down vote up
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) 
Example #19
Source File: safe2bin.py    From NoobSec-Toolkit with GNU General Public License v2.0 5 votes vote down vote up
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) 
Example #20
Source File: safe2bin.py    From NoobSec-Toolkit with GNU General Public License v2.0 5 votes vote down vote up
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) 
Example #21
Source File: config.py    From python-netsurv with MIT License 5 votes vote down vote up
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 
Example #22
Source File: config.py    From python-netsurv with MIT License 5 votes vote down vote up
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
        ) 
Example #23
Source File: config.py    From python-netsurv with MIT License 5 votes vote down vote up
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 
Example #24
Source File: config.py    From linter-pylama with MIT License 5 votes vote down vote up
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) 
Example #25
Source File: config.py    From linter-pylama with MIT License 5 votes vote down vote up
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 
Example #26
Source File: config.py    From linter-pylama with MIT License 5 votes vote down vote up
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) 
Example #27
Source File: xosVer.py    From learning-python with MIT License 4 votes vote down vote up
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)