Home > Computers > programming > python > parse command line arguments| About
optparse
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>' sys.exit() elif opt in ("-i", "--ifile"): inputfile = arg elif opt in ("-o", "--ofile"): outputfile = arg
argparse
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.
parser.add_argument("--from",dest="_from")
contact : @ychaouche yacinechaouche at yahoocom