难以使用Python docopt必需的选项和带参数的选项

2024-06-28 16:13:12 发布

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

我是新来的docopt和有点困难,得到一个小的例子工作。我刚才遇到了两个小问题,希望能得到关于这些问题的帮助和关于改进代码的更多一般性意见。第一个问题是让程序需要--required选项。它应该在不使用必需的命令行选项的情况下在运行时打印docstring。第二个问题是让程序接受选项(比如--computer)的参数(比如COMPUTER)。如何在终端中指定,以及如何对其进行编码?

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
my example program

Usage:
    docopt_example_1.py [--ipaddress=IPADDRESS] [--computer=COMPUTER]
    docopt_example_1.py --network <network>
    docopt_example_1.py (--required)
    docopt_example_1.py --notrequired
    docopt_example_1.py --version

Arguments:
    IPADDRESS               I.P. address
    COMPUTER                computer identification
    <network>               network identification

Options:
    -h, --help              Show this help message.
    --version               Show the version and exit.
    --required              option required for running
    --notrequired           option not required for running
    --ipaddress=IPADDRESS   I.P. address
    --computer=COMPUTER     computer identification
    --network=NETWORK       network identification
"""
from docopt import docopt

def main(options):
    print("----------")
    print("a printout of the command line options as parsed by docopt:")
    print(options)
    print("----------")
    if options["--notrequired"]:
        print("required option selected")
    if options["--computer"]:
        print("computer name: {computer}".format(computer=options["COMPUTER"]))
    if options["--network"]:
        print("computer name: {network}".format(network=options["<network>"]))
    else:
        print("no options")

if __name__ == "__main__":
    options = docopt(__doc__, version='1')
    main(options)

Tags: pyifversionexample选项requirednetworkdocopt