I have this code:
#! /usr/bin/python
import sys, string
def findAll(search, fh):
count = 0
for line in fh:
count += 1
if line.find(search) != -1:
print "%3d: %s"%(count, line.rstrip())
return count
search = raw_input("Enter string to be found: ")
filename = raw_input("Enter filename: ")
fh = open(filename, "rU")
findAll(search, fh)
My professor recommended I write this code and incorporate “improved usage”.
I’m confused as to how but she recommended that
-
I modify the program by commenting out the
raw_input()statements, then adding statements to check if the program is invoked with fewer than 2 arguments and if so toprint 'Usage: findstring.py string filename. The code takes strings and locates them in a file. -
I use the
filenamecommand line argument fromsys.argvto open the file and prepare for an input/output error (IOError) to occur. Then to use atry-exceptblock to encode what to do if opening the file works or not.
If the opening fails, Iprint 'Error: cannot open findstring.pywherefindstring.pyis also the considered the text file.
To be honest… I was so busy writing down her suggestions that I had no idea how to do many of the things she recommended. Can someone help improve this code? I’m confused and I don’t know how to do this. My prof did say that the code would run, but I don’t know how to modify it.
For improved usage, try using the argparse module. It makes taking command-line options easier.
http://docs.python.org/library/argparse.html#module-argparse
A code sample from the above link reads:
Now think about how you might modify this sample for your assignment. You need to take strings (search term, filename) instead of integers.
For the try/except block, remember that the code to handle an error goes in the except portion of the block. That is, you might consider showing an error message in the except block.