[Tutor] Help with ARGV parsing

Skip Montanaro skip@mojam.com (Skip Montanaro)
Tue, 1 Jun 1999 12:37:06 -0400 (EDT)


    Jerry> I'm new to Python.  But I really like what I see so far.  I'm
    Jerry> looking to write and rewrite some scripts.  I'm having some
    Jerry> trouble trying to figure out how to parse command-line arguments
    Jerry> under Python.

Jerry,

The getopt module is pretty general, and not difficult to use once you get
used to how it works.  Getopt splits command line arguments up into a list
of tuples, grouped as (argname, value).  For example, if I have a script
that accepts two arguments, "t" and "q", and that "t" takes a value,  I
could invoke getopt.getopt as

    >>> import getopt
    >>> getopt.getopt(["-t", "4", "-q"], "t:q")
    ([('-t', '4'), ('-q', '')], [])

and then massage its results.  The first argument is an input list,
typically sys.argv[1:].  The second argument is a format specifier that
tells the getopt function which arguments require values.  Typical usage
goes something like:

    import getopt, sys
    nthreads = 1
    quiet = 0
    for arg, val in getopt.getopt(sys.argv[1:], "t:q"):
	if arg == "-t": nthreads = int(val)
	if arg == "-q": quiet = 1

There's more to the getopt module.  For details, check out its section in
the library manual:

    http://www.python.org/doc/lib/module-getopt.html

A quick doc tip for everyone: Over time, as you get more familiar with
Python, you'll find you have less and less need for the tutorial and
reference manual documentation.  You'll know (most of the time) which module
does what you want.  Instead, what you find yourself asking are questions
like, "What function in the string module transfrobnicates Martian strings?"
or, "What is the order of the arguments to re.sub?"  To easily find the
answers to these sorts of questions, I maintain a bookmark to the library
manual's module index:

    http://www.python.org/doc/lib/modindex.html

Though the list is fairly large, the sections I tend to refer to are
generally marked as "visited", so it's easily to pick out "re", "string",
etc from the bunch.  Instead of clicking through the Python home page,
documentation page, library manual front page and scanning the table of
contents, I can generally get to what I'm after in two or three clicks.

Skip Montanaro	| Mojam: "Uniting the World of Music" http://www.mojam.com/
skip@mojam.com  | Musi-Cal: http://www.musi-cal.com/
518-372-5583