我使用下面的简单代码来解析一些参数;请注意,其中之一是必需的。不幸的是,当用户在不提供参数的情况下运行脚本时,显示的用法/帮助文本并不表示存在非可选参数,我觉得这很困惑。如何让 python 指示参数不是可选的?
代码如下:
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Foo')
parser.add_argument('-i','--input', help='Input file name', required=True)
parser.add_argument('-o','--output', help='Output file name', default="stdout")
args = parser.parse_args()
print ("Input file: %s" % args.input )
print ("Output file: %s" % args.output )
在不提供所需参数的情况下运行上述代码时,我得到以下输出:
usage: foo.py [-h] -i INPUT [-o OUTPUT]
Foo
optional arguments:
-h, --help show this help message and exit
-i INPUT, --input INPUT
Input file name
-o OUTPUT, --output OUTPUT
Output file name
最佳答案
以 -
或 --
开头的参数通常被认为是可选的。所有其他参数都是位置参数,因此设计需要(如位置函数参数)。可能需要可选参数,但这有点违背他们的设计。由于它们仍然是非位置参数的一部分,即使它们是必需的,它们仍然会列在令人困惑的标题“可选参数”下。然而,用法部分中缺少的方括号表明它们确实是必需的。
另见documentation :
In general, the argparse module assumes that flags like -f and --bar indicate optional arguments, which can always be omitted at the command line.
Note: Required options are generally considered bad form because users expect options to be optional, and thus they should be avoided when possible.
话虽如此,帮助中的标题 “位置参数” 和 “可选参数” 是由两个参数组生成的,其中参数自动分成。现在,您可以“破解”并更改可选参数的名称,但更优雅的解决方案是为“必需的命名参数”(或任何您想调用的名称)创建另一个组:
parser = argparse.ArgumentParser(description='Foo')
parser.add_argument('-o', '--output', help='Output file name', default='stdout')
requiredNamed = parser.add_argument_group('required named arguments')
requiredNamed.add_argument('-i', '--input', help='Input file name', required=True)
parser.parse_args(['-h'])
usage: [-h] [-o OUTPUT] -i INPUT
Foo
optional arguments:
-h, --help show this help message and exit
-o OUTPUT, --output OUTPUT
Output file name
required named arguments:
-i INPUT, --input INPUT
Input file name
关于python - Argparse:在 "optional arguments"下列出的必需参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24180527/