【问题标题】:Python optparse help message formattingPython optparse 帮助消息格式化
【发布时间】:2013-02-07 12:10:57
【问题描述】:

我正在使用 optparse 处理命令行参数,但我遇到了 optparse 帮助消息的多个空格行的问题。

group.add_option(
    '-H',
    '--hostname',
    action='store',
    dest='hostname',
    help='Specify the hostname or service/hostname you want to connect to\
    If specified -f/--hostfile will be ignored',
    metavar='HOSTNAME',)

所以我在帮助消息中的“to”之后得到了几个空格(因为缩进)。

 Specify the hostname or service/hostname you want to connect 
 to                   If specified -f/--hostfile will be ignored

我可以删除帮助消息第二行中的前导空格,但那将是不符合 Python 的。

是否有一些pythonic方法可以删除帮助消息中的空格。

【问题讨论】:

  • 注意:自 python 2.7 版起,不鼓励使用 optparse。 optparse 模块已弃用,不会进一步开发; argparse 模块将继续开发。请参阅PEP 0389 了解更多信息。

标签: python arguments command-line-arguments optparse


【解决方案1】:

如果用括号括起来,可以连接多行字符串。所以你可以这样重写:

group.add_option(
    '-H',
    '--hostname',
    action='store',
    dest='hostname',
    help=('Specify the hostname or service/hostname you want to connect to.  '
          'If specified -f/--hostfile will be ignored'),
    metavar='HOSTNAME',)

【讨论】:

    【解决方案2】:

    Austin Phillips 的回答涵盖了您希望将字符串连接起来的情况。如果您想保留换行符(即,您需要多行帮助字符串)。查看textwrap module。具体来说就是 dedent 函数。

    示例用法:

    >>> from textwrap import dedent
    >>> def print_help():
    ...   help = """\
    ...   Specify the hostname or service/hostname you want to connect to
    ...   If specified -f/--hostfile will be ignored
    ...   Some more multiline text here
    ...   and more to demonstrate"""
    ...   print dedent(help)
    ... 
    >>> print_help()
    Specify the hostname or service/hostname you want to connect to
    If specified -f/--hostfile will be ignored
    Some more multiline text here
    and more to demonstrate
    >>> 
    

    来自文档:

    textwrap.dedent(文本)

    从文本的每一行中删除所有常见的前导空格。

    这可用于使三引号字符串与显示的左边缘对齐,同时仍以缩进形式在源代码中显示它们。

    【讨论】:

      猜你喜欢
      • 2010-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-21
      相关资源
      最近更新 更多