| re: How to handle wrong input in getopt package in Python?
Danielgetopt.GetoptError: option --imageDir requires argument
Which is precisely what the getopt module should do.
DanielIs there any method in getopt or Python that I could easily
Danielcheck the validity of each command line input parameter?
Getopt already did the validity check for you. Just catch its exception,
display a meaningful usage message, then exit, e.g.:
try:
o, a = getopt.getopt(sys.argv[1:], 'h', ['imageDir='])
except getopt.GetoptError, msg:
usage(msg)
raise SystemExit # or something similar
My usual definition of usage() looks something like this:
def usage(msg=""):
if msg:
print >>sys.stderr, msg
print >>sys.stderr
print >sys.stderr, __doc__.strip()
This will display the module-level doc string for the user. I find that a
convenient place to document the usage of scripts. For more complex
programs where command line arg processing is in a separate module you may
have to do something like:
def usage(msg=""):
if msg:
print >>sys.stderr, msg
print >>sys.stderr
import __main__
print >sys.stderr, __main__.__doc__.strip()
Skip |