understanding sys.argv[]

Don Low mt at open2web.com
Wed Aug 14 17:23:41 CEST 2002

I'm learning Python with Core Python programming by W. Chun. In chpt 3
there's a script which I more or less understand. Here's the original

#!/usr/bin/env python

"fgrepwc.py -- searches for string in text file"

import sys
import string

# print usage and exit
def usage():
    print "usage:  fgrepwc [ -i ] string file"

# does all the work
def filefind(word, filename):

    # reset word count
    count = 0

    # can we open file? if so, return file handle
        fh = open(filename, 'r')

    # if not, exit
        print filename, ":", sys.exc_value[1]

    # read all file lines into list and close
    allLines = fh.readlines()

    # iterate over all lines of file
    #for eachLine in allLines:

	# search each line for the word
        #if string.find(eachLine, word) > -1:
        #    count = count + 1
        #    print eachLine,

    # when complete, display line count
    #print count

    for eachLine in allLines:

        if string.find(eachLine, word) > -1:
            count = count + 1
            print eachLine,

    print count

# validate arguments and call filefind()
def checkargs():

    # check args; 'argv' comes from 'sys' module
    argc = len(sys.argv)

    if argc != 3:

    # call fgrepwc.filefind() with args
    filefind(sys.argv[1], sys.argv[2])

# execute as application
if __name__ == '__main__': 

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

if argc != 3:


if argc != 4:

since there's 4 arguments now. 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.

Could someone explain.



More information about the Python-list mailing list