Easy command line parsing? (Was Re: understanding sys.argv[])
Huaiyu Zhu
huaiyu at gauss.almadan.ibm.com
Wed Aug 14 20:52:16 EDT 2002
Steve Holden <sholden at holdenweb.com> wrote:
>
>That will work in this case. However, in general you may want to implement a
>number of options for any given program. Since by their nature these are
>optional, checking the argumnet count is often best left until you've
>processed the options (see below).
A somewhat related question (and IMHO a better approach):
It appears that the traditional command line with arguments and options
is very similar to python functions with default arguments and default
keyword arguments:
cmd -a A -b -c C ... -- arg1 arg2 ...
def func(cmd, *args, **kwargs):
where args = [cmd, arg1, arg2 ,.. ], kwargs = {a:A, b:'', c:C ...}
Is there an existing module that allows simple operations like the
following?
from cmdline import parse_cmdline
args, kwargs = parse_cmdline()
func(*args, **kwargs)
The problem I have with the getopt module is that it needs pre-specified
options, so it cannot be used in the above fashion if I am going to
substitute another definition of func.
In other words, I want parse_cmdline to do just the shallow parsing, leaving
all the actual option checking and argument counting to the function that
uses them.
Of course the command line is ambiguous if some options may or may not have
arguments and if they can be mixed with plain arguments. However, it should
be possible to define a subset that's unambiguous. For example, the
following command line formats are not ambiguous
cmd arg1 arg2 ... -a A -b -c C ... # options come last
cmd -a A -b -c C ... -- arg1 arg2 ... # options followed by --
cmd -a A -b '' arg1 -c C ... arg2 ... # options always have arguements
Are there existing facilities that can be easily adapted to this?
Huaiyu
More information about the Python-list
mailing list