【问题标题】:Python optparse metavarPython optparse 元变量
【发布时间】:2008-12-03 12:36:12
【问题描述】:

我不确定optparsemetavar 参数是做什么用的。我看到它到处都在使用,但我看不到它的用途。

有人可以告诉我吗?谢谢。

【问题讨论】:

    标签: python optparse


    【解决方案1】:

    正如@Guillaume 所说,它用于生成帮助。如果您想要一个带有参数的选项,例如文件名,您可以将 metavar 参数添加到 add_option 调用中,以便在帮助消息中输出您的首选参数名称/描述符。来自the current module documentation

    usage = "usage: %prog [options] arg1 arg2"
    parser = OptionParser(usage=usage)
    parser.add_option("-f", "--filename",
                      metavar="FILE", help="write output to FILE"),
    

    会产生这样的帮助:

    usage: <yourscript> [options] arg1 arg2
    
    options:
      -f FILE, --filename=FILE
    

    “-f”和“--filename”后面的“FILE”来自元变量。

    【讨论】:

      【解决方案2】:

      【讨论】:

      • metavar="helpfulname" 用一个有用的名字自定义帮助信息;不同于 dest="name"。 dest="name" 可能对用户没有帮助。
      【解决方案3】:

      metavar 是选项后用于在屏幕上打印的变量。通常用于选项后的建议输入是FILEINTSTRING 给用户。如果没有metavaroptparse 将在添加选项后打印dest 值。

      【讨论】:

        【解决方案4】:

        metavar 的另一个有意义的用途是希望使用 'dest' 作为参数查找标记,但使用 metavar 掩盖帮助消息。 (例如,有时在使用子解析器时很方便)。 (如S.Lott的评论所示)。

        parser.add_argument(
                'my_fancy_tag',
                help='Specify destination',
                metavar='helpful_message'
                )
        

        或同等

        parser.add_argument(
                dest='my_fancy_tag',
                help='Specify destination',
                metavar='helpful_message'
                )
        

        帮助将显示元变量:

        ./parse.py -h usage: parser [-h] destination
        
        positional arguments:   
          helpful_message  Specify destination
        

        但 dest 会将 fancy_tag 存储在命名空间中:

        ./parse.py test 
        Namespace(my_fancy_tag='test')
        

        【讨论】:

          【解决方案5】:

          现在最好使用 argparse 库而不是 optparse。

          给出here的原因。

          【讨论】:

            猜你喜欢
            • 2011-11-22
            • 1970-01-01
            • 2011-08-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-04-22
            • 1970-01-01
            相关资源
            最近更新 更多