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. :)
I'm not entirely sure what your goal is. But if that's literally all you have to do, you don't have to get very complicated:
import sys
print int(sys.argv[1]) + 2
Here is the same but with some nicer error checking:
import sys
if len(sys.argv) < 2:
print "Usage: %s <integer>" % sys.argv[0]
sys.exit(1)
try:
x = int(sys.argv[1])
except ValueError:
print "Usage: %s <integer>" % sys.argv[0]
sys.exit(1)
print x + 2
Sample usage:
C:\Users\user>python blah.py
Usage: blah.py <integer>
C:\Users\user>python blah.py ffx
Usage: blah.py <integer>
C:\Users\user>python blah.py 17
19