understanding sys.argv[]

Hans Nowak wurmy at earthlink.net
Wed Aug 14 17:33:58 CEST 2002


Don Low wrote:

> I'm trying to modify the script according to the exercises at the end of the
> chapter. The exercise question is the following:
> 
> The "-i" option is indicated in the usage() function of the fgrepwc module
> but is not implemented anywhere in the application. This option is to
> perform the search in a case-insensitive manner. Implement this
> functionality for fgreqwc.py. You may use the getopt module.
> 
> OK, so the first thing I do is import getopt. The getopt module is for
> parsing command line options so I guess it makes sense to import it. Next, I
> modify
> 
> if argc != 3:
>          usage()
> 
> to
> 
> if argc != 4:
>          usage()
> 
> since there's 4 arguments now. 

Not always. -i is an *option*... maybe it's specified, maybe not.

Then there's the following:
> 
> filefind(sys.argv[1], sys.argv[2]). 
> 
> The author says "the command-line arguments are stored in sys.argv list."
> That makes sense. "The first argument is the program name and presumably,
> the second is the string we are looking for, and the final argument is the
> name of the file to search." Wait, there are 3 arguments but the code only
> lists two. So I add a third one as in:
> 
> filefind(sys.argv[1], sys.argv[2], sys.argv[3])
> 
> This doesn't work, so I try:
> 
> filefind(sys.argv[1], sys.argv[3]).  
> 
> This works, although honestly I don't know why. Does the sys.argv[x] where x
> equals a number signify 1st arg, 2nd arg, etc, or what?  I don't get this.

sys.argv is a list of the command line arguments passed to the program. 
sys.argv[0] is the name of the program itself; sys.argv[1] and further are used 
for the arguments.

If you use getopt, as the author suggests, things should be a bit easier, since 
you don't have to figure out where exactly the -i switch is in the list, or if 
it's there at all. Instead, getopt.getopt() returns two lists, one of 
options/switches, and one of "normal" arguments. See the documentation:

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

-- 
Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA=='))
# decode for email address ;-)
The Pythonic Quarter:: http://www.awaretek.com/nowak/




More information about the Python-list mailing list