Domanda

Python's argparse module has what are called 'optional' arguments. All arguments whose name starts with - or -- are optional by default. Typically, compulsory arguments are positional, and hence when running the program, they are not explicitly named.

For example, in a script which had:

parser.add_argument('language', help="Output language")

Invocations would look like:

$ hello-world czech

It may sometimes be nicer to have a compulsory argument passed by name (e.g. scripted invocations are easier to read this way), but still be compulsory. i.e.

$ hello-world --use-lang czech

How to achieve this? Named arguments are called 'optional' in the argparse documentation, which makes it sound like they cannot be compulsory. Is there a way to make them compulsory?

È stato utile?

Soluzione

According to canonical documentation, it is possible to declare 'optional' arguments that are compulsory. You use the required named argument of add_argument:

parser.add_argument('--use-lang', required=True, help="Output language")
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top