我是第一次在Python 3中使用docopt。当我运行代码时,输​​出仅显示“用法”选项数据,而不执行模块中的功能。

这是一个例子。我在文件中有此代码。

"""Usage:  scratch.py [-h] [--boston | --sandiego] [--prostitution |
        --drugs] [--lim VALUE]
    Options:
        -h --help        :Show help information
        --boston         : work on boston addresses
        --sandiego       : work on san diego addresses
        --prostitution  : prostitution incidents
        --drugs         : drug sale incidents
        --lim          : number of addresses to work with
"""


from docopt import docopt

def scratch(args):
    print(args['--boston'])
    print('hello')

if __name__ == '__main__':

    arg = docopt(__doc__, help=False)
    print(arg)
    scratch(arg)


当我使用各种选项运行该文件时,得到的只是文档字符串的副本。我应该看到docopt从docstring参数创建的字典的副本。然后,我还应该从函数调用中看到打印结果。但是除了文档字符串,我什么也看不到。

因此,如果我进行如下命令行调用:

python scratch.py --boston --drugs --lim 100


返回的所有内容如下。

Usage:  scratch.py <city> [--boston | --sandiego] <crime> [--prostitution |
        --drugs] --count=N
    Options:
        city            : city to geocode
        --boston         : work on boston addresses
        --sandiego       : work on san diego addresses
        crime           : crime to select on
        --prostitution  : prostitution incidents
        --drugs         : drug sale incidents
        -count          : number of addresses to work with


我想知道出了什么问题,这样我才能实际运行已定义的函数。

最佳答案

此答案的功劳属于J.F. Sebastian, above;我只是想确保我解决了这个问题。

在文档字符串的Usage:Options:部分之间必须有一个空行,否则docopt将给您类似我上面问题的结果。 documentation中提到了此要求,但是可能很难理解(强调我的意思):


  使用模式格式
  
  使用模式是以doc开头的usage:子字符串(大小写)
  不敏感)并以明显的空行结束。

10-08 13:41