Yet Another Command Line Parser

Manlio Perillo NOmanlio_perilloSPAM at libero.it
Tue Oct 26 20:13:57 CEST 2004


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



Since sometimes one needs to keep the options, I have provided an
alternate syntax, here is an example:


import optlist

optlist.setup('a, b, *args, **kwargs')

print 'a =', optlist.a
print 'b =', optlist.b

print 'args:', optlist.args
print 'kwargs:', optlist.kwargs



Finally, the module is so small that I post it here:

-------------------------- optlist.py --------------------------------

import sys

# add spaces to avoids errors like: 1 2, 3 4 -> (12, 34)
_options = ' '.join(sys.argv[1:])

def call(func):
    """
    Call func, passing to it the arguments from the command line
    """
    exec('func(' + _options + ')')
        
def setup(template):
    """
    Template is a string containing the argument list.
    The command line options are evaluated according to the template
    and the values are stored in the module dictionary
    """
    exec('def helper(' + template +
'):\n\tglobals().update(locals())')
    exec('helper(' + _options + ')')

----------------------------------------------------------------------



I hope that this is not 'Yet Another Unuseful Module' and that the
code is correct.

The only problem is that error messages are ugly.



Regards   Manlio Perillo



More information about the Python-list mailing list