Python optparse元变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/336963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python optparse metavar
提问by Blair Conrad
I am not sure what optparse
's metavar
parameter is used for. I see it is used all around, but I can't see its use.
我不确定optparse
's 的metavar
参数用于什么。我看到它到处都在使用,但我看不到它的用途。
Can someone make it clear to me? Thanks.
有人可以给我说清楚吗?谢谢。
回答by Blair Conrad
As @Guillaume says, it's used for generating help. If you want to have an option that takes an argument, such as a filename, you can add the metavar
parameter to the add_option
call so your preferred argument name/descriptor is output in the help message. From the current module documentation:
正如@Guillaume 所说,它用于生成帮助。如果您想要一个带有参数的选项,例如文件名,您可以将metavar
参数添加到add_option
调用中,以便在帮助消息中输出您首选的参数名称/描述符。从当前模块文档:
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-f", "--filename",
metavar="FILE", help="write output to FILE"),
would produce help like this:
会产生这样的帮助:
usage: <yourscript> [options] arg1 arg2
options:
-f FILE, --filename=FILE
The "FILE" after the "-f" and the "--filename" comes from the metavar.
“-f”和“--filename”之后的“FILE”来自元变量。
回答by Guillaume
metavar seems to be used for generating help : http://www.python.org/doc/2.5.2/lib/optparse-generating-help.html
metavar 似乎用于生成帮助:http://www.python.org/doc/2.5.2/lib/optparse-generating-help.html
回答by Yuda Prawira
metavar
is a variable used for print in the screen after option. Usually used for suggestion input after option are FILE
or INT
or STRING
to user. Without metavar
, optparse
will print dest
value after option you've been added.
metavar
是用于在选项后的屏幕中打印的变量。通常用于选项 are FILE
or INT
or后的建议输入STRING
给用户。没有metavar
,optparse
将dest
在添加选项后打印值。
回答by count0
There's another meaningful use of metavar where one desires to use 'dest' as the argument lookup-tag but mask the help message by metavar. (E.g. sometimes handy when using subparsers). (As indicated in the comment of S.Lott).
metavar 的另一个有意义的用途是使用“dest”作为参数查找标签,但通过 metavar 屏蔽帮助消息。(例如,有时在使用子解析器时很方便)。(如S.Lott的评论所示)。
parser.add_argument(
'my_fancy_tag',
help='Specify destination',
metavar='helpful_message'
)
or equally
或同样
parser.add_argument(
dest='my_fancy_tag',
help='Specify destination',
metavar='helpful_message'
)
Help will show the metavar:
帮助将显示元变量:
./parse.py -h usage: parser [-h] destination
positional arguments:
helpful_message Specify destination
but dest will store the fancy_tag in Namespace:
但 dest 将在命名空间中存储fancy_tag:
./parse.py test
Namespace(my_fancy_tag='test')