python - argparse "compulsory"可选参数

标签 python argparse

Python 的 argparse 模块具有所谓的“可选”参数。默认情况下,名称以 --- 开头的所有参数都是可选的。通常,强制参数是位置参数,因此在运行程序时,它们没有明确命名

例如,在一个脚本中:

parser.add_argument('language', help="Output language")

调用看起来像:

$ hello-world czech

有时通过名称传递强制参数可能会更好(例如,脚本调用更易于阅读),但仍然是强制的。即

$ hello-world --use-lang czech

如何做到这一点?在 argparse 文档中,命名参数被称为“可选”,这使得它们听起来不能是强制性的。有没有办法强制要求?

最佳答案

根据规范文档,declare 'optional' arguments that are compulsory 是可能的.您使用 add_argumentrequired 命名参数:

parser.add_argument('--use-lang', required=True, help="Output language")

关于python - argparse "compulsory"可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22333636/

相关文章:

python - 关闭 boto ec2 连接

python - 在Python中崩溃时显示消息?

Python:扫描raw_input

python - 如何存储来自同一变量的两个不同输入?

python - 在 "OS X"上使用 Python ArgParse 的 UTF-8 STDIN+STDOUT

python - argparse.REMAINDER 改变位置参数的行为

python - 将大矩阵转换为灰度图像

python - argparse 何时停止显示无参数的 'short help' ?

python - argparse:包括默认值并键入 '--help'

python - 每个位置参数的可选参数