1

I'm learning the basics of argparse, and I have made a program that prints information on the solar system in the command line, however, I have used 2 positional arguments which is causing some complications. My aim is to print the 'help' interface when an unknown argument is entered into the command line, but have been unable due to using multiple positional arguments. Using optional arguments is out of the question for now.

How can I print the help for unknown arguments? As I understand it planet does not need to be called as specifically 'planet' but anything and a planet name afterwards so I've found it difficult to do this.

cact1
  • 11
  • 2
  • Your current argument set is rather odd. Do you really need the program to both be able to list (a kind of subcommand) and display information on chosen planet at the same time? Either make subcommands of list and display, or make list a flag, even if you say it is out of the question. – Ilja Everilä Mar 15 '16 at 09:19
  • Normally we expect `argparse` questions to include the `parser` as defined so far, and some sample commandlines and the desired parse. It's hard to tell from text like this what you want and what you have tried. – hpaulj Mar 15 '16 at 17:49
  • An argument, positional or flagged, can take a `choices` parameter, e.g. `choices=['mercury', 'venus', 'earth', ...]`. – hpaulj Mar 15 '16 at 19:33

2 Answers2

1

Perhaps what you're after is a mutually exclusive group.

parser = argparse.ArgumentParser(description="About the Solar System") # initialises argparse

parser.add_argument("--orderby", help="displays the planets ordered by mass, largest to smallest", action='store_true')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--list", help="displays the planets in alphabetical order", action='store_true')
group.add_argument("planet", help="displays information on the chosen <planet> and opens a wiki page", nargs="?", action="store")

args = parser.parse_args()

which would result in

 % python3 args.py 
usage: args.py [-h] [--orderby] (--list | planet)
args.py: error: one of the arguments --list planet is required

and

 % python3 args.py --list
Namespace(list=True, orderby=False, planet=None)

 % python3 args.py asdf  
Namespace(list=False, orderby=False, planet='asdf')

 % python3 args.py --list asdf
usage: args.py [-h] [--orderby] (--list | planet)
args.py: error: argument planet: not allowed with argument --list
Ilja Everilä
  • 40,618
  • 6
  • 82
  • 94
0

You'd want to raise an argParse.ArgumentTypeError with a custom type, there's a basic example how to do that here: argparse choices structure of allowed values

Community
  • 1
  • 1
Nicholas Smith
  • 11,428
  • 6
  • 32
  • 53