Python Command Args

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

A sample run in Ipython with your code, showing that args is a simple object, not a dictionary. In the argparse code the namespace is accessed with getattr and setattr

In [4]: args=parser.parse_args(['12','4','5'])
In [5]: args
Out[5]: Namespace(x=[12, 4, 5])
In [6]: args['x']
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-3867439e1f91> in <module>()
----> 1 args['x']
TypeError: 'Namespace' object is not subscriptable
In [7]: args.x
Out[7]: [12, 4, 5]
In [8]: getattr(args,'x')
Out[8]: [12, 4, 5]
In [9]: sum(getattr(args,'x'))
Out[9]: 21

vars() can be used to turn the namespace into a dictionary.

In [12]: vars(args)['x']
Out[12]: [12, 4, 5]

Review the Namespace section of the argparse documentation.


You should simply do something like this:

x = args.x