python - 如何显示自定义消息而不是 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 提供我的自定义消息?
解决方案
您需要覆盖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()
当用户滥用任何提供的参数时,您还可以覆盖相同的方式以显示相同的消息。
推荐阅读
- amazon-web-services - 使用 Bitbucket 管道将网站持续部署到 AWS S3
- tensorflow - 如何在 Keras 中使用 Convolutional LSTM 实现位置估计?
- python - 如何通过在重复后添加数字 a 来管理 .unstack() ValueError
- javascript - 画布显示但图像不呈现
- javascript - 将 html div 添加到数组中
- reactjs - react-custom-scrollbars 动态内容滚动
- java - 带有 Angular 5 的 Java Selenium
- ios - 我可以将 WatchKit 扩展添加到通用应用程序吗?
- 3d - 三 JS - 直接在相机前面获取地面位置
- java - 带有 CORS 的 Spring Boot HTTPS,Angular 5 将所有请求加倍