2014-10-29 70 views
0

我正在嘗試使用​​庫爲我的python腳本編寫用法/幫助。python的參數解析器以大寫字母打印參數名稱

這是我的示例代碼:

import argparse 
parser = argparse.ArgumentParser(
     description='My description') 

parser.add_argument(
     "-r", "--remote", 
     help="help message") 

parser.print_help() 

輸出:

usage: [-h] [-r REMOTE] 

My description 

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

我不知道爲什麼它是打印在上面的輸出-r--remote開關後REMOTE

任何人都可以告訴我我在這裏做錯了什麼,或者我應該怎麼做才能擺脫它?

回答

1

您正在查看的metavar;它從選項字符串自動生成以形成佔位符。它告訴用戶他們需要填寫一個值。

您可以用metavar keyword argument設置明確的metavar值:

ArgumentParser產生幫助信息,它需要一些辦法請參閱各期望的參數。默認情況下,ArgumentParser對象使用dest值作爲每個對象的「名稱」。默認情況下,對於位置參數操作,dest值直接使用,對於可選參數操作,dest值是大寫的。

你可以看到它,因爲你的參數需要一個值;如果您希望它是一個切換,請使用action='store_true';在這種情況下,除非用戶指定了交換機,否則該選項默認爲False。後者的

演示:

>>> import argparse 
>>> parser = argparse.ArgumentParser(
...   description='My description') 
>>> parser.add_argument("-r", "--remote", action='store_true', help="help message") 
_StoreTrueAction(option_strings=['-r', '--remote'], dest='remote', nargs=0, const=True, default=False, type=None, choices=None, help='help message', metavar=None) 
>>> parser.print_help() 
usage: [-h] [-r] 

My description 

optional arguments: 
    -h, --help show this help message and exit 
    -r, --remote help message 
>>> opts = parser.parse_args([]) 
>>> opts.remote 
False 
>>> opts = parser.parse_args(['-r']) 
>>> opts.remote 
True 
+0

謝謝。通過設置'Metavar =「」'明確地解決了我的問題。我不想給'action = store_true',因爲我想在腳本中使用-r之後的值。 – RBH 2014-10-29 09:54:18

0

你缺少action

import argparse 
parser = argparse.ArgumentParser(
     description='My description') 

parser.add_argument(
     "-r", "--remote", action="store_true", # add action 
     help="help message") 

parser.print_help() 
usage: -c [-h] [-r] 

My description 

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