understanding sys.argv[]

Don Low mt at open2web.com
Wed Aug 14 18:54:33 CEST 2002


>> 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.

OK, then I would do 

if argc == 3 || argc == 4
> 
> 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.

How come sys.argv[0] isn't mentioned? Is it implicit?  In this case

sys.argv[1] represents the word I want to look up
sys.argv[2] reps name of the document in which I want to look up the word.
> 
> 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
> 
OK, so if I understand correctly, I'd have something like this

opts, args = getopt.getopt(sys.argv[1:], "i:")

Not sure why 2 variables (opts and args) get initialized with getopt...

def checkargs():

    argc = len(sys.argv)

    if argc == 3 || argc == 4 :

	filefind(getopt.getopt(sys.argv[1:], "i"), sys.argv[2])

    else:
        usage()


Still haven't figured out how the -i parameter allows a case-insensitive
search.
 
-- 
Thanks,

Mark



More information about the Python-list mailing list