带有换行的Python argparse.RawTextHelpFormatter

时间:2016-03-10 13:12:08

标签: python argparse

在我解析代码的论证中,我需要使用argparse.RawTextHelpFormatter,但我也希望以与默认格式化程序相同的方式将行自动换行为固定宽度。

如何将这两种行为结合起来有什么优雅的方法吗?

1 个答案:

答案 0 :(得分:7)

编写自定义RawTextHelpFormatter

您可以自己编写RawTextHelpFormatterRawTextHelpFormatter与[{1}}方法_fill_text_split_lines之间只有差异,因此只需覆盖ArgumentDefaultsHelpFormatter方法就可以修复此问题。

_spilt_lines_

输出

import argparse
import textwrap as _textwrap

class LineWrapRawTextHelpFormatter(argparse.RawDescriptionHelpFormatter):
    def _split_lines(self, text, width):
        text = self._whitespace_matcher.sub(' ', text).strip()
        return _textwrap.wrap(text, width)


parser = argparse.ArgumentParser(
    prog='PROG',
    formatter_class=LineWrapRawTextHelpFormatter)
parser.add_argument('--foo', type=int, default=42, help="FOO! Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an u")
parser.add_argument('bar', nargs='*', default=[1, 2, 3], help="BAR! FOO! Lorem Ipsum is simply dummy text of the printing and typesetting industry.")
parser.print_help()

如您所见,该行会自动换行。如果要调整宽度,可以使用usage: PROG [-h] [--foo FOO] [bar [bar ...]] positional arguments: bar BAR! FOO! Lorem Ipsum is simply dummy text of the printing and typesetting industry. optional arguments: -h, --help show this help message and exit --foo FOO FOO! Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an u 方法对_textwrap.wrap(text, width)(仅限FOO! Lorem部分的宽度)的宽度进行硬编码,或使用_spilit_lines (这是完整帮助文本的宽度)。

代码列= 40

_os.environ['COLUMNS']

<强>输出

import os
os.environ['COLUMNS'] = "40"

使用硬编码40的代码

usage: PROG [-h] [--foo FOO]
            [bar [bar ...]]

positional arguments:
  bar         BAR! FOO! Lorem Ipsum is
              simply dummy text of the
              printing and typesetting
              industry.

optional arguments:
  -h, --help  show this help message
              and exit
  --foo FOO   FOO! Lorem Ipsum is
              simply dummy text of the
              printing and typesetting
              industry. Lorem Ipsum
              has been the industry's
              standard dummy text ever
              since the 1500s, when an
              u

<强>输出

def _split_lines(self, text, width):
    text = self._whitespace_matcher.sub(' ', text).strip()
    return _textwrap.wrap(text, 40)

PreserveWhiteSpaces,例如Bulletpoints

如果你想保留换行符前面的空白,我只写了一个PreserveWhiteSpaceWrapRawTextHelpFormatter。

usage: PROG [-h] [--foo FOO] [bar [bar ...]]

positional arguments:
  bar         BAR! FOO! Lorem Ipsum is simply dummy
              text of the printing and typesetting
              industry.

optional arguments:
  -h, --help  show this help message and exit
  --foo FOO   FOO! Lorem Ipsum is simply dummy text of
              the printing and typesetting industry.
              Lorem Ipsum has been the industry's
              standard dummy text ever since the

它只是查看文本文本的缩进,并为每个import argparse import textwrap as _textwrap import re class PreserveWhiteSpaceWrapRawTextHelpFormatter(argparse.RawDescriptionHelpFormatter): def __add_whitespace(self, idx, iWSpace, text): if idx is 0: return text return (" " * iWSpace) + text def _split_lines(self, text, width): textRows = text.splitlines() for idx,line in enumerate(textRows): search = re.search('\s*[0-9\-]{0,}\.?\s*', line) if line.strip() is "": textRows[idx] = " " elif search: lWSpace = search.end() lines = [self.__add_whitespace(i,lWSpace,x) for i,x in enumerate(_textwrap.wrap(line, width))] textRows[idx] = lines return [item for sublist in textRows for item in sublist] 行添加此内容。用这个参数调用。

_textwrap.warp

<强>输出

parser = argparse.ArgumentParser(
    prog='PROG',
    formatter_class=PreserveWhiteSpaceWrapRawTextHelpFormatter)
parser.add_argument('--foo', type=int, default=42, help="""Just Normal Bullet Point with Some Enter in there

    1. Lorem Ipsum has been the industry's standard dummy text ever since
    2. the 1500s, when an u
    3. Lorem Ipsum is simply dummy text of the printing and typesetting industry

Some other Bullet POint

    - Ipsum is simply dummy text of the printing and typesetting industry
    - Ipsum is simply dummy text of the printing and typesetting industry

And No BulletPoint
    Ipsum is simply dummy text of the printing and typesetting industry
    Ipsum is simply dummy text of the printing and typesetting industry
    """)
parser.add_argument('bar', nargs='*', default=[1, 2, 3], help="BAR! FOO! Lorem Ipsum is simply dummy text of the printing and typesetting industry.")
parser.print_help()