Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #92839 > unrolled thread
| Started by | Tony the Tiger <tony@tiger.invalid> |
|---|---|
| First post | 2015-06-18 17:56 +0000 |
| Last post | 2015-06-18 12:55 -0600 |
| Articles | 4 — 3 participants |
Back to article view | Back to comp.lang.python
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
| From | Tony the Tiger <tony@tiger.invalid> |
|---|---|
| Date | 2015-06-18 17:56 +0000 |
| Subject | CLI Arguments That Call Functions? |
| Message-ID | <7DDgx.1121732$LW6.214416@fx09.am4> |
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:
---8<--------------------------------------------------------------
# coding:utf-8
## ~/Programming/Python/CLIMenu $ python --version
## Python 2.7.3
## Author: Pär Smårs, SWEDEN (c) 2015 - GPL License
from argparse import ArgumentParser
class FunctionCaller(object):
'''
The FunctionCaller() object is responsible for calling
functions having the same names as options.
Attributes:
OptionsList List
Methods:
InvokeOptions No attributes
'''
def __init__(self):
self.OptionsList = []
def InvokeOptions(self):
'''
Method to run the options.
'''
# Get the keyword arguments from the Namespace object.
for item in self.OptionsList._get_kwargs():
# Get only arguments which are used.
if item[1]:
# Call the appropriate function.
# Order does not, and should not matter
# once we are here.
# You might, however, want to filter out
# any extra options you use to determine,
# for instance, options order.
globals()[item[0]](item[1])
###-------------------------------------------------------
# Functions to handle options with or without attributes,
# having the same names as the options that call them.
# All functions need to have an attribute value for the
# FunctionCaller() class to work properly, or we will
# have the same problem as before: we need to handle
# exceptions to what comes in. You don't need to handle
# the attribute, however.
def option_alfa(in_attr):
# We get a string value, so convert it to an integer.
in_value = int(in_attr) + 1000
print 'This is Alfa\t{}\n add 1000\t{}'.format(in_attr, in_value)
def option_bravo(in_attr):
# The attibute is not handled here, but there
# has to be one present, or the caller fails.
print 'This is Bravo.'
#---------------------------------------------------------
def main(options):
'''
The main() function that gets to sort out the if's and the
but's of how to create and invoke the function caller.
You might want to pull some options out of the Namespace
object because you might need to make sure they are run first.
'''
opt_handler = FunctionCaller()
opt_handler.OptionsList = options
# Do black magic here, like splitting the options up,
# re-entering the options and run some of them first.
# For instance, you wouldn't want to replace all \'s
# in a string with A's and then look for the presence
# of \n. You'll need to handle that situation in a more
# thought-through manner.
opt_handler.InvokeOptions()
del opt_handler
if __name__ == '__main__':
'''
Add a new parser item, choose a dest name for it and use
the same name for the function you intend to handle the
option.
'''
parser = ArgumentParser(description="Let's handle some options.")
parser.add_argument(
'-a', '--alfa',
action='store',
dest='option_alfa',
help='Test Option A. Takes an integer.')
parser.add_argument(
'-b', '--bravo',
action='store_true',
dest='option_bravo',
default=False,
help='Test Option Bravo. Takes no value, nada.')
# Send the ArgumentParser Namespace object as an argument.
main(parser.parse_args())
---8<--------------------------------------------------------------
Expected output and test command:
~/Programming/Python/CLIMenu $ python climnu.py -ba 123
This is Alfa 123
add 1000 1123
This is Bravo.
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.
/Grrr
--
___ ___
(\_--_/) | _ ._ _|_|_ _ |o _ _ ._
( 9 9 ) |(_)| |\/ |_| |(/_ ||(_|(/_|
stripes are forever - as overripe ferrets
[toc] | [next] | [standalone]
| From | Tony the Tiger <tony@tiger.invalid> |
|---|---|
| Date | 2015-06-18 18:08 +0000 |
| Message-ID | <NODgx.1121733$LW6.127114@fx09.am4> |
| In reply to | #92839 |
On Thu, 18 Jun 2015 17:56:19 +0000, Tony the Tiger wrote:
> I would have assumed [...]
Forgot to add, I don't read or see anything posted from outside of the
groups. Yes, don't bother trying to talk to me if you're on this shitty
"googlegroins" thing, I'll probably hate you anyway.
/Grrr
--
___ ___
(\_--_/) | _ ._ _|_|_ _ |o _ _ ._
( 9 9 ) |(_)| |\/ |_| |(/_ ||(_|(/_|
stripes are forever - as overripe ferrets
[toc] | [prev] | [next] | [standalone]
| From | Michael Torrie <torriem@gmail.com> |
|---|---|
| Date | 2015-06-18 13:10 -0600 |
| Message-ID | <mailman.610.1434654649.13271.python-list@python.org> |
| In reply to | #92841 |
On 06/18/2015 12:08 PM, Tony the Tiger wrote: > Forgot to add, I don't read or see anything posted from outside of the > groups. Posting from the mailing list here. I assume the nntp gateway is two-way. Unless you're manually blocking message originating in google groups, I don't see why you wouldn't pick them up (bad formatting and all) on Usenet. If not, you're not missing anything, nor are we here outside of usenet.
[toc] | [prev] | [next] | [standalone]
| From | Ian Kelly <ian.g.kelly@gmail.com> |
|---|---|
| Date | 2015-06-18 12:55 -0600 |
| Message-ID | <mailman.609.1434654145.13271.python-list@python.org> |
| In reply to | #92839 |
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.
[toc] | [prev] | [standalone]
Back to top | Article view | comp.lang.python
csiph-web