带有换行的Python argparse.RawTextHelpFormatter

zeg*_*jan 2 python argparse

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

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

Kor*_*rdi 7

编写自定义RawTextHelpFormatter

你可以写自己的RawTextHelpFormatter.该RawTextHelpFormatter只有在方法的差异_fill_text,并_split_linesArgumentDefaultsHelpFormatter这样只是覆盖_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()
Run Code Online (Sandbox Code Playgroud)

产量

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
Run Code Online (Sandbox Code Playgroud)

如您所见,线条会自动包裹.如果要调整宽度,可以在方法中硬编码宽度_textwrap.wrap(text, width)(仅为零件的宽度FOO! Lorem)_spilit_lines或使用_os.environ['COLUMNS'](这是完整帮助文本的宽度).

列数为40的代码

import os
os.environ['COLUMNS'] = "40"
Run Code Online (Sandbox Code Playgroud)

产量

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
Run Code Online (Sandbox Code Playgroud)

带硬编码的代码40

def _split_lines(self, text, width):
    text = self._whitespace_matcher.sub(' ', text).strip()
    return _textwrap.wrap(text, 40)
Run Code Online (Sandbox Code Playgroud)

产量

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
Run Code Online (Sandbox Code Playgroud)

PreserveWhiteSpaces和例如Bulletpoints

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

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]
Run Code Online (Sandbox Code Playgroud)

它只是查看文本文本的缩进,并为每_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()
Run Code Online (Sandbox Code Playgroud)

产量

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   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 and no Enter
                  Ipsum is simply dummy text of the printing and typesetting
                  industry
                  Ipsum is simply dummy text of the printing and typesetting
                  industry
Run Code Online (Sandbox Code Playgroud)