【问题标题】:including more than one list of arguments with docopt包括多个带有 docopt 的参数列表
【发布时间】:2015-06-01 13:36:22
【问题描述】:

我将 python 应用程序用作命令行工具,功能 docopt library。使用该库很容易实现命令。 但是,目前我找不到完成以下要求的方法:

文档字符串是:

"""
aTXT tool

Usage:
  aTXT <source>... [--ext <ext>...]

Options:
    --ext       message

"""

从shell,我想写这样的东西:

atxt a b c --ext e f g

docopt 输出的结果字典如下:

 {'--ext': True,
 '<ext>': [],
 '<source>': ['a', 'b', 'c', 'e', 'f']}

但是,我需要具备以下条件:

 {'--ext': True,
 '<ext>': ['e', 'f', 'g'],
 '<source>': ['a', 'b', 'c']}

我该如何进行?

【问题讨论】:

    标签: python command-line-interface command-line-arguments docopt


    【解决方案1】:

    我还没有找到将列表直接传递到 Docopt 参数字典的方法。但是,我已经制定了一个解决方案,允许我将一个字符串传递给 Docopt,然后将该字符串转换为一个列表。

    您的 Docopt doc 存在问题,我对其进行了修改,以便测试针对您的案例的解决方案。这段代码是用 Python 3.4 编写的。

    命令行:

    $python3 gitHubTest.py a,b,c -e 'e,f,g'
    

    gitHubTest.py

    """
    aTXT tool
    
    Usage:
      aTXT.py [options] (<source>)
    
    Options:
      -e ext, --extension=ext    message
    
    """
    from docopt import docopt
    
    def main(args) :
        if args['--extension'] != None:
            extensions = args['--extension'].rsplit(sep=',')
            print (extensions)
    
    if __name__ == '__main__':
        args = docopt(__doc__, version='1.00')
        print (args)
        main(args)
    

    返回:

    {
    '--extension': 'e,f,g',
    '<source>': 'a,b,c'
    }
    ['e', 'f', 'g']
    

    在 main() 中创建的变量“扩展”现在是您希望传入的列表。

    【讨论】:

    • 我希望有一种方法可以用 docopt 正确地做到这一点...据我了解,拥有多个像 OP 想要的列表是完全合法的。使用 argparse 是可能的:stackoverflow.com/a/32763023/4671300
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-12
    • 1970-01-01
    • 1970-01-01
    • 2013-08-30
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多