Python Command Args

user1601118 picture user1601118 · Jul 29, 2013 · Viewed 16.6k times · Source

I have been googling almost an hour and am just stuck.

for a script, stupidadder.py, that adds 2 to the command arg.

e.g. python stupidadder.py 4

prints 6

python stupidadder.py 12

prints 14

I have googled so far:

import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('x', metavar='x', type=int, nargs='+',
                    help='input number')

...

args = parser.parse_args()
print args
x = args['x']  # fails here, not sure what to put
print x + 2

I can't find a straightforward answer to this anywhere. the documentation is so confusing. :( Can someone help? Please and thank you. :)

Answer

tdelaney picture tdelaney · Jul 29, 2013

Assuming that you are learning how to use the argparse module, you are very close. The parameter is an attribute of the returned args object and is referenced as x = args.x.

import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('x', metavar='x', type=int, nargs='+',
                    help='input number')

...

args = parser.parse_args()
print args
#x = args['x']  # fails here, not sure what to put
x = args.x
print x + 2