我如何使用"选项结束"在docopt中?

时间:2016-05-28 00:21:17

标签: python command-line-arguments docopt

我使用docopt和python 2.7。我想在vim中实现与--类似的东西。来自man vim

--      Denotes the end of the options. Arguments after this will be handled as a file 
        name. This can be used to edit a filename that starts with a '-'.

值得庆幸的是,docopt已经实现了这一点,但它在我的参数列表中给了我额外的'--'。例如,使用这个简短的python脚本:

"""Usage:
  doc.py FILE [ARGUMENTS ... ]
  doc.py FILE [options] [ARGUMENTS ... ]
Options:
  -h --help     Show this screen.
  -d            Debug mode.
  -f FILE       Open FILE
  -w FILE       Log to FILE
  --safe        Do not allow shell access
"""

from docopt import docopt

def main():
    print(args["ARGUMENTS"])

if __name__ == "__main__":
    args = docopt(__doc__, version="V alpha 0.1")
    main()

如果我用

打电话
python doc.py file.txt -- 1 2 3 -w

我明白了:

['--', '1', '2', '3', '-w']

我希望它能给出:

['1', '2', '3', '-w']

我做错了什么?

2 个答案:

答案 0 :(得分:0)

我不是专家,但请尝试为所有用法选择--

doc.py FILE [options] [--] [ARGUMENTS ... ]

您既可以输入选项,也可以不输入参数。如果它存在,它将查找第一个--

让我知道这是否有效。

答案 1 :(得分:0)

我已经尝试过Wahlstrom的解决方案,那是行不通的。
据我所知,docopt会将所有内容解析为参数列表,
docopt中没有语法或特殊用法供您使用。

目前最好的解决方案是在进一步的程序流程之前清除“-”元素。
或者只是添加一个if案例来处理它。