Docstoc

week3b_ch12_14

Document Sample
week3b_ch12_14 Powered By Docstoc
					         Exception-Handling Overview

• Exception: when something unforeseen happens
  and causes an error
• Exception handling
   – improves program clarity by removing error-handling
     code from the “main line” of the program
   – Improves a program’s fault tolerance
• Exception handler catches a raised/thrown
  exception
• try statement encloses code that potentially cause
  exceptions
• raise statement indicates an exception occurred

                                                           1
number1 = raw_input( "Enter numerator: " )
number2 = raw_input( "Enter denominator: " )

# attempt to convert and divide values         User might raise a
try:                                           ValueError by entering
   number1 = float( number1 )                  a string that cannot be
   number2 = float( number2 )                  converted to float
   result = number1 / number2

# float raises a ValueError exception                Division by zero raises
except ValueError:                                   ZeroDivisionError
   print "You must enter two numbers"
                                                     exception
# division by zero raises a ZeroDivisionError exception
except ZeroDivisionError:
   print "Attempted to divide by zero"

# else clause's suite executes if try suite raises no exceptions
else:
   print "%.3f / %.3f = %.3f" % ( number1, number2, result )
                        14.3 Files and Streams

• Python views files as sequential streams of bytes
• Each file ends with an end-of-file marker
• Opening a file creates an object associated with a
  stream


             0      1   2      3   4   5    6   7   8    9    ...   n-1


                                                              ...         end-of-file marker




        Fig. 14.2           Python’s view of a file of n bytes.




                                                                                               3
                 Files and Streams

• Three file streams created when Python program executes
   – sys.stdin (standard input stream)
   – sys.stdout (standard output stream)
   – sys.stderr (standard error stream)
• Defaulted to keyboard, screen and screen, respectively
  (raw_input uses stdin, print uses stdout)
• Redirect:
  print >> file, “Yes sir we have no bananas”




                                                            4
Methods for reading a file

 Method                De sc rip tio n
 close()               Closes the file object.

 fileno()              Returns an integer that is the file’s file descriptor (i.e., the
                       number the operating system uses to maintain information about
                       the file).
 flush()               Flushes the file’s buffer. A buffer contains the information to
                       be written to or read from a file. Flushing the buffer performs the
                       read or write operation.

 isatty()              Returns 1 if the file object is a tty (terminal) device.
 read( [size] )        Reads data from the file into a single string. If size is not
                       specified, the method reads all data to the end of the file. If
                       argument size is specified, the method reads at most size bytes
                       from the file.
 readline( [size] )    Reads one line from the file. If size is not specified, the method
                       reads to the end of the line. If size is specified, the method reads
                       at most size bytes from the line.
 readlines( [size] )   Reads lines from the file and returns the lines in a list. If size is
                       not specified, the method reads to the end of the file. If size is
                       specified, the method reads at most size bytes.
 seek( offset[,        Moves the file position offset bytes. If location is not
 location] )           specified, the file position moves offset bytes from the
                       beginning of the file. If location is specified, the file position
                       moves offset bytes from location. Section 14.5 discusses
                       seek in detail.


                                                                                               5
        CD management
cd.py




                        6
        Implicitly calling
        the __str__
cd.py




        method of the cd
        class                7
cd.py   Save cd collection to a file, line by line




                                                     8
                                                                         Test




                                                               Prince
                                                               Purple Rain
                                                               7.4
                                                               Oscar Peterson
                                                               Night Train
                                            File cdsave.dat    8.0
                                                               Beatles
                                                               Sgt. Pepper
            Program output                                     9.6
cdtest.py




                     Prince / Purple Rain               (rating: 7.4)
             Oscar Peterson / Night Train                (rating: 8.0)
                    Beatles / Sgt. Pepper                (rating: 9.6)          9
        Load cd collection from file, line by line




                                             Remove
                                             the trailing
                                             newline
                                             from line
cd.py




                  Create new CD object and
                  add to collection                         10
                    Testing the load method


>>> from cd import CD, CDcollection
>>> cds = CDcollection()
>>> cds.load( 'cdsave.dat')
>>> print cds
                 Prince / Purple Rain         (rating: 7.4)
     Oscar Peterson / Night Train             (rating: 8.0)
                Beatles / Sgt. Pepper         (rating: 9.6)




                                                              11
cd2.py   Extending class definition with cd comments




                     Write each comment on a line of its own, with a
                     suitable number of spaces                         12
                     Prince / Purple Rain                    (rating: 7.4)
                              [Groundbreaking!]
             Oscar Peterson / Night Train                    (rating: 8.0)
cd2test.py




                              [Got it in a Starbucks in West L.A.]
                              [Good album, especially the Gershwin songs.]
                    Beatles / Sgt. Pepper                    (rating: 9.6)
                              [Groundbreaking AND evergreen!!]
                                                                             13
         New save method




                    Write each comment
cd2.py




                    on a line of its own
                    after artist, title and
                    rating                    14
                       New load method..?


Prince                                       Which attributes are which
Purple Rain                                  in the saved file??
7.4
Groundbreaking!
Oscar Peterson                               No longer 3 lines per cd 
Night Train                                  • Change save method or
8.0
                                             • Write super-intelligent
Got it in a Starbucks in West L.A.
Good album, especially the Gershwin songs.     load method
Beatles
Sgt. Pepper
9.6
Groundbreaking AND evergreen!!


                                                                         15
               New load/save methods using module cPickle




                                             Write entire object
                                             (list of CD objects)
                                             to file

                                              Easy to load
cd_pickle.py




                                              object back into
                                              memory if you’re
                                              completely sure
                                              what kind of
                                              object the file
                                              contains         16
                                  Testing the pickle save method




                                                         ..
                                                         S'Purple Rain'
                                                         p6
                                                         sS'comments'
                                                         p7
                                                         (lp8
cd_pickletest.py




                                                         S'Groundbreaking!'
                                                         p9
                                                         asS'artist'
                                                         p10
                                                         S'Prince'
                                                         p11
                                                         sba(icd_pickle
                   Excerpt from file cd_picklesave.dat   CD
                                                                              17
                                                         ..
                        Testing the load method                     We need a
                                                                    CDcollection
                                                                    object for which we
                                                                    can call the load
                                                                    method to retrieve the
                                                                    pickled object
cd_pickletest_load.py




                                 Prince / Purple Rain                    (rating: 7.4)
                                          [Groundbreaking!]
                         Oscar Peterson / Night Train                    (rating: 8.0)
                                          [Got it in a Starbucks in West L.A.]
                                          [Good album, especially the Gershwin songs.]
                                Beatles / Sgt. Pepper                    (rating: 9.6)
                                          [Groundbreaking AND evergreen!!]
                                Beatles / A Hard Day's Night             (rating: 6.8)
                                          [First album with all Lennon/McCartney songs]
                                                                                             18

				
DOCUMENT INFO
Categories:
Tags:
Stats:
views:0
posted:4/6/2013
language:English
pages:18