【发布时间】:2008-12-03 12:36:12
【问题描述】:
我不确定optparse 的metavar 参数是做什么用的。我看到它到处都在使用,但我看不到它的用途。
有人可以告诉我吗?谢谢。
【问题讨论】:
我不确定optparse 的metavar 参数是做什么用的。我看到它到处都在使用,但我看不到它的用途。
有人可以告诉我吗?谢谢。
【问题讨论】:
正如@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”来自元变量。
【讨论】:
metavar 似乎用于生成帮助:http://www.python.org/doc/2.5.2/lib/optparse-generating-help.html
【讨论】:
metavar 是选项后用于在屏幕上打印的变量。通常用于选项后的建议输入是FILE 或INT 或STRING 给用户。如果没有metavar,optparse 将在添加选项后打印dest 值。
【讨论】:
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')
【讨论】: