usage function doesn't work with getopt

Alejandro picture Alejandro · Sep 26, 2011 · Viewed 20k times · Source

I have a problem with a usage function in Python. This is a part of my main function:

def main(argv):
    try:
            opts, args = getopt.getopt(argv, 'hi:o:tbpms:', ['help', 'input=', 'output='])
            if not opts:
                    print 'No options supplied'
                    usage()
    except getopt.GetoptError,e:
           print e
           usage()
           sys.exit(2)

    for opt, arg in opts:
            if opt in ('-h', '--help'):
                    usage()
                   sys.exit(2)
if __name__ =='__main__':
    main(sys.argv[1:])

and I define a usage function as well

def usage():
    print "\nThis is the usage function\n"
    print 'Usage: '+sys.argv[0]+' -i <file1> [option]'

but when I run my code as ./code.py or ./code.py -h (it is executable) I got anything but the Python help.

Answer

BenH picture BenH · Sep 26, 2011

The below worked for me. Run it with "python code.py".

import getopt, sys

def usage():
  print "\nThis is the usage function\n"
  print 'Usage: '+sys.argv[0]+' -i <file1> [option]'

def main(argv):
  try:
    opts, args = getopt.getopt(argv, 'hi:o:tbpms:', ['help', 'input=', 'output='])
    if not opts:
      print 'No options supplied'
      usage()
  except getopt.GetoptError,e:
    print e
    usage()
    sys.exit(2)

  for opt, arg in opts:
    if opt in ('-h', '--help'):
      usage()
      sys.exit(2)

if __name__ =='__main__':
    main(sys.argv[1:])