49
import argparse

parser = argparse.ArgumentParser(description='sort given numbers')
parser.add_argument('-s', nargs = '+', type = int)
args = parser.parse_args()
print(args)

On command line when I run the command

python3 file_name.py -s 9 8 76

It prints Namespace(s=[9, 8, 76]).

How can I access the list [9, 8, 76]? What is the namespace object. Where can I learn more about it?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Shashank Garg
  • 703
  • 1
  • 6
  • 14

3 Answers3

57
  • The documentation for argparse.Namespace can be found here.
  • You can access the s attribute by doing args.s.
  • If you'd like to access this as a dictionary, you can do vars(args), which means you can also do vars(args)['s']
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
  • argparse.Namespace can also be used for type-hinting! i.e. args: argparse.Namespace. Your answer helped me figure out that it was a module specific Namespace type instead of global. – colby-ham Oct 23 '19 at 23:01
3

It is the result object that argparse returns; the items named are attributes:

print(args.s)

This is a very simple object, deliberately so. Your parsed arguments are attributes on this object (with the name determined by the long option, or if set, the dest argument).

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thanks a lot for the answer. Where can I know more about this namespace object? Where and how is it used? I couldn't find anything good on googling. – Shashank Garg Dec 29 '13 at 18:00
  • 1
    I linked you to the documentation in my answer already. There is not that much to say about it, really. – Martijn Pieters Dec 29 '13 at 19:29
1

you can access as args.s , "NameSpace class is deliberately simple, just an object subclass with a readable string representation. If you prefer to have dict-like view of the attributes, you can use the standard Python idiom, vars()." Source

Owen
  • 7,494
  • 10
  • 42
  • 52