How to handle wrong input in getopt package in Python?

Daniel Mark danielmarkhot at gmail.com
Fri Aug 25 10:33:34 EDT 2006


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!")




More information about the Python-list mailing list