These lines work:
parser = argparse.ArgumentParser(prog='PROG')
parser.add_argument('foo', nargs='+', type=lambda x:x.split('/'))
parser.parse_args(['3/5', '4/6']) # output Namespace(foo=[['3', '5'], ['4', '6']])
But the following don't. Why?
The only difference is that this time the type caster uses a list comprehension to convert strings to integers.
parser = argparse.ArgumentParser(prog='PROG')
parser.add_argument('foo', nargs='+', type=lambda x:[[int(a), int(b)] for a,b in x.split('/')])
parser.parse_args(['3/5', '4/6']) # Raise error: argument foo: invalid <lambda> value: '3/5'
Basically, what you're trying to do here is
for a, b in '3/5'.split('/')...
which is a ValueError ("not enough values to unpack"). argparse
hides actual errors and responds with a generic ArgumentError
if there's anything wrong with your type
function. You might want to use an actual def
instead to debug it:
def test(x):
try:
return [[int(a), int(b)] for a,b in x.split('/')]
except Exception as e:
print(e)
parser = argparse.ArgumentParser(prog='PROG')
parser.add_argument('foo', nargs='+', type=test)
parser.parse_args(['3/5', '4/6'])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.