Python argparse:预格式化帮助文本?

发布于 2024-10-06 02:28:26 字数 123 浏览 0 评论 0原文

我正在使用 argparse,我想在我的选项之一的帮助文本中显示一个列表。但是,argparse 会从文本中删除新行并将其显示在一行上。

是否有办法告诉 argparse 帮助字符串已预先格式化,而不是删除新行字符?

I'm using argparse and I want to display a list in the help text of one of my options. However, argparse strips new lines from the text and displays it on a single line.

Is there anyway to tell argparse that the help string is preformatted, and not to strip new line characters?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

苹果你个爱泡泡 2024-10-13 02:28:26

来自 文档

RawTextHelpFormatter 维护
各种帮助文本的空白
包括参数描述。

from argparse import RawTextHelpFormatter
parser = ArgumentParser(description='test', formatter_class=RawTextHelpFormatter)

From the docs:

RawTextHelpFormatter maintains
whitespace for all sorts of help text
including argument descriptions.

from argparse import RawTextHelpFormatter
parser = ArgumentParser(description='test', formatter_class=RawTextHelpFormatter)
耳钉梦 2024-10-13 02:28:26

如果您只想覆盖一个选项,则不能使用 RawTextHelpFormatter。相反,子类化 HelpFormatter 并为应“原始”处理的选项提供特殊介绍(我使用 “R|rest of help”):

import argparse

class SmartFormatter(argparse.HelpFormatter):

    def _split_lines(self, text, width):
        # this is the RawTextHelpFormatter._split_lines
        if text.startswith('R|'):
            return text[2:].splitlines()  
        return argparse.HelpFormatter._split_lines(self, text, width)

并使用它:

from argparse import ArgumentParser
from textwrap import dedent

parser = ArgumentParser(description='test')

parser.add_argument('--list', help=dedent("""\
    R|abc
      def
        ghi
"""))
parser.parse_args()

任何其他对 .add_argument() 的调用(帮助信息不以 R| 开头)将照常包装。

这是我对 argparse 的改进的一部分。完整的 SmartFormatter 还支持添加
默认为所有选项以及实用程序描述的原始输入。

If you just want to override the one option, you cannot use RawTextHelpFormatter. Instead subclass the HelpFormatter and provide a special intro for the options that should be handled "raw" (I use "R|rest of help"):

import argparse

class SmartFormatter(argparse.HelpFormatter):

    def _split_lines(self, text, width):
        # this is the RawTextHelpFormatter._split_lines
        if text.startswith('R|'):
            return text[2:].splitlines()  
        return argparse.HelpFormatter._split_lines(self, text, width)

And use it:

from argparse import ArgumentParser
from textwrap import dedent

parser = ArgumentParser(description='test')

parser.add_argument('--list', help=dedent("""\
    R|abc
      def
        ghi
"""))
parser.parse_args()

Any other calls to .add_argument() where the help does not start with R| will be wrapped as normal.

This is part of my improvements on argparse. The full SmartFormatter also supports adding
the defaults to all options, and raw input of the utilities description.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文