【问题标题】:docopt boolean arg pythondocopt 布尔 arg python
【发布时间】:2020-06-15 15:53:20
【问题描述】:

我在我的脚本中使用以下 args 和 docopt

Usage:
GaussianMixture.py --snpList=File --callingRAC=File

Options:
-h --help     Show help.
snpList     list snp txt
callingRAC      results snp

我想添加一个对我的脚本有条件结果的参数:更正我的数据或不更正我的数据。类似的东西:

Usage:
GaussianMixture.py --snpList=File --callingRAC=File  correction(--0 | --1)

Options:
-h --help     Show help.
snpList     list snp txt
callingRAC      results snp
correction      0 : without correction | 1 : with correction 

我想在我的脚本中的某些函数中添加if

def func1():
  if args[correction] == 0:
      datas = non_corrected_datas
  if args[correction] == 1:
      datas = corrected_datas

但我不知道如何在我的脚本中使用它。

【问题讨论】:

    标签: python docopt


    【解决方案1】:

    编辑: 我最初的答案没有考虑到 OP 要求 --correction 是强制性的。我的原始答案中的语法不正确。这是一个经过测试的工作示例:

    #!/usr/bin/env python
    """Usage:
        GaussianMixture.py --snpList=File --callingRAC=File --correction=<BOOL>
    
    Options:
        -h, --help          Show this message and exit.
        -V, --version       Show the version and exit
        --snpList         list snp txt
        --callingRAC      results snp
        --correction=BOOL Perform correction?  True or False.  [default: True]
    
    """
    
    __version__ = '0.0.1'
    
    from docopt import docopt
    
    def main(args):
        args = docopt(__doc__, version=__version__)
        print(args)
    
        if args['--correction'] == 'True':
            print("True")
        else:
            print("False")
    
    if __name__ == '__main__':
        args = docopt(__doc__, version=__version__)
        main(args)
    

    如果这对你有用,请告诉我。

    【讨论】:

    • 感谢您提供此解决方案,此方法有效。但是我真的很想有一个带或不带更正的强制性参数,因为用户可能会忘记可选参数并且如果他们不熟悉这个数据不会错误地更正,就好像这是强制性的,他们会有错误。但我可以添加警告打印,同时我找到更好的解决方案:) 无论如何谢谢!
    • 您可以尝试进行更正(删除括号),并给它一个真/假值,例如:
    • 用法:GaussianMixture.py --snpList=文件 --callingRAC=文件修正=(True | False)
    • 最后一条评论没有包含正确的语法 --correction=(True | False) - 我已经更新了我的答案以考虑成为一个强制参数
    • 记得在选项部分加上单-和双破折号--。选项参数也应该出现在选项部分。
    【解决方案2】:

    并非所有选项都必须在 docopt 中包含参数。换句话说,您可以改用 flag 参数。这是从用户那里获取布尔值的最直接的方法。话虽如此,您可以简单地执行以下操作。

    """
    Usage:
      GaussianMixture.py (--correction | --no-correction)
    
    Options:
      --correction      With correction
      --no-correction   Without correction
      -h --help     Show help.
    """
    import docopt
    
    
    if __name__ == '__main__':
        args = docopt.docopt(__doc__)
        print(args)
    
    

    【讨论】:

      猜你喜欢
      • 2016-08-10
      • 1970-01-01
      • 2017-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-20
      • 2021-10-18
      • 2015-05-09
      相关资源
      最近更新 更多