[Tutor] arg exceptions for scrips
kevin parks
kp87@lycos.com
Fri, 13 Jul 2001 23:32:58 +0900
Below is my little copy thing which does nothing but copy a file. It works,
but i would like be able to use it as a script and a module. So here i have it
wired up for the usual __name__, run as main thing. The problem is that the cp()
func takes 2 args. So i tried to patch it up so that when i typed:
% cp.py foo.txt bar.txt
it executed the cp() function and passes the 2 command line arguments to
the func itself. I don't know if this is the standard way to do this or my
kludge but it works, except the if len(sys.argv) < 2: part. What i want it to
is complain if it doesn't get exactly 2 arguments and i want to to say:
"Usage: infile outfile" or something close to that and then exit. But it doesn't
Python itself complains if the args aren't right and i get:
[localhost:~/scripts] kevin% python cp.py scales.txt
Traceback (most recent call last):
File "cp.py", line 28, in ?
cp(sys.argv[1],sys.argv[2])
IndexError: list index out of range
for less than 2 args (and nothing yet for more than 2). Is there no
way to tell python to chill and print the exception and usage i want?
This way if someone other than me executes this script they can know what
the expected arguements are rather than knowing:
cp(sys.argv[1],sys.argv[2])
IndexError: list index out of range
Which is useless for the end user.
#!/usr/bin/env python
import os
import sys
def cp(infilename, outfilename):
"""this will copy a file exactly, args are: 'infile' and 'outfile'"""
infile = open(infilename, 'r')
f = open(outfilename, 'w')
for aLine in infile.xreadlines() :
f.write( aLine )
infile.close()
f.close()
# if used as a script we have to pass the args from the
# shell command-line to the function above. If there are
# not exactly 2 args, complain and quit.
if __name__ == '__main__':
if len(sys.argv) < 2:
print "Usage:", sys.argv[0], "infile outfile"
sys.exit(1)
else:
cp(sys.argv[1],sys.argv[2])
Get 250 color business cards for FREE!
http://businesscards.lycos.com/vp/fastpath/