On Thu, Jun 18, 2015 at 11:56 AM, Tony the Tiger tony@tiger.invalid wrote:
I would have assumed there would be something built in to the
ArgumentParser, but I can't detect anything that seems to do what I want,
so I wrote the following:
[SNIP]
So, is there something already in the Python libs? Do I continue with
this? Or what?
There ought to be something already built in to Python, but I think I've
missed it. Sure hope so. I'd hate to continue with this mess.
You can specify custom actions for arguments. See
https://docs.python.org/3.4/library/argparse.html#action-classes
For example (untested):
class AppendCallable(argparse.Action):
def __call__(self, parser, namespace, values, option_string):
callables = getattr(namespace, self.dest, None) or []
callables.append(functools.partial(self.const, *values))
setattr(namespace, self.dest, callables)
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'-a', '--alfa',
action=AppendCallable,
const=option_alfa,
dest='callables',
nargs=1,
type=int)
parser.add_argument(
'-b', '--bravo',
action=AppendCallable,
const=option_bravo,
dest='callables',
nargs=0)
args = parser.parse_args()
for callable in args.callables:
callable()
You might also be interested in reading
https://docs.python.org/3.4/library/argparse.html#sub-commands in case
that's related to what you're trying to accomplish.
--
https://mail.python.org/mailman/listinfo/python-list