A little disappointed so far

Jere Kahanpaa kahanpaa at gstar.astro.helsinki.fi
Fri May 23 15:21:34 EDT 2003


Hi.

I am a bit late with this, but I'd like to point out that the getopt 
module in the standard library could do most of the work you do by hand in the 
code snipped below. I appended my own version for comparison:

Graham Nicholls <graham at rockcons.co.uk> wrote:
> #!/usr/bin/env python

> import string,os,sys
> import re

> TRUE=1
> FALSE=0
> BAD_ARGS=1
> OPEN_FAIL=2

> debug=FALSE
> version="0.1"
> progname=""

> def main():
>         """Main routine for extract_fonttable program"""
>         global progname, version, debug

>         pname_re=re.compile("^.*/")

>         progname=sys.argv[0]
>         infiles,outfile=setup(sys.argv[1:])
>         print ("Reading files %s; creating file %s" % (infiles,outfile))

> def setup(arglist):
>         """     Process all command line args and check all files, etc
>                         arglist already has been stripped of program name"""

>         global progname, version, debug

>         outfile=""
>         flist=[]

>         ok_opts="dvo"
>         argc=len(arglist)

>         if debug:
>                 print ("arglist=%s, argcount=%d" % ( arglist,argc))

>         i=0
>         while (i < argc):
>                 opt=arglist[i]

>                 if opt[0] == "-":               # i.e. its an option

>                         option=opt[1:]
>                         print ("Option %s found " % opt[1:] )

>                         if option not in ok_opts:
>                                 usage("What is option %s" % option )
>                                 sys.exit(BAD_ARGS)

>                         # Flag type options:
>                         if option == 'd':
>                                 print ("%s DEBUG - debug activated" % progname)
>                                 debug=TRUE

>                         if option == 'v':
>                                 verbose=TRUE
>                                 print ("%s version %s" % (progname,version))

>                         # Others - take args
>                         if option == 'o':               # Output file specifier
>                                 if len (opt) > 2:       # i.e. there's no space after -o
>                                         print "Outfile is %s" % opt[2:]
>                                         outfile=opt[2:]
>                                 else:
>                                         i=i+1
>                                         try: 
>                                                 outfile=arglist[i]
>                                                 if outfile[0] == '-':
>                                                         raise IndexError
>                                         except IndexError:
>                                                 usage("Option -o requires a filename")
>                                                 sys.exit(BAD_ARGS)
>                                 
>                 else:   # Not an option, so assume it must be a filename
>                         flist.append(opt)

>                                 # Try to open the file
>                         try:
>                                         infile=open(opt,"r")
>                         except IOError:
>                                 print ("Error opening file %s" % opt)
>                                 sys.exit(OPEN_FAIL)
>                         else:
>                                 infile.close()
>                                 
>                 
>                 i=i+1

>         # Check we've got an output file
>         if outfile=="":
>                 usage ("No output file specified")
>                 exit(BAD_ARGS)

>         # and at least one input file
>         if len(flist)==0:
>                 usage ("No input file specified")
>                 exit(BAD_ARGS)
>         
>         return flist,outfile
> ###############################################################################

> def usage(errmsg):
>         """Print an error message, then a usage string, and return"""
>         global progname, version, debug

>         umsg="""
> exft attempts to extract the font table from an rtf file or files.  It is 
> called thusly:

>         exft -h(elp) -d(ebug) -o(utput)[out_fname]
>         """

>         print errmsg
>         print umsg
>         return
> ###############################################################################

> if __name__ == '__main__': # ie we're _not_ a module
>         main()

#!/usr/bin/env python
# A slightly more 'Pythonized' version by Jere Kahanpää

import os,sys,getopt

TRUE=1
FALSE=0
BAD_ARGS=1
OPEN_FAIL=2

# I prefer to keep all misc. options in a simple storage class 
# that behaves like a C struct, and then pass a single instance around
class parameters:
   debug=FALSE
   version="0.1"
   progname= None

pars = parameters()   
pars.progname=sys.argv[0]

def main():
        """Main routine for extract_fonttable program"""
	global pars
        infiles,outfile=setup(sys.argv[1:])
        print ("Reading files %s; creating file %s" % (infiles,outfile))

def setup(arglist):
        """     Process all command line args and check all files, etc
                        arglist already has been stripped of program name"""

	global pars
        outfile=""
	
	# Process options:
        try:
          ok_opts="dho:"   # Forces option argument for opt '-o'
    	  opts, flist  = getopt.getopt(arglist,ok_opts)
	  
   	  for option,val in opts:
             print ("Option %s found " % option)
             if option == '-d':
                 print ("%s DEBUG - debug activated" % pars.progname)
                 debug=TRUE
             if option == '-h':
                 usage("")
                 sys.exit()
             if option == '-o':  
                 outfile=val
        except getopt.GetoptError, msg:
	    usage(msg)
	    sys.exit()
       
        for filename in flist:
	  if not os.path.exists(filename):
              print ("Error opening file '%s'" % filename)
              sys.exit(OPEN_FAIL)

        # Check we've got an output file
        if not outfile:
                usage ("No output file specified")
                sys.exit(BAD_ARGS)

        # and at least one input file
        if not flist:
                usage ("No input file specified")
                sys.exit(BAD_ARGS)

        return flist,outfile
###############################################################################


def usage(errmsg):
        """Print an error message, then a usage string, and return"""

        umsg="""
exft attempts to extract the font table from an rtf file or files.  It is
called thusly:

        exft -h(elp) -d(ebug) -o(utput)[out_fname]
        """

        print errmsg
        print umsg
        return
###############################################################################

if __name__ == '__main__': # ie we're _not_ a module
        main()

Jere
-- 
It's hard to think outside the box when you ARE the box.
                            - unknown, alt.religion.kibology 




More information about the Python-list mailing list