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_argument
的 required
命名参数:
parser.add_argument('--use-lang', required=True, help="Output language")
关于python - argparse "compulsory"可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22333636/