Python Command Args Python Command Args python python

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 argparseparser = 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 putx = args.xprint 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]: argsOut[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 subscriptableIn [7]: args.xOut[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