Skip to main content
 首页 » 编程设计

python之python 3 上的 docopt 仅打印帮助屏幕并且不执行该功能

2025年05月04日18yyy_WW

我是第一次在 Python 3 中使用 docopt。当我运行代码时,输​​出仅显示 Usage 选项数据,并没有执行模块中的函数。

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

"""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 中提到了此要求, 但它可能很难捕捉(强调我的):

Usage pattern format

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