首页 > 解决方案 > 如何显示自定义消息而不是 Argparse 生成的默认帮助消息?

问题描述

考虑以下示例代码

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('action', help='Action to take')
parser.add_argument('-b','--bar', help='Description for bar argument')
parser.parse_args()

--help参数调用它的输出可能是这样的:

positional arguments:

action   Action to take


optional arguments:

-h, --help show this help message and exit
-b  --bar  Description for bar argument

我不想要 Argparse 生成的上述默认帮助文本。我想要一个完全由我写的消息

例如,使用--help参数调用文件应显示以下帮助消息:

Please go to http://some_website.com/help to understand more about our software

那么如何向 Argparse 提供我的自定义消息?

标签: pythonpython-3.xargparse

解决方案


您需要覆盖print_help()方法。所以,我创建了一个名为MyArguementParser覆盖的类,ArgumentParser如下所示:

import argparse
import sys as _sys

class MyArgumentParser(argparse.ArgumentParser):

    def print_help(self, file=None):
        if file is None:
            file = _sys.stdout
        message = "Please go to http://some_website.com/help to understand more about our software"
        file.write(message+"\n")

现在,ArgumentParser您将MyArgumentParser像这样调用,而不是被调用:

parser = MyArgumentParser() #THIS IS THE ONLY CHANGE YOU NEED TO MAKE
# parser = argparse.ArgumentParser()
parser.add_argument('action', help='Action to take')
parser.add_argument('-b','--bar', help='Description for bar argument')
parser.parse_args()

现在,当您使用-h--help标志运行脚本时!

print_usage()当用户滥用任何提供的参数时,您还可以覆盖相同的方式以显示相同的消息。


推荐阅读