Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

argparse "compulsory" optional arguments

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?

like image 932
ArjunShankar Avatar asked Mar 11 '14 18:03

ArjunShankar


People also ask

How do you make an argument optional in Argparse?

To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.

How do you make an argument compulsory in Python?

By default, the arguments of type -f or --foo are optional and can be omitted. If a user is required to make an argument, they can set the keyword argument required to True .

What is a compulsory argument?

Mandatory (or compulsory) arguments are arguments that have to be specified. Examples: If you want a footnote, you need to use the \footnote command, which has a mandatory argument that specifies the contents of the footnote.

Can positional arguments be optional?

There are two types of arguments a Python function can accept: positional and optional.


1 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")
like image 148
ArjunShankar Avatar answered Oct 01 '22 21:10

ArjunShankar