如何使用docopt传递多个参数

时间:2015-02-19 09:27:24

标签: python docopt

我想使用docopt向我的程序传递两个必需参数,一个可选参数。我正在使用的代码是:

"""Setup

Usage: myprog.py server_name config [--help] [options] 

Arguments:
    SERVER_NAME        Server Name (a1, a2)
    CONFIG             Config file with full path

Options:
    -h --help
    -r --start      Start the server if yes [default: 'no']
"""

from docopt import docopt

class ServerSetup(object):
    def __init__(self, server_name, config_file, start_server):
        self.server = server_name
        self.config = config_file
        self.start_server = start_server

    def print_msg(self):
        print self.server
        print self.config
        print self.start_server

if __name__ == '__main__':
    args = docopt(__doc__)
    setup = ServerSetup(server_name=args['SERVER_NAME']),
                        config=args['CONFIG']
                        start_rig=args['-r'])
    setup.print_msg()
  

$ python myprog.py a1 /abc/file1.txt

当我使用上面的命令运行上面的程序时,我收到显示我写过的用法的错误消息。这里出了什么问题,我怎么能使用多个'Arguments'?

1 个答案:

答案 0 :(得分:5)

将参数括在< ...>中,否则它们只是作为命令进行威胁。这应该有效:

"""Setup

Usage: myprog.py [options] <SERVER_NAME> <CONFIG>

Arguments:
    SERVER_NAME        Server Name (a1, a2)
    CONFIG             Config file with full path

Options:
    -h, --help
    -r, --start        Start the server if yes [default: 'no']
"""

from docopt import docopt

class ServerSetup(object):
    def __init__(self, server_name, config_file, start_server):
        self.server = server_name
        self.config = config_file
        self.start_server = start_server

    def print_msg(self):
        print self.server
        print self.config
        print self.start_server

if __name__ == '__main__':
    args = docopt(__doc__)
    print args
    setup = ServerSetup(server_name=args['<SERVER_NAME>'],
                        config_file=args['<CONFIG>'],
                        start_server=args['--start'])
    setup.print_msg()