argparse presence of switch

Chris Angelico rosuav at gmail.com
Tue Jan 12 13:13:29 EST 2021


On Wed, Jan 13, 2021 at 5:01 AM Dhimant Patel <drp4kri at gmail.com> wrote:
>
> Its what I searched for on this group.
>
> 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')
>
> Since argument started with "-" it should be optional, but absence of it causes following error:
>
> main.py: error: argument -r/--register: expected one argument

This is what different actions are for. I'd probably use
action="store_true" here; that should mean that args.register will be
set to True if "-r" was passed, or False if it wasn't.

ChrisA


More information about the Python-list mailing list