Usage function does not work with getopt

I have a problem with the use function in Python. This is 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 also define the use function

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

but when I run my code like ./code.pyor ./code.py -h(it is executable), I got something other than Python help.

+5
source share
1 answer

Below I worked for me. Run it using "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:])
+5
source

All Articles