Can't get true/false value from command line in python 2.7
Question: I'm trying to incorporate a flag in to a program:

    
    
    python2.7 hello.py --showxy
    

and `argparse` is giving me trouble.

this is my example test code:

    
    
    import os
    import sys
    import argparse
    
    print (os.getcwd())
    print ("___________________________________________________")
    print ("A: " + sys.argv[0])
    print ("B: " + sys.argv[1])
    print ("C: " + sys.argv[2])
    print ("___________________________________________________")
    
    
    parser = argparse.ArgumentParser()
    parser.add_argument('--showxy', action='store_true')
    args = argparse.Namespace()
    d = vars(args)
    
    
    print Namespace()
    

And while I _should_ be getting:

    
    
    Namespace(showxy=True)
    

I am _actually_ getting an error:

    
    
    A: hello.py
    B: haarcascade_frontalface_default.xml
    C: euromil.jpg
    ___________________________________________________
    Traceback (most recent call last):
      File "hello.py", line 19, in <module>
        print Namespace()
    
    NameError: name 'Namespace' is not defined
    

How should I be formatting this?


Answer: You are missing the parsing step

    
    
    args = parser.parse_args()
    

`args = argparse.Namespace()` just creates an new empty `Namespace` object.

`argparse` is the module. `parser` is the `ArgumentParser` object. `Namespace`
is a class defined in that module. `parse_args` creates a `Namespace`, fills
it with values that that it parses from `sys.argv`, and returns it as `args`.

Defining the `parser` by itself does not do any parsing.

* * *

The very first example in the docs is:

    
    
    import argparse
    
    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument('integers', metavar='N', type=int, nargs='+',
                       help='an integer for the accumulator')
    parser.add_argument('--sum', dest='accumulate', action='store_const',
                       const=sum, default=max,
                       help='sum the integers (default: find the max)')
    
    args = parser.parse_args()
    print(args.accumulate(args.integers))
    

Some claim this is too advanced for beginners, but the key pieces are there.

    
    
    parser = ...
    parser.add_argument...
    args = parser.parse_args()
    # look at args, print it, access attributes, etc.
    

`argparse.Namespace` isn't mentioned until section
<https://docs.python.org/3/library/argparse.html#the-namespace-object>

