[Courses] [python] Lesson 4: Modules and command-line arguments
Kay Nettle
pkn at cs.utexas.edu
Fri Jul 15 02:03:21 UTC 2011
>========================= Homework ============================
>
>1. With the little example I gave earlier, the one that used
> num = int(sys.argv[1]):
> if you run it and don't give an argument, you'll get an error.
> Why? Can you think of a way to check whether the user forgot to
> supply an argument, and print an error message if so?
There is no sys.argv[1], so you get an error.
import sys
if len(sys.argv) != 2:
print "%s arg" % sys.argv[0]
sys.exit(1)
>
>2. Write a program that takes a filename and prints the number of
>lines in the file. (You can check its results with wc -l filename.)
(I use mh as my mail and I've forgotten how to start a line with #
so it's indented one space)
#!/usr/bin/python
import sys, os
def usage():
print "%s: file" % (sys.argv[0])
if len(sys.argv) != 2:
usage()
sys.exit(1)
if not os.path.isfile(sys.argv[1]):
print "No such file"
sys.exit(1)
lc = 0
file=open(sys.argv[1])
for line in file:
lc += 1
file.close()
print "The number of lines in %s is %d" % (sys.argv[1], lc)
>3. How would you extend this so that you can count lines in multiple
>files, not just one? So you could say
>$ mywordcounter file1 file2 file3
#!/usr/bin/python
import sys, os
def usage():
print "%s: file [file]" % (sys.argv[0])
if len(sys.argv) < 2:
usage()
sys.exit(1)
for arg in sys.argv[1:]:
if not os.path.isfile(arg):
print "No such file %s" % (arg)
continue
lc = 0
file=open(arg)
for line in file:
lc += 1
file.close()
print "The number of lines in %s is %d" % (arg, lc)
>
>4. Here's a harder problem, an exercise in debugging (which is a big
> part of programming, sadly):
>
> a. Write a program that counts words in a file (or multiple files,
> if you prefer). Use the same split() and len() you used in
> lesson 2.
#!/usr/bin/python
import sys, os
def usage():
print "%s: file [file]" % (sys.argv[0])
if len(sys.argv) < 2:
usage()
sys.exit(1)
for arg in sys.argv[1:]:
if not os.path.isfile(arg):
print "No such file %s" % (arg)
continue
wc = 0
file=open(arg)
for line in file:
wc += len(line.split())
file.close()
print "The number of words in %s is %d" % (arg, wc)
>
> b. Compare the number of words from your program to what wc -w gives.
> (If you're on a platform that doesn't have wc, run it on a small
> file and count by hand.) Are the answers the same?
Yes.
>
> c. Here's the debugging part: why aren't they the same?
> (You don't have to fix it: just figure out the problem.)
Mine are the same since I didn't do line.split(' '). line.split()
removes all the extra white spaces.
More information about the Courses
mailing list