使用argparse时,传递--help给程序会生成帮助文本.不幸的是,它很难阅读,因为选项之间没有空行.这是一个摘录来说明:
optional arguments:
-h, --help show this help message and exit
-u FILENAME, --up-sound FILENAME
The sound to play when the network comes up. Default:
"/path/to/some/sound/file.wav"
-d FILENAME, --down-sound FILENAME
The sound to play when the network goes down. Default:
"/path/to/some/other/sound/file.wav"
-p EXECUTABLE, --player EXECUTABLE
The program to use to play sounds. Default: "play"
-s, --silent If specified, network_monitor.py will not play any
sounds.
-c, --no-clear-screen
If specified, screen will not be cleared (nor extra
blank lines added) before network_monitor.py runs.
--version show program's version number and exit
Run Code Online (Sandbox Code Playgroud)
请注意,在某些情况下,如之间-p和-s之间或-c和--version,这是很难说在帮助文本适用的选项,一目了然.条目之间应该有一个空行.例如:
-p EXECUTABLE, --player EXECUTABLE
The program to use to play sounds. Default: "play"
-s, --silent If specified, network_monitor.py will not play any
sounds.
Run Code Online (Sandbox Code Playgroud)
我怎么能做到这一点?其他几个 问题建议使用.问题是,如果我使用它,我必须编写自己的逻辑来包装帮助文本,因为原始文本帮助格式化程序不进行格式化.显而易见的答案是附加到帮助文本的末尾并使用默认格式化程序.但令人费解的是,新行被剥夺了.argparse.RawTextHelpFormatter'\n\n'
这里前进的方向是什么?我正在使用Python 3.4.
您可以创建自己的帮助文本格式化程序来执行此操作.请注意,这要求您非常具体地了解实现细节argparse.HelpFormatter.因此,请考虑每个帮助格式化程序类型说明中包含的此警告:
只有此类的名称才被视为公共API.该类提供的所有方法都被视为实现细节.
一旦我们忽略了这一点,创建我们自己的帮助格式化程序,在条目之间添加一个空行非常简单:
class BlankLinesHelpFormatter (argparse.HelpFormatter):
def _split_lines(self, text, width):
return super()._split_lines(text, width) + ['']
Run Code Online (Sandbox Code Playgroud)
就是这样.现在,当您ArgumentParser在传递
formatter_class=BlankLinesHelpFormatter给构造函数时创建对象时,帮助文本中的每个参数之间将出现空白行.
| 归档时间: |
|
| 查看次数: |
810 次 |
| 最近记录: |