How to handle wrong input in getopt package in Python?

D

Daniel Mark

Hello all:

I am using getopt package in Python and found a problem that I can not
figure out an easy to do .

// Correct input
D:\>python AddArrowOnImage.py --imageDir=c:/

// Incorrect input
D:\>python AddArrowOnImage.py --imageDi
Traceback (most recent call last):
File "AddArrowOnImage.py", line 113, in ?
File "AddArrowOnImage.py", line 88, in main
File "getopt.pyc", line 89, in getopt
File "getopt.pyc", line 157, in do_longs
getopt.GetoptError: option --imageDir requires argument

Is there any method in getopt or Python that I could easily check the
validity of each
command line input parameter?

Thank you
-Daniel


FYI: My code that deals with getopt is as follows:

o, a = getopt.getopt(sys.argv[1:], 'h', ['imageDir='])

opts = {}
for k,v in o:
if k in ['--imageDir'] and len(v) == 0:
usage(); sys.exit("Insufficient input parameters!")
opts[k] = v
if opts.has_key('-h'):

usage(); sys.exit(0)
if not len(opts['--imageDir']):
usage(); sys.exit("Insufficient input parameters!")
 
S

skip

Daniel> getopt.GetoptError: option --imageDir requires argument

Which is precisely what the getopt module should do.

Daniel> Is there any method in getopt or Python that I could easily
Daniel> check 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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,920
Messages
2,570,038
Members
46,449
Latest member
onedumbsquirrel

Latest Threads

Top