Python optparse 帮助信息格式化

0 投票
2 回答
2103 浏览
提问于 2025-04-17 16:42

我正在使用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的风格。

有没有什么更符合Python风格的方法来去掉帮助信息中的空格呢?

2 个回答

3

多行字符串可以通过括号连接在一起。所以你可以这样重写:

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',)
0

Austin Phillips的回答讲的是当你想把字符串连接在一起的情况。如果你想保留换行符(也就是说,你想要多行的帮助字符串),可以看看textwrap模块。特别是里面的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(text)

这个函数会去掉文本中每一行前面共同的空白部分。

这样可以让用三重引号括起来的字符串在显示时左对齐,同时在源代码中仍然保持缩进的样子。

撰写回答