极端挑剔的问题,但令我烦恼的是默认的argparse帮助消息是一个句子片段。例如,对于包含
的脚本#!/usr/bin/env python
import argparse
parser = argparse.ArgumentParser()
parser.parse_args()
-h
和--help
标志消息显示:
$ tmp.py --help
usage: tmp.py [-h]
optional arguments:
-h, --help show this help message and exit
但是我更喜欢文档中的完整句子和标题的“句子大小写”:
$ tmp.py --help
Usage: tmp.py [-h]
Optional arguments:
-h, --help Show this help message and exit.
如何保持script -h
和script --help
的行为但更改消息?
Welp在5秒后找到了答案。
#!/usr/bin/env python
import argparse
parser = argparse.ArgumentParser(add_help=False)
parser.parse_args()
parser.add_argument(
'-h', '--help', action='help', help='Show this help message and exit.')
定义您自己的action='help'
参数可能是最好的答案。但是可以编辑默认的help
。
所有定义的动作都收集在parser._actions
列表中。是的,它被标记为隐藏,但是人们可以根据需要进行访问。通常,help
操作是第一个创建的操作(默认情况下),因此它是该列表的元素[0]
。
In [15]: parser._actions[0].help
Out[15]: 'show this help message and exit'
In [16]: parser._actions[0].help = "Show this help message and exit."
测试:
In [17]: parser.print_help()
usage: ipython3 [-h] {mySubcommand,m} ...
positional arguments:
{mySubcommand,m} sub-command help
mySubcommand (m)
Subcommand help
optional arguments:
-h, --help Show this help message and exit.
def main():
parser = argparse.ArgumentParser()
# specific file
parser.add_argument('-f', '--file', type=str, default='file',
help=Fore.BLUE + '--file access_log -extract-ip' + Style.RESET_ALL)
# http get file
parser.add_argument('-hgf', '--http-get-file', type=str, default='http-get-file',
help=Fore.BLUE + '--http-get-file URL' + Style.RESET_ALL)