2012-04-24 28 views
2

我需要根據給定的字符串創建自定義對象(下例中的Bar)的實例。如果我類型更改爲Bar並運行下面的代碼:使用帶有argparse的自定義類型時的正常參數錯誤

import argparse 

VALID_BAR_NAMES = ['alfa', 'beta', 'gamma', 'delta'] 


class Bar: 

    def __init__(self, name): 
     if not name in VALID_BAR_NAMES: 
      raise RuntimeError('Bar can not be {n}, ' 
           'it must be one of {m}'.format(
            n=name, m=', '.join(VALID_BAR_NAMES))) 
     self.name = name 


if __name__ == '__main__': 
    parser = argparse.ArgumentParser() 

    parser.add_argument('foo', help='Specify the foo!') 

    parser.add_argument('-b', '--bar', nargs='*', 
         choices=VALID_BAR_NAMES, 
         type=str, # SELECTED TYPE 
         help=('Specify one or many valid bar(s)')) 
    parsed_arguments = parser.parse_args() 

我得到傳遞了無效argment當這相當不錯的輸出hello-b

usage: Example.py [-h] 
        [-b [{alfa,beta,gamma,delta} [{alfa,beta,gamma,delta} ...]]] 
        foo 
Example.py: error: argument -b/--bar: invalid choice: 'hello' (choose from 'alfa', 'beta', 'gamma', 'delta') 

但是,如果我將type=str更改爲type=Bar並再次運行該示例我得到以下輸出:

Traceback (most recent call last): 
    File "C:\PyTest\Example.py", line 25, in <module> 
    parsed_arguments = parser.parse_args() 
    File "C:\Python27\lib\argparse.py", line 1688, in parse_args 
    args, argv = self.parse_known_args(args, namespace) 
    File "C:\Python27\lib\argparse.py", line 1720, in parse_known_args 
    namespace, args = self._parse_known_args(args, namespace) 
    File "C:\Python27\lib\argparse.py", line 1926, in _parse_known_args 
    start_index = consume_optional(start_index) 
    File "C:\Python27\lib\argparse.py", line 1866, in consume_optional 
    take_action(action, args, option_string) 
    File "C:\Python27\lib\argparse.py", line 1778, in take_action 
    argument_values = self._get_values(action, argument_strings) 
    File "C:\Python27\lib\argparse.py", line 2218, in _get_values 
    value = [self._get_value(action, v) for v in arg_strings] 
    File "C:\Python27\lib\argparse.py", line 2233, in _get_value 
    result = type_func(arg_string) 
    File "C:\PyTest\Example.py", line 12, in __init__ 
    n=name, m=', '.join(VALID_BAR_NAMES))) 
RuntimeError: Bar can not be hello, it must be one of alfa, beta, gamma, delta 

看起來很糟糕。我知道這是由於之前的發生的類型轉換,因爲可用的選擇已完成。處理這個問題的最好方法是什麼?

回答

2

您需要創建一個自定義操作(未經測試):

class Bar: 
    ... 


class BarAction(argparse.Action): 
    def __call__(self,parser,namespace,values,option_string=None): 
     try: #Catch the runtime error if it occures. 
      l=[Bar(v) for v in values] #Create Bars, raise RuntimeError if bad arg passed. 
     except RuntimeError as E: 
      #Optional: Print some other error here. for example: `print E; exit(1)` 
      parser.error() 

     setattr(namespace,self.dest,l) #add the list to the namespace 

... 
parser.add_argument('-b', '--bar', nargs='*', 
        choices=VALID_BAR_NAMES, 
        action=BarAction, # SELECTED TYPE -- The action does all the type conversion instead of the type keyword. 
        help=('Specify one or many valid bar(s)')) 

... 
+2

除'parser.error()'還考慮'提高argparse.ArgumentError(self,「你的專用錯誤信息在這裏」)。 'self'與'__call__'中的object是'self',它是當前的參數對象。 – cfi 2012-08-28 08:10:19

1

將參數保留爲字符串,直到解析完成。解析完成後,首先將它們轉換爲域對象。

+0

該解決方案將是如果有一種方法可以調用argparse並將其用於錯誤輸出以防從字符串轉換爲域對象失敗,則可以進行改進。如果您知道這種方式,請將其作爲單獨(更好)的答案發布。 – Deleted 2012-04-24 12:42:19

+0

請參閱下面的答案。 – mgilson 2012-04-24 13:29:07

0

不知道是否有幫助,但我看着argparse.FileType作爲參考:

class Bar: 
    def __call__(self, strting): 
     if not name in VALID_BAR_NAMES: 
      raise argparse.ArgumentError(None,'Bar can not be {n}, ' 
           'it must be one of {m}'.format(
            n=name, m=', '.join(VALID_BAR_NAMES))) 
     self.name = string 

    def __init__(self): 
     pass 

    def __repr__(self): 
     return name 

parser.add_argument('-b', '--bar', nargs='*', 
        choices=VALID_BAR_NAMES, 
        type=Bar(), # SELECTED TYPE 
        help=('Specify one or many valid bar(s)')) 
相關問題