docopt 不解析参数,只打印用法

docopt does not parse args, just prints usage

我无法让 docopt 工作。我有这个简单的例子,据我所知它是正确的:

#! /usr/bin/env python3
"""usage: do.py name

"""
from docopt import docopt


args = docopt(__doc__)
print(f"Hello, {args['name']}!")

它只会打印:

$ ./do.py susan
usage: do.py name

来自docopt documentation:

  • <arguments>, ARGUMENTS. Arguments are specified as either upper-case words, e.g. my_program.py CONTENT-PATH or words surrounded by angular brackets: my_program.py <content-path>.

因为 name 既不是大写也没有被尖括号括起来,所以它不是一个参数。而且既然不是论证,那肯定属于

的范畴
  • commands are words that do not follow the described above conventions of --options or <arguments> or ARGUMENTS, plus two special commands: dash "-" and double dash "--"…

确实如此:

$ ./do.py name
Hello, True!

它显示 True 因为这是为命令存储的值,用于证明输入了命令。所以这可能不是你想要的。你可以从这个模型开始:

#! /usr/bin/env python3
"""usage: do.py hello <name>

"""
from docopt import docopt

args = docopt(__doc__)
if args['hello']:
    print(f"Hello, {args['<name>']}!")

哪个结果更直观:

 ./do.py hello susan
Hello, susan!

但您可能根本不需要命令:

#! /usr/bin/env python3
"""usage: do.py <name>

"""
from docopt import docopt

args = docopt(__doc__)
print(f"Hello, {args['<name>']}!")
$ ./do.py susan
Hello, susan!