understanding sys.argv[]
Don Low
mt at open2web.com
Wed Aug 14 11:23:41 EDT 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
script:
#!/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"
sys.exit(1)
# does all the work
def filefind(word, filename):
# reset word count
count = 0
# can we open file? if so, return file handle
try:
fh = open(filename, 'r')
# if not, exit
except:
print filename, ":", sys.exc_value[1]
sys.exit(1)
# read all file lines into list and close
allLines = fh.readlines()
fh.close()
# 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:
usage()
# call fgrepwc.filefind() with args
filefind(sys.argv[1], sys.argv[2])
# execute as application
if __name__ == '__main__':
checkargs()
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. 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.
--
Thanks,
Mark
More information about the Python-list
mailing list