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 (eg scripted invocations are easier to read this way), but still be compulsory. ie
$ 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?
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")
链接地址: http://www.djcxy.com/p/28558.html
下一篇: 强制“强制性”可选参数