0

Consider:

    import getopt

    options, remainder = getopt.getopt(sys.argv[1:], 'd:a', ['directory=',
                                                     'algorithm',
                                                     'version=',
                                                     ])
    print 'OPTIONS   :', options

    for opt, arg in options:
      if opt in ('-d', '--dir'):
        directory_path = arg
      elif opt in ('-a', '--alg'):
        algorithm = arg
      elif opt == '--version':
        version = arg

This script works fine, but if the user does not specify any argument (the -d option is a must), how do I specify this and make the program continue without exiting with an error: as no file path specified

If the user does not know which arguments are available to use, how do I show like help or usage?

mklement0
  • 382,024
  • 64
  • 607
  • 775
aAAAAAAa
  • 135
  • 1
  • 2
  • 9

2 Answers2

2

You can define a new function for help and show it when you want

def help():
  print(...)

...
for opt, arg in options:
  if opt in ('-d', '--dir'):
    directory_path = arg
  else:
    help()
RaminNietzsche
  • 2,683
  • 1
  • 20
  • 34
0

you can achieve your goal as below:

import sys
import getopt

def usage():
    print '<program.py> -i infile | -o outfile | -h help'

def mymethod(argv):
 inputfile=''
 outputfile=''
 if(len(argv)<2):
  usage()
  sys.exit(2)
 try:
  opts, args = getopt.getopt(argv, "i:o:h",["ifile=", "ofile=","help="])
 except getopt.GetoptError:
  usage()
  sys.exit(2)
 for opt, arg in opts:
  if opt == '-h':
   usage()
   sys.exit()
  elif opt in ("-i", "--ifile"):
   print 'input file name is ', arg
  if opt in ("-o", "--ofile"):
   print 'output file name is ', arg
if __name__=='__main__':
        mymethod(sys.argv[1:])
Hridaynath
  • 497
  • 5
  • 4