pythongetopt

how set default value if cmd arguments is not set in getopt


I use getopt to parse command line arguments in python script. Is it possible to set default values for command line arguments? I have following code:

try:
  opts, args = getopt.getopt(argv,"htt:tf:d:",["from=","to=","on="])
except getopt.GetoptError:
  print 'logReader.py -f <from> -t <to> -d <on>'
  sys.exit(2)
for opt, arg in opts:
  if opt == '-h':
    print 'logReader.py -f <from> -t <to> -d <on>'
    sys.exit()
  elif opt in ("-f", "--from"):
    fromTime = arg
  elif opt in ("-t", "--to"):
    toTime = arg
  elif opt in ("-d", "--on"):
    onDate = arg 

So I need to do so if from is not set, fromTime should be set as some default value.


Solution

  • With argparse, modified from the tutorial:

    import argparse
    parser = argparse.ArgumentParser()
    # The -- indicates that it is optional 
    parser.add_argument("--verbosity", help="increase output verbosity") 
    args = parser.parse_args()
    if args.verbosity:
        print "verbosity turned on"
    else:
        print "Default option"
    

    This way if the optional argument is not added it will do the else statement. It adds also a help manual where you can explain all the options. And if it fails to interpret the arguments it automatically return the options of the script. (automatically does this logReader.py -f <from> -t <to> -d <on>)

    The OP in the comments state that argparse is out of consideration due to version problems.

    The other options I see are optparse, or just the basic sys.argv and do it with a else clause.