0

i have de folowing situation, as you can see there are 3 required arguments

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-u','--url', required=True)
parser.add_argument('-l','--lang', required=True)
parser.add_argument('-c','--code', required=True)

args = parser.parse_args()

Now I want to add the argument --list-lang, this argument shows a list of available languages

The thing is that I want to copy the behaviour of the --help argument, if the program is executed only with the --list-lang argument it has to show the list of languages, the problem is that the rest of the arguments are needed and when I execute the program in the following way it stops and says that there are missing arguments.

python3 file.py --list-lang

I have tried the following code:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--list-lang', action='store_true')
parser.add_argument('-u','--url', required=True)
parser.add_argument('-l','--lang', required=True)
parser.add_argument('-c','--code', required=True)

args = parser.parse_args()

if args.list_lang:
   show_list_lang()

Is there a way to do this, or do I just remove rel required from the arguments and check them by hand?

Barmar
  • 741,623
  • 53
  • 500
  • 612
SrMiamibeach
  • 116
  • 2
  • Either look into seperating this into sub-commands or using [`mutaully exclusive arg groups`](https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_mutually_exclusive_group) – joshmeranda May 31 '23 at 19:07
  • Remove the `required` requirement, and give the arguments reasonable defaults. Or it is easy to check for the default None, and raise your own `parser.error` – hpaulj May 31 '23 at 20:00
  • It is possible to define an action class modeled on the `help` (or version) class. But you have to be comfortable reading the argparse.py file. – hpaulj May 31 '23 at 20:01
  • As the duplicate shows there are lots of ways to get something like this. And no one approach that is correct or best. I'd try to choose one that's easy and least confusing to your user. – hpaulj May 31 '23 at 20:25
  • you could list the languages in the help, or even make them choices. – hpaulj May 31 '23 at 20:27

0 Answers0