【问题标题】:Python argparse: Insert blank line between help entriesPython argparse:在帮助条目之间插入空行
【发布时间】:2015-06-11 15:04:27
【问题描述】:

使用 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

请注意,在某些情况下,例如在-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.

我怎样才能做到这一点? Severalother问题推荐使用argparse.RawTextHelpFormatter。问题在于,如果我使用它,我必须编写自己的逻辑来包装帮助文本,因为原始文本帮助格式化程序不进行格式化。显而易见的答案是将'\n\n' 附加到帮助文本的末尾并使用默认格式化程序。但莫名其妙地,换行符被剥离了。

这里的前进方向是什么?我正在使用 Python 3.4。

【问题讨论】:

    标签: python argparse


    【解决方案1】:

    您可以创建自己的帮助文本格式化程序来执行此操作。请注意,这要求您非常具体地了解argparse.HelpFormatter 的实现细节。因此,请考虑包含在每个帮助格式化程序类型描述中的这个警告:

    只有这个类的名称被认为是公共 API。该类提供的所有方法都被视为实现细节。

    一旦我们忽略了这一点,创建我们自己的帮助格式化程序,在条目之间添加一个空行就非常简单了:

    class BlankLinesHelpFormatter (argparse.HelpFormatter):
        def _split_lines(self, text, width):
            return super()._split_lines(text, width) + ['']
    

    就是这样。现在,当您在将 formatter_class=BlankLinesHelpFormatter 传递给构造函数的同时创建ArgumentParser 对象时,帮助文本中的每个参数之间将出现空行。

    【讨论】:

    • 正是我想要的。谢谢。你认为这种情况在未来发生的几率是多少?
    • source file 过去并没有那么频繁地被触动,而且大部分更改对界面没有影响。因此,尽管有警告,但我会说您在很长一段时间内都很好。另外,通过调用基本方法,我的解决方案不会依赖太多,也不会重新发明任何将来可能会中断的逻辑。
    【解决方案2】:

    poke's 方法很好。注意RawTextHelpFormatter也修改了这个方法,简化为:

    def _split_lines(self, text, width):
        return text.splitlines()
    

    poke's 方法可以调整以提供更多控制权

    class BlankLinesHelpFormatter (argparse.HelpFormatter):
        # add empty line if help ends with \n
        def _split_lines(self, text, width):
            lines = super()._split_lines(text, width)
            if text.endswith('\n'):
                lines += ['']
            return lines
    

    有了这个:

    parser = argparse.ArgumentParser(description='A description',
        formatter_class=BlankLinesHelpFormatter,
        epilog='Epilog line',
        )
    parser.add_argument('-u', '--up-sound', metavar='FILENAME',
        help='The sound to play when the network comes up. Default:"%(default)s"\n',
        default="/path/to/some/sound/file.wav")
    # note \n in above help
    parser.add_argument('-d', '--down-sound', metavar='FILENAME',
        help='The sound to play when the network goes down. Default:"%(default)s"',
        default="/path/to/some/other/sound/file.wav")
    parser.add_argument('-s','--silent', action='store_true',
        help='If specified, network_monitor.py will not play any sounds.')
    parser.add_argument('positional', nargs='*', help='positional argument')
    parser.print_help()
    

    显示:

    usage: stack29484443.py [-h] [-u FILENAME] [-d FILENAME] [-s]
                            [positional [positional ...]]
    
    A description
    
    positional arguments:
      positional            positional argument
    
    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"
      -s, --silent          If specified, network_monitor.py will not play any
                            sounds.
    
    Epilog line
    

    供参考,默认_split_lines为:

    def _split_lines(self, text, width):
        text = self._whitespace_matcher.sub(' ', text).strip()
        return _textwrap.wrap(text, width)
        # self._whitespace_matcher = _re.compile(r'\s+')
    

    这将删除最后的 \n 并将所有内部空格减少为一个空白。

    【讨论】:

      猜你喜欢
      • 2013-03-09
      • 2011-04-20
      • 1970-01-01
      • 2017-04-04
      • 2015-06-19
      • 2011-05-06
      • 2016-03-24
      • 2015-05-20
      相关资源
      最近更新 更多