2013-07-09 19 views
0

我使用一些從this answer代碼,特別是部分的,其提出了一個argparse.ArgumentTypeError獲取參數,而不是dest的名稱()

raise argparse.ArgumentTypeError(
       "argument '{f}' requires between {nmin} and {nmax} " 
       "arguments".format(f=self.dest, nmin=nmin, nmax=nmax)) 

不過,我也上漲在append動作行爲到我的子類'__call__(),這意味着這些重複的參數中的一個或多個可能格式不正確,並可能引發ArgumentTypeError

所以,當我使用這個對於這樣的參數在解析器:

parse = argparse.ArgumentParser() 
parser.add_argument("-a", "--append-arg", action=append_range(2,3), default=[]) 

我打字錯誤的參數個數得到一個錯誤,我得到的是這樣的:

argparse.ArgumentTypeError: argument 'append_arg' requires between 2 and 3 arguments 

太好了,那就是我希望它被使用的方式。但是現在參數列表在命名空間中被命名爲append_arg。我希望它被命名爲list_of_repeated_args或其他。所以,如果我做的:

parser.add_argument("-a", "--append-arg", action=append_range(2,3), default=[], dest="list_of_repeated_args") 

然後我得到這個的錯誤,而不是:

argparse.ArgumentTypeError: argument 'list_of_repeated_args' requires between 2 and 3 arguments 

這不是我想要的。當然,我可以改變函數,把我想要的名字作爲參數,但是我想只是自動使用這個名字。有沒有辦法做到這一點? (即,我應該放置什麼來代替f=self.dest?)

回答

0

找出解決方案。定製argparse.Action__call__()方法具有option_string參數,而根據the docs,是:

這是用於調用該操作選項字符串。 option_string參數是可選的,如果該動作與位置參數關聯,則該參數將不存在。

果然,如果我改變了下面的代碼使用option_string代替

raise argparse.ArgumentTypeError(
       "argument '{f}' requires between {nmin} and {nmax} " 
       "arguments".format(f=option_string, nmin=nmin, nmax=nmax)) 

我得到(假設我使用縮寫形式)的預期效果:

argparse.ArgumentTypeError: argument '-a' requires between 2 and 3 arguments