argparse "compulsory" optional arguments

ArjunShankar picture ArjunShankar · Mar 11, 2014 · Viewed 16.8k times · Source

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?

Answer

ArjunShankar picture ArjunShankar · Mar 11, 2014

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")