gpt4 book ai didi

python argparse : print epilog only when verbose

转载 作者:太空宇宙 更新时间:2023-11-04 10:13:39 26 4
gpt4 key购买 nike

我定义了一个带有描述、选项和结尾的解析器。当我使用 --help 运行应用程序时,它会按预期输出关于 epilog 的帮助。但是,如果 --help 与 --verbose 一起出现,我只想查看结语。使用 argparse 实现此目的的正确方法是什么?

# example code in file test
import argparse
parser = argparse.ArgumentParser( description='description', epilog='epilog' )
parser.add_argument('-v', '--verbose', action='store_true', help='verbose help')
parser.parse_args()

当我按如下方式运行测试时

$ python test -h

它产生

 usage: test [-h] [-v]

description

optional arguments:
-h, --help show this help message and exit
-v, --verbose verbose help

epilog

然而,我想看到的是

 usage: test [-h] [-v]

description

optional arguments:
-h, --help show this help message and exit
-v, --verbose verbose help

仅在我运行时显示结尾

$ python test -h -v

最佳答案

<选择。我知道这样做的唯一方法是自己编写帮助输出:

import argparse
parser = argparse.ArgumentParser(
description='description',
add_help=False )
parser.add_argument(
'-h', '--help',
action=store_true,
dest='show_help')
parser.add_argument(
'-v', '--verbose',
action='store_true',
help='verbose help')
args = parser.parse_args()
if args.show_help:
if args.verbose:
print '%s\n%s' % (parser.format_help(), 'epilog')
else
parser.print_help()
sys.exit(0)

关于 python argparse : print epilog only when verbose,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36738309/

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