Valeriy Solovyov
Valeriy Solovyov

Reputation: 5648

How to handle missing arguments in argparse?

I need to do the following:

  1. if there weren't argument's for script variable test == False
  2. elif there was argument -t or --test variable test == True
  3. else there were another arguments get them as string and pass to third code

Now I got an error:

# ./cli something
usage: cli [-t]
cli: error: unrecognized arguments: something

My code for first 2 steps:

import argparse
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-t', '--test', action="store_true")
args = parser.parse_args()
if args.test is True:
    intro = None

Upvotes: 2

Views: 6906

Answers (1)

Wolph
Wolph

Reputation: 80111

Within argparse you need that as a separate parameter, for example:

import argparse
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-t', '--test', action="store_true")
parser.add_argument('params', nargs='+')
args = parser.parse_args()
if args.test is True:
    intro = None
elif args.params:
    pass  # process the params here
else:
    pass  # no params whatsoever

Upvotes: 2

Related Questions