gpt4 book ai didi

python - 不要在 argparse 的 print_help() 中两次显示长选项

转载 作者:太空狗 更新时间:2023-10-29 17:27:03 25 4
gpt4 key购买 nike

我有以下代码:

parser = argparse.ArgumentParser(description='Postfix Queue Administration Tool',
prog='pqa',
usage='%(prog)s [-h] [-v,--version]')
parser.add_argument('-l', '--list', action='store_true',
help='Shows full overview of all queues')
parser.add_argument('-q', '--queue', action='store', metavar='<queue>', dest='queue',
help='Show information for <queue>')
parser.add_argument('-d', '--domain', action='store', metavar='<domain>', dest='domain',
help='Show information about a specific <domain>')
parser.add_argument('-v', '--version', action='version', version='%(prog)s 0.1')
args = parser.parse_args()

这给了我这样的输出:

%./pqa                                                                                                                        
usage: pqa [-h] [-v,--version]

Postfix Queue Administration Tool

optional arguments:
-h, --help show this help message and exit
-l, --list Shows full overview of all queues
-q <queue>, --queue <queue>
Show information for <queue>
-d <domain>, --domain <domain>
Show information about a specific <domain>
-v, --version show program's version number and exit

我非常想知道如何“分组”具有两个版本(即长选项)的命令,每个版本也显示一个元变量。

这主要是我这边的美学问题,但我仍然想解决这个问题。我一直在互联网上阅读手册和文本,但要么没有相关信息,要么我在这里完全遗漏了一些东西:)

最佳答案

将 hpaulj 的答案放入实际代码中,类似这样的工作:

class CustomHelpFormatter(argparse.HelpFormatter):
def _format_action_invocation(self, action):
if not action.option_strings or action.nargs == 0:
return super()._format_action_invocation(action)
default = self._get_default_metavar_for_optional(action)
args_string = self._format_args(action, default)
return ', '.join(action.option_strings) + ' ' + args_string

fmt = lambda prog: CustomHelpFormatter(prog)
parser = argparse.ArgumentParser(formatter_class=fmt)

要额外扩展帮助变量的默认列大小,请将构造函数添加到 CustomHelpFormatter:

def __init__(self, prog):
super().__init__(prog, max_help_position=40, width=80)

实际操作:

usage: bk set [-h] [-p] [-s r] [-f] [-c] [-b c] [-t x y] [-bs s] [-bc c]
[--crop x1 y1 x2 y2] [-g u r d l]
monitor [path]

positional arguments:
monitor monitor number
path input image path

optional arguments:
-h, --help show this help message and exit
-p, --preview previews the changes without applying them
-s, --scale r scales image by given factor
-f, --fit fits the image within monitor work area
-c, --cover makes the image cover whole monitor work area
-b, --background c selects background color
-t, --translate x y places the image at given position
-bs, --border-size s selects border width
-bc, --border-color c selects border size
--crop x1 y1 x2 y2 selects crop area
-g, --gap, --gaps u r d l keeps "border" around work area

关于python - 不要在 argparse 的 print_help() 中两次显示长选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18275023/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com