2

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
4
  • 1
    Never use is instead of == to test for equality: don't say if args.test is True: You can just say if args.test Commented Apr 9, 2015 at 11:33
  • What should belong to -t in the following case: cli -t first second? first and second? Commented Apr 9, 2015 at 11:53
  • You if conditions aren't clear. Show us several intended usage cases, and what you want the args namespace to look like. Commented Apr 9, 2015 at 16:46
  • 1
    @smci. Always use is for singletons, like None. Agree with your second statement though. Commented Dec 17, 2018 at 3:26

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.