Newbie Getopts Question
Andrew N. McGuire
amcguire at coastalnet.com
Thu Dec 16 16:00:01 EST 1999
Hey all,
I picked up my first python book 5 days ago, so dont laugh at me too
hard. I have looked in man
page, Learning Python by O &A, and python.org, as well as here, and
found nothing __substantial__
on the use of getopts. Here is a code snipet of a program I have
written... The programs works
fine, and I really like the language, but this seems like a somewhat
ineffecient way of handling
options.
Well, I am probably just ignorant here, so if any of you can help me
clean up the mess below, I will
be very grateful.. Looking specifically for getopts suggestions, but all
suggestions are wanted and welcomed. Thanxx all.
Andrew
PS. Once again this is my first program, so dont laugh too hard. ;^)
####################################################################################
#!/usr/local/bin/python
import sys, string, getopt
CF = 0
# Define a usage summary function.
def usage():
print """
Usage: dbformat -f FS -n NF -i INFILE -o OUTFILE [ -c CF ]
Where:
FS = Field separator / delimiter, must be single charachter
NF = Number of fields to insert \\n after
INFILE = Input file name
OUTFILE = Output file name
CF = Number of fields to cut from beginning of line
"""
sys.exit(1)
# Build an argument/option list.
arglist = sys.argv[1:]
# Check for extra options or arguments.
try:
optlist, arglist = getopt.getopt(arglist, 'f:n:i:o:c:')
except getopt.error:
print 'Unrecognized argument or option!'
usage()
# Generate a list of all options passed to the program. Arguments
# are left out.
list = []
for opt in optlist:
list.append(opt[0])
# Bounce that list against a list of mandatory options.
for opt in ['-f', '-n', '-i', '-o']:
if opt not in list:
print '%s argument is mandatory!' % opt
usage()
for opt in optlist:
if opt[0] == '-f':
FS = opt[1]
if (len(FS) > 1):
print 'The FS specified must be a single character.'
usage()
elif opt[0] == '-n':
try:
NF = string.atoi(opt[1])
except ValueError:
usage()
if NF <= 0:
usage()
elif opt[0] == '-i':
try:
INFILE = open(opt[1], 'r')
except IOError:
print 'Sorry, cannot open output file: %s' % opt[1]
usage()
elif opt[0] == '-c':
CF = string.atoi(opt[1])
for line in INFILE.readlines():
line = string.split(line, FS)[CF:]
COUNT = 0
for word in line:
COUNT = COUNT + 1
if word == '\n':
OUTFILE.write(word + '\n')
else:
if COUNT % NF == 0:
OUTFILE.write(word + '\n')
else:
OUTFILE.write(word + FS)
INFILE.close()
OUTFILE.close()
More information about the Python-list
mailing list