仅在参数列表中而不是在其用法中更改 argparse 中的元变量值 [英] Changing the metavar value in argparse only in argument listing and not in its Usage
问题描述
我的问题类似于没有重复ALLCAPS的argparse帮助 问题.
My question is similar to argparse help without duplicate ALLCAPS question.
虽然我会简要解释那个问题是什么以及我的问题是什么:
我想以与默认 -h,--help
相同的方式显示我的选项的 argparse 帮助,每个选项后没有 ALLCAPS 文本,或者至少没有重复的 CAPS.
Though i would explain in brief what that question was and what my question is:
I'd like to display argparse help for my options the same way the default -h,--help
is, without the ALLCAPS text after each option, or at least without the duplicated CAPS.
例如,使用以下代码:
#filename=temp.py
import argparse
p = argparse.ArgumentParser()
p.add_argument('-i', '--ini', help="use alternate ini file")
print '\n', p.parse_args()
现在运行 python temp.py -h
:
usage: temp.py [-h] [-i INI]
optional arguments:
-h, --help show this help message and exit
-i INI, --ini INI use alternate ini file
现在我想要的是:
usage: 123.py [-h] [-i INI]
optional arguments:
-h, --help show this help message and exit
-i, --ini INI use alternate ini file
或
usage: 123.py [-h] [-i INI]
optional arguments:
-h, --help show this help message and exit
-i, --ini use alternate ini file
要获得第二个,方法是将 p.add_argument
行中的默认 metavar
更改为:
To get the second one, the way is to change the default metavar
in the line p.add_argument
as:
p.add_argument('-i', '--ini', help="use alternate ini file")
并更改argparse.ArgumentParser()
中的默认用法声明.
and change the default usage statement in argparse.ArgumentParser()
.
但是当我的代码中可选参数的数量增加时,我发现很难根据代码中的修改添加和删除参数来修改使用消息.
But when number of optional arguments increases in my code, I find it difficult to modify the usage message by adding and deleting the argument according to the modification in my code.
有没有其他方法可以解决metavar
的问题而不影响使用说明.
Is there any other way of solving the problem of metavar
without affecting the usage statement.
另外,如果我想让我的帮助显示在第一种情况下,在 -i, --ini
之后只有一次 INI
.
Also what if I want to have my help displayed as shown in the first case, where there is only one time INI
after -i, --ini
.
如果我错误地将帮助显示为 -i, --ini INI
或 -i, --ini
而不是 -i INI,--ini INI
请以适当的理由纠正我.(我的意思是说错了,我使用的约定会导致用户混淆或误解)
If I am getting wrong in showing help as -i, --ini INI
or -i, --ini
instead of -i INI, --ini INI
please correct me with proper reason. (By getting wrong I mean, it the convention I am using will lead to confusion or misunderstanding in user)
推荐答案
要获得快速解决方案,您只需将退格字符设置为元变量即可.
For a fast solution you can just set backspace character to a metavar.
p.add_argument('-i', '--ini', help="use alternate ini file", metavar='\b')
它会让你得到这个:
optional arguments:
-h, --help show this help message and exit
如果你想要这个:
-i, --ini INI use alternate ini file
您将不得不修改帮助格式化程序.在这里回答 python argparse 帮助消息,禁用短选项的元变量?
You will have to modify help formatter. Answered here python argparse help message, disable metavar for short options?
这篇关于仅在参数列表中而不是在其用法中更改 argparse 中的元变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!