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?
To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.
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 .
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.
There are two types of arguments a Python function can accept: positional and optional.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With