0

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

ヘルプメッセージの2行目の先頭の空白を削除することはできますが、それは非Pythonです。

ヘルプメッセージの空白を削除するためのPythonの方法はありますか?

4

2 に答える 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',)
于 2013-02-22T00:17:25.570 に答える
0

Austin Phillips の答えは、文字列を連結したい場合をカバーしています。そこに改行を残したい場合 (つまり、複数行のヘルプ文字列が必要な場合)。textwrap モジュールをチェックしてください。具体的には、デデント機能。

使用例:

>>> 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(テキスト)

テキストのすべての行から共通の先頭の空白を削除します。

これを使用して、三重引用符で囲まれた文字列をディスプレイの左端に揃え、ソース コードではインデント形式で表示することができます。

于 2013-02-22T00:28:15.863 に答える