Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #92844

Re: CLI Arguments That Call Functions?

References <7DDgx.1121732$LW6.214416@fx09.am4>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2015-06-18 12:55 -0600
Subject Re: CLI Arguments That Call Functions?
Newsgroups comp.lang.python
Message-ID <mailman.609.1434654145.13271.python-list@python.org> (permalink)

Show all headers | View raw


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.

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

CLI Arguments That Call Functions? Tony the Tiger <tony@tiger.invalid> - 2015-06-18 17:56 +0000
  Re: CLI Arguments That Call Functions? Tony the Tiger <tony@tiger.invalid> - 2015-06-18 18:08 +0000
    Re: CLI Arguments That Call Functions? Michael Torrie <torriem@gmail.com> - 2015-06-18 13:10 -0600
  Re: CLI Arguments That Call Functions? Ian Kelly <ian.g.kelly@gmail.com> - 2015-06-18 12:55 -0600

csiph-web