考虑以下示例代码
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 提供自定义消息?
最佳答案
您需要重写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()
,以便在用户误用任何提供的参数时显示相同的消息。
关于python - 如何显示自定义消息而不是 Argparse 生成的默认帮助消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57369719/