2012-06-07 17 views
25

我在學習如何使用python的​​模塊。目前我的Python腳本是:使用argparse模塊打印程序使用示例

parser = argparse.ArgumentParser(description='My first argparse attempt', 
           add_help=True) 
parser.add_argument("-q", action ="store", dest='argument', 
        help="First argument") 
output = parser.parse_args() 

,並讓輸出爲:

usage: test.py [-h] [-q ARGUMENT] 

My first argparse attempt 

optional arguments: 
    -h, --help show this help message and exit 
    -q ARGUMENT First argument 

現在,讓我們假設我要我的-h or --help參數打印usage example也。像,

Usage: python test.py -q "First Argument for test.py" 

我的目的是打印與-h參數的默認內容沿着上述使用示例,使用戶可以得到如何使用test.py python腳本一個基本思路。

因此,​​模塊內置此功能。如果不是,解決這個問題的正確方法是什麼。

回答

34

使用parser.epilog在生成的-h文本後面顯示一些內容。

parser = argparse.ArgumentParser(
    description='My first argparse attempt', 
    epilog='Example of use') 

output = parser.parse_args() 

打印:

My first argparse attempt 

optional arguments: 
    -h, --help show this help message and exit 

Example of use 
+0

感謝您的回答。 – RanRag

+17

@Noob - 請注意,空白符將從您的描述和epilog中去除(這通常不適用於「使用示例」。爲了讓您希望使用'argparse.RawDescriptionHelpFormatter'(http://docs.python.org /dev/library/argparse.html#argparse.RawDescriptionHelpFormatter) – mgilson

+1

有沒有一種方法使用argparse.RawDescriptionHelpFormatter僅用於epilog而不用於描述?我想將描述自動包裝,但我想照顧尾聲的格式。 – user2015487