gpt4 book ai didi

python - 如何防止 docopt 吞下一个选项?

转载 作者:太空宇宙 更新时间:2023-11-04 10:48:12 25 4
gpt4 key购买 nike

我正在尝试使用 docopt 创建命令行界面。这是我的文件的简化版本:

#!/usr/bin/env python
"""
Test program.

Usage:
test.py [options]

Options:
-a <input>
-b
-c
-d
"""
import docopt

print docopt.docopt(__doc__)

我基本上希望能够以任何顺序指定任何选项。但是,如果我忘记为 -a 标志指定参数,则会得到如下输出:

$ python test.py -a -b -c
{"-a": "-b",
"-b": False,
"-c": True,
"-d": False}

Docopt 将 -b 标志视为 -a 标志的参数,而不是拒绝无效输入。有什么简单的方法可以检测到这一点,或者让 docopt 拒绝接受这种格式错误的输入吗?

最佳答案

关于短选项有一些歧义:最好使用 --option=ARG 长选项:

-o --option

Words starting with one or two dashes (with exception of "-", "--" by themselves) are interpreted as short (one-letter) or long options, respectively.

- Short options can be "stacked" meaning that -abc is equivalent to -a -b -c.
- Long options can have arguments specified after space or equal "=" sign: --input=ARG is equivalent to --input ARG.
-Short options can have arguments specified after optional space: -f FILE is equivalent to -fFILE.

Note, writing --input ARG (opposed to --input=ARG) is ambiguous, meaning it is not possibe to tell whether ARG is option's argument or positional argument. In usage patterns this will be interpreted as option with argument only if option's description (covered below) for that option is provided. Otherwise it will be interpreted as separate option and positional argument.

Same ambiguity is with -f FILE and -fFILE notation. Although in the latter case it is not possible to tell whether it is a number of stacked short options, or an option with argument. These notations will be interpreted as option with argument only if option's description is provided.

关于python - 如何防止 docopt 吞下一个选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15827784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com