argparse "compulsory" optional arguments

Question:

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?

Asked By: ArjunShankar

||

Answers:

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")
Answered By: ArjunShankar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.