argparse presence of switch

David Lowry-Duda david at lowryduda.com
Tue Jan 12 13:18:48 EST 2021


> I want to have an argument's presence only - value is not required.
> For example, my program main.py needs to know if "-r" is present when program is invoked. 
> So the value command line would be:
> (1) python3 main.py -r 
> or...
> (1) python3 main.py
> 
> I tried following:
> parser.add_argument('-r','--register', help='Register it')

You should use the "store_true" action, or perhaps some other action.

A complete minimal working sample is as follows.


import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-r", "--register", help="Register it",
                    action="store_true")
args = parser.parse_args()
if args.register:
    print("Seen register")


For more, I suggest reading the quick tutorial in the documentation, 
available at https://docs.python.org/3/howto/argparse.html#id1

Good luck! - DLD


More information about the Python-list mailing list