2013-02-22 53 views
0

我正在使用optparse來處理命令行參數,並且我正在運行optparse幫助消息的多個空行的問題。Python 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',) 

所以我「到」在幫助信息(因爲壓痕)後得到一對夫婦在幫助信息的空間。

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

我可以刪除幫助消息的第二行中的主要空格,但這將是unpythonic。

是否有一些pythonic方法來刪除幫助消息中的空格。

+0

**注意**:自從python版本2.7以後,不鼓勵使用* optparse *。 optparse模塊已棄用,不會進一步開發;開發將繼續使用* argparse *模塊。有關更多信息,請參見[PEP 0389](http://www.python.org/dev/peps/pep-0389/)。 – shakaran 2013-04-03 23:32:59

回答

0

奧斯汀菲利普斯的答案涵蓋了你想要你的字符串連接的情況。如果你想保留換行符(即你想要多行幫助字符串)。檢查出textwrap module。具體來說,這個縮進函數。

實例:

>>> 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(文本)

從文本中每行中刪除任何共同前導空白。

這可以用來使三引號字符串與顯示的左邊緣對齊,同時仍以縮進的形式將它們呈現在源代碼中。

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