Search code examples
pythonpython-2.7optparse

How to parse a valid IP4/IPV6 address using optparse in python?


Like I want to parse 127.0.0.1 it can be parsed correctly but 127.0.a.1 is not a valid ip address so it should throw an error. How to do this using optparse in python?

Like to parse a integer or a string value we use

parser.add_option("-n", action="store", type="int", dest="number")

but for parsing a valid ip address what should we write?


Solution

  • I think that using this section of the optparse documentation, this SO answer (which adresses the exact same question with argparse) can be adapted to optparse.

    The idea is basically the following:

    1. Define a function that checks whether or not the input fulfills given condition (the logic is already done in the argparse answer, and the structure is in the optparse documentation I linked)
    2. Define a new option for the type optparse parameter.
    3. Use this user defined type for the IP argument

    Therefore, the code would look like this:

    from copy import copy
    from optparse import OptionParser, Option, OptionValueError 
    import re
    
    # define checker function
    def check_ip(option, opt, value):
        try:
            return re.match(r'(\d{3}(\.\d){3})', value).group(0) # I added some 
            # parethesis to the comment in order to define the IP as group(0)
        except: # I think re.match().group() would raise an AttributeError, check it
            raise OptionValueError(
                "option %s: invalid IP value: %r" % (opt, value))
    
    # define new optparse option
    class MyOption(Option):
        TYPES = Option.TYPES + ("IP",)
        TYPE_CHECKER = copy(Option.TYPE_CHECKER)
        TYPE_CHECKER["IP"] = check_ip
    
    # use optparser with the new option
    parser = OptionParser(option_class=MyOption)
    parser.add_option("-c", type="IP")
    

    Comments

    Check the error you get from the re.match, and write except <error_type>. It is not good practice to catch any exception (see Why is "except: pass" a bad programming practice?).

    Also consider using argparse instead of optparse, both work in python2.7. Why use argparse rather than optparse?