python3上的docopt只打印帮助屏幕,不执行函数

2024-06-06 12:13:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我第一次在python3中使用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)

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

所以如果我发出命令行调用,比如:

^{pr2}$

返回的全部内容如下。在

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

我想知道是什么地方出了问题,这样我就可以实际运行定义的函数了。在


Tags: toonaddressesarghelpdocoptbostonwork
1条回答
网友
1楼 · 发布于 2024-06-06 12:13:56

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

docstring的Usage:Options:部分之间需要有一个空行,否则docopt将给出与我上面的问题类似的结果。此要求在documentation中提到,但可能很难理解(重点是我的):

Usage pattern format

Usage pattern is a substring of doc that starts with usage: (case insensitive) and ends with a visibly empty line.

相关问题 更多 >