I'm trying to parse the arguments passed to a script and execute functionality on the fly
#!/usr/bin/python
import sys
from argparse import ArgumentParser
def method_a(sometext):
print 'a -- {0}'.format(sometext)
def method_b(sometext):
print 'b -- {0}'.format(sometext)
parser = ArgumentParser(description='A or B')
parser.add_argument('--sometext',
dest='sometext',
required=False,
default=None)
option_group = parser.add_mutually_exclusive_group(required=True)
option_group.add_argument('-a',
dest='cmd',
action='store_const',
const=lambda: method_user(parser.sometext))
option_group.add_argument('--list',
'-l',
dest='cmd',
action='store_const',
const=lambda: method_list(parser.sometext))
args = parser.parse_args(sys.argv[1:])
args.cmd()
This unforunately throws the exception:
Traceback (most recent call last):
File "test.py", line 39, in <module>
args.cmd()
File "test.py", line 34, in <lambda>
const=lambda: method_list(parser.sometext),
AttributeError: 'ArgumentParser' object has no attribute 'sometext'
Is it possible to access the value passed to sometext while parsing later arguments? I'd like to pass the value captured in sometext to the methods being run inside the const field for the mutually exclusive group.
As a side question: is the keyword lambda required in the above example? Or will it execute the method regardless.. I'd use the lambda in a similar example below, but again, is this even required?
switch = {0: lambda: sys.exit(),
1: lambda: method_a('sometext'),
2: lambda: method_b('sometext')}
index = int(raw_input('Make a selection'))
switch.get(index)()