我需要根据给定的字符串创建自定义对象的实例(下例中的 Bar)。如果我不将类型更改为Bar
并运行以下代码:
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()
将无效参数传递给时,我得到了这个相当不错的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
这看起来很糟糕。我知道这是由于在检查可用选项之前发生了类型转换。处理这种情况的最佳方法是什么?