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:
- 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)
- Define a new option for the type optparse parameter.
- 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?