0

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?

OriolAbril
  • 3,515
  • 3
  • 25
  • 35

1 Answers1

0

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?

OriolAbril
  • 3,515
  • 3
  • 25
  • 35
  • Hi Yeah I am getting an error. if I try to pass any IP like 192.168.10.10 or any ip value its showing invalid ip error. Example: python eg1.py -c 12.12.12.12 Usage: eg1.py [options] eg1.py: error: option -c: invalid IP value: '12.12.12.12' What changes should I make in the code? – Debiprasad Das May 13 '18 at 20:52
  • The regex checks for 3 digits, then 3 times the pack (dot followed by digit). What should it accept? just any number of digits with 3 dots in between? – OriolAbril May 13 '18 at 22:23
  • You can also check this question https://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean or this tutorial https://medium.com/factory-mind/regex-tutorial-a-simple-cheatsheet-by-examples-649dc1c3f285 and check if they work for all your cases here https://regex101.com/ regular expressions can be really useful – OriolAbril May 13 '18 at 22:29
  • For example, you may want to try `r'((\d+\.){3}\d+)'`, which matches the pattern: 3 times the pack (digit one or more times followed by dot) and then digit one or more times – OriolAbril May 13 '18 at 22:37
  • Thanks sir yeah it worked perfectly.. I clearly understood about the use of regex for IP. Now I want to try to use argparse instead of optparse for IP address parsing. Can you please any links so that I can try? – Debiprasad Das May 14 '18 at 09:08
  • You can start taking a look at this tutorial https://docs.python.org/2/howto/argparse.html. Then, as you can see in the answer I linked, the type option can accept any user defined function without need to define a custom `MyOption` class – OriolAbril May 14 '18 at 12:12