Yet Another Command Line Parser
Ian Bicking
ianb at colorstudy.com
Tue Oct 26 16:54:30 EDT 2004
Manlio Perillo wrote:
> Regards.
> In the standard library there are two modules for command line
> parsing: optparse and getopt.
> In the Python Cookbook there is another simple method for parsing,
> using a docstring.
>
> However sometimes (actually, in all my small scripts) one has a simple
> function whose arguments are choosen on the command line.
>
> For this reason I have written a simple module, optlist, that parses
> the command line as it was a function's argument list.
>
> It is more simple to post an example:
>
>
> import optlist
>
>
> def main(a, b, *args, **kwargs):
> print 'a =', a
> print 'b =', b
>
> print 'args:', args
> print 'kwargs:', kwargs
>
> optlist.call(main)
>
>
> And on the shell:
> shell: script.py 10, 20, 100, x=1
I think it would be better if this was called like
script 10 20 100 --x=1
With something like:
def parse_args(args):
kw = {}
pos = []
for arg in args:
if arg.startswith('--') and '=' in arg:
name, value = arg.split('=', 1)
kw[name] = value
else:
pos.append(arg)
return pos, kw
def call(func, args=None):
if args is None:
args = sys.argv[1:]
pos, kw = parse_args(args)
func(*pos, **kw)
This isn't exactly what you want, since you want Python expressions
(e.g., 10 instead of '10'). But adding expressions (using eval) should
be easy. Or, you can be more restrictive, and thus safer:
def coerce(arg_value):
try:
return int(arg_value)
except TypeError:
pass
try:
return float(arg_value)
except TypeError:
pass
return arg_value
Or a little less restrictive, allowing for dictionaries and lists, but
still falling back on strings:
def coerce(arg_value):
# as above for int and float
if arg_value[0] in ('[', '{'):
return eval(arg_value)
return arg_value
--
Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org
More information about the Python-list
mailing list