Home > Computers > programming > python > parse command line arguments| About


opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
# -h, -i, -o is optional. --ifile, --ofile take arguments
#opts will contain the given arguments as a opt,arg tuples
#args will contain non parsed arguments
#forces you to write code like this : 

   for opt, arg in opts:
      if opt == '-h':
         print 'test.py -i <inputfile> -o <outputfile>'
      elif opt in ("-i", "--ifile"):
         inputfile = arg
      elif opt in ("-o", "--ofile"):
         outputfile = arg


parser = argparse.ArgumentParser()
parser.add_argument('-v', action="store_true")
args = parse.parse_args()
print args.v # (prints true if -v was given on the command line)

You need to use the "dest" argument to add_argument if you would like to have a reserved keyword option like from, import etc.


contact : @ychaouche yacinechaouche at yahoocom

QR Code
QR Code optparse (generated for current page)