1

I want to do something like this in my python code

python my_prog.py -inp 3 -inp2 4

and be able to use inp and inp2 as inputs in my python program. How can I do it?

Simone Bolognini
  • 505
  • 5
  • 14

2 Answers2

3

You're looking for the argparse module.

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('input1', metavar='a', type=int, help='an input for foo')
parser.add_argument('input2', metavar='b', type=int, help='an input for bar')
args = parser.parse_args()

print(args.input1 + args.input2)
Maltysen
  • 1,868
  • 17
  • 17
1

You can use getopt for parsing input arguments.

Example from the docu:

import getopt, sys

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
    except getopt.GetoptError as err:
        # print help information and exit:
        print str(err) # will print something like "option -a not recognized"
        usage()
        sys.exit(2)
    output = None
    verbose = False
    for o, a in opts:
        if o == "-v":
            verbose = True
        elif o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ("-o", "--output"):
            output = a
        else:
            assert False, "unhandled option"
    # ...

if __name__ == "__main__":
    main()
Sjoerd222888
  • 3,228
  • 3
  • 31
  • 64
  • Sys.argv is basic sample http://stackoverflow.com/questions/4117530/sys-argv1-meaning-in-script – dsgdfg Aug 01 '15 at 08:39