2016-11-04 78 views
1

我用argparse來處理輸入參數,它輸出與parser.print_help()以下:argparse添加例如使用

optional arguments: 
    -h, --help   show this help message and exit 
    -t TEMPLATES, --templates TEMPLATES 
        template names to make, should be defined as section 
        name in conf, and have related file in templates/ 
        folder 
    -c CONFPATH, --confpath CONFPATH 
        configuration path for template detail info 

我的代碼如下所示:

import argparse 
    parser = argparse.ArgumentParser(prog='base_maker', description='template maker') 
    parser.add_argument('-t', '--templates', help='template names to make, should be defined as section name in conf, and have related file in templates/ folder', type=str) 
    parser.add_argument('-c', '--confpath', help='configuration path for template detail info', type=str, default=os.path.join(basepath, 'conf/maker.conf')) 

然而,我想補充有關如何使用-t /一個詳細的例子 - 模板一樣(在例如添加部分):

optional arguments: 
    -h, --help   show this help message and exit 
    -t TEMPLATES, --templates TEMPLATES 
        template names to make, should be defined as section 
        name in conf, and have related file in templates/ 
        folder 
    -c CONFPATH, --confpath CONFPATH 
        configuration path for template detail info 

example: 

    python test.py -t template/test.py 
    python test.py -t template/test -c conf/test.conf 
    python test.py -t test.py 

我不知道應該使用哪個屬性來添加「示例」部分,我檢查了Print program usage example with argparse modulen,但是當我檢查epilog in the official doc時,我不清楚和沒有詳細示例。

任何人都可以給我一個關於如何實現的例子嗎?謝謝

+0

您是否嘗試過使用上述'epilog'?它出什麼問題了? – DeepSpace

+1

是的,但如何改變它內部的線,我想有多行的解釋,然後我想知道是否有更好的方法 – linpingta

+0

你有沒有嘗試傳遞''「」多行字符串「」「'來'epilog'?我猜想這樣做會發生,換行符會被保留。你可以保持整潔,因爲我展示[這裏](http://codereview.stackexchange.com/a/60369/32391)。 – jonrsharpe

回答

3

如果您希望在末尾打印示例(epilog)並保留空格/格式(formatter_class設置爲RawDescriptionHelpFormatter),則需要使用epilog和formatter_class參數到ArgumentParser。

通過修改你上面的例子舉例:

import argparse 

example_text = '''example: 

python test.py -t template/test.py 
python test.py -t template/test -c conf/test.conf 
python test.py -t test.py''' 

parser = argparse.ArgumentParser(prog='base_maker', 
           description='template maker', 
           epilog=example_text, 
           formatter_class=argparse.RawDescriptionHelpFormatter) 

parser.add_argument('-t', '--templates', help='template names to make, should be defined as section name in conf, and have related file in templates/ folder', type=str) 
parser.add_argument('-c', '--confpath', help='configuration path for template detail info', type=str, default=os.path.join(basepath, 'conf/maker.conf')) 
+0

準確,謝謝,它需要formatter_class設置:) – linpingta