【问题标题】:How to display a custom message instead of the default help message which Argparse generates?如何显示自定义消息而不是 Argparse 生成的默认帮助消息?
【发布时间】:2019-08-06 05:57:11
【问题描述】:

考虑以下示例代码

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 提供我的自定义消息?

【问题讨论】:

标签: python python-3.x argparse


【解决方案1】:

您需要覆盖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")

现在,您将调用MyArgumentParser,而不是调用ArgumentParser

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(),以在用户滥用任何提供的参数时显示相同的消息。

【讨论】:

    猜你喜欢
    • 2016-06-21
    • 2015-07-26
    • 2016-01-01
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    • 2012-08-17
    • 2013-09-10
    • 2021-09-16
    相关资源
    最近更新 更多