[Courses] [python] Lesson 4: Modules and command-line arguments
Prana Peddi
prana.lists at gmail.com
Tue Jul 12 18:32:12 UTC 2011
Hi,
I just joined the course this week. I am using python 2.6.5 on ubuntu 10.04
64. For the previous assignments, I compared my results with the mailing
list answers.
Here are my answers for this week's assignment:
========================= 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?
>
The array argv contains only 1 element argv[0] which is the scriptname and
argv[1] is invalid array entry.
Here's a way to check for required number of args -
#! /usr/bin/python
import sys
if(len(sys.argv) < 2):
print "not enough args"
else:
num = int(sys.argv[1])
print num
> 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.)
>
> #! /usr/bin/python
import sys
if(len(sys.argv) < 2):
print "not enough args"
else:
file = open(sys.argv[1])
ct = 0
for line in file:
ct += 1
file.close()
print sys.argv[1], "has lines", ct
> 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
if(len(sys.argv) < 2):
print "not enough args"
else:
for i in sys.argv[1:]:
file = open(i)
ct = 0
for line in file:
#print "read", line,
ct += 1
file.close()
print i, "has lines", ct
> 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
if(len(sys.argv) < 2):
print "not enough args"
else:
for i in sys.argv[1:]:
file = open(i)
ct = 0
for line in file:
ct += len(line.split(" "))
file.close()
print "\n",i, "has words", ct
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?
>
No, the answers are not the same.
> c. Here's the debugging part: why aren't they the same?
>
My program counts blank lines as a word and splits multiple spaces between
words as separate words.
> d. OPTIONAL, harder: fix the problems and make your word count
> program give the same answer as wc -w.
>
#! /usr/bin/python
import sys
if(len(sys.argv) < 2):
print "not enough args"
else:
for i in sys.argv[1:]:
file = open(i)
ct = 0
for line in file:
words = line.strip().split(" ")
for j in range(0,len(words)):
if(len(words[j].strip()) == 0):
continue;
ct += 1
file.close()
print "\n",i, "has words", ct
Thanks,
Prana
More information about the Courses
mailing list