Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

usage function doesn't work with getopt

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.

like image 474
Alejandro Avatar asked Sep 26 '11 14:09

Alejandro


1 Answers

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:])
like image 131
BenH Avatar answered Oct 14 '22 09:10

BenH