Module 4 Python
Module 4 Python
MODULE 4
3.2 DEBUGGING
Raising Exceptions, Getting the Traceback as a String, Assertions, Logging, IDLE’s Debugger
• The shutil.copy() will copy a single file, shutil.copytree() will copy an entire folder and
everyfolder and file contained in it.
• Calling shutil.copytree(source, destination) will copy the folder at the path source, along
with all ofits files and subfolders, to the folder at the path destination.
• The source and destination parameters are both strings.
• The function returns a string of the path of the copied folder.
• Example:
• Example:
import os
print('')
• Output:
• Since a ZIP file can also contain multiple files and subfolders, it’s a handy way to
package several
files into one. This single file, called an archive file, can then be, say, attached to an email.
Python programs can both create and open (or extract) ZIP files using functions in
the zipfilemodule.
• A ZipFile object has a namelist() method that returns a list of strings for all the files and
folderscontained in the ZIP file.
• These strings can be passed to the getinfo() ZipFile method to return a ZipInfo object about
thatparticular file.
• ZipInfo objects have their own attributes, such as file_size and compress_size in bytes, which
holdintegers of the original file size and compressed file size, respectively.
• While a ZipFile object represents an entire archive file, a ZipInfo object holds useful
informationabout a single file in the archive.
• Example:
• After running this code, the contents of of the zip file will be extracted to the current
workingdirectory.
• Optionally, we can pass a folder name to extractall() to have it extract the files into a
folder otherthan the current working directory.
• If the folder passed to the extractall() method does not exist, it will be created.
• For instance, if we replaced the call at with exampleZip.extractall('C:\ delicious'), the
code wouldextract the files from zip file into a newly created C:\delicious folder.
• The extract() method for ZipFile objects will extract a single file from the ZIP file.
• Example:
• The string we pass to extract() must match one of the strings in the list returned by
namelist()
• In the above example, it will extract to the current working dir
ectoryC:\\Users\\Dell\\automate_online-materials\\yourname2.py
• Optionally, we can pass a second argument to extract() to extract the file into a folder
other than thecurrent working directory.
• If this second argument is a folder that doesn’t yet exist, Python will create the folder.
• The value that extract() returns is the absolute path to which the file was extracted.
• This code will create a new ZIP file named new.zip that has the compressed contents of
spam.txt
• writing to files, write mode will erase all existing contents of a ZIP file.
• If you want to simply add files to an existing ZIP file, pass 'a' as the second argument to
zipfile.ZipFile() to open the ZIP file in append mode.
Raising Exceptions:
• Python’s exceptions with try and except statements so that your program can recover from
exceptions that you anticipated.
• But you can also raise your own exceptions in your code.
• Raising an exception is a way of saying, “Stop running the code in this function and move
the program execution to the except statement.”
Exceptions are raised with a raise statement. In code, a raise statement consists of the
following:
• The raise keyword
• A call to the Exception() function
• A string with a helpful error message passed to the Exception() function
• If there are no try and except statements covering the raise statement that raised the
exception, the program simply crashes and displays the exception’s error message.
• The code that calls the function, not the fuction itself, that knows how to handle an
expection.
• So you will commonly see a raise statement inside a function and the try and except
statements in the code calling the function.
Example:
def boxPrint(symbol, width, height):
if len(symbol) != 1:
raise Exception('Symbol must be a single character string.')
if width <= 2:
raise Exception('Width must be greater than 2.')
if height <= 2:
raise Exception('Height must be greater than 2.')
print(symbol * width)
for i in range(height - 2):
print(symbol + (' ' * (width - 2)) + symbol)
print(symbol * width)
for sym, w, h in (('*', 4, 4), ('O', 20, 5), ('x', 1, 3), ('ZZ', 3, 3)):
try:
boxPrint(sym, w, h)
except Exception as err:
print('An exception happened: ' + str(err))
Output:
• From the traceback, you can see that the error happened on line 5, in the bacon()
function. This particular call to bacon() came from line 2, in the spam() function, which
in turn was called on line 7.
• In programs where functions can be called from multiple places, the call stack can help
you determine which call led to the error.
Assertions:
• An assertion is a sanity check to make sure your code isn’t doing something obviously
wrong. These sanity checks are performed by assert statements.
• If the sanity check fails, then an AssertionError exception is raised. In code, an assert
statement consists of the following:
• The assert keyword
• A condition (that is, an expression that evaluates to True or False)
• A comma
• A string to display when the condition is False
Example:
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
print KelvinToFahrenheit(273)
print int(KelvinToFahrenheit(505.78))
print KelvinToFahrenheit(-5)
Logging:
• Logging is a great way to understand what’s happening in your program and in what
order its happening.
• Python’s logging module makes it easy to create a record of custom messages that you
write.
• These log messages will describe when the program execution has reached the logging
function call and list any variables you have specified at that point in time.
• On the other hand, a missing log message indicates a part of the code was skipped and
never executed.
Using the logging Module:
• To enable the logging module to display log messages on your screen as your program runs,
• copy the following to the top of your program
• when Python logs an event, it creates a LogRecord object that holds information
about that event.
• The logging module’s basicConfig() function lets you specify what details about the
LogRecord object you want to see and how you want those details displayed.
Example:
Logging Levels:
• Logging levels provide a way to categorize your log messages by importance.
• Messages can be logged at each level using a different logging function.
LEVEL LOGGING DESCRIPTION
FUNCTION
DEBUG logging.debug() The lowest level. Used for small details. Usually, you care about these
messages only when diagnosing problems.
WARNING logging.warning() Used to indicate a potential problem that doesn’t prevent the program
from working but might do so in the future.
ERROR logging.error() Used to record an error that caused the program to fail to do
something.
CRITICAL logging.critical() The highest level. Used to indicate a fatal error that has caused or is
about to cause the program to stop running entirely.
• Your logging message is passed as a string to these functions. The logging levels are
suggestions. Ultimately, it is up to you to decide which category your log message falls into.
Disabling Logging:
• The logging.disable() function disables these so that you don’t have to go into your
IDLE ’s Debugger:
• The debugger is a feature of IDLE that allows you to execute your program one line at a
time.
• The debugger will run a single line of code and then wait for you to tell it to continue. By
running your program “under the debugger” like this, you can take as much time as you want
to examine the values in the variables at any given point during the program’s lifetime.
• This is a valuable tool for tracking down bugs. To enable IDLE’s debugger, click
Debug4Debugger in the interactive shell window.
• When the Debug Control window appears, select all four of the Stack, Locals, Source, and
Globals checkboxes so that the window shows the full set of debug information.
• While the Debug Control window is displayed, any time you run a program from the file
editor, the debugger will pause execution before the first instruction and display the
following:
▪ The line of code that is about to be executed
▪ A list of all local variables and their values
▪ A list of all global variables and their values
The program will stay paused until you press one of the five buttons in the Debug Control window:
Go, Step, Over, Out, or Quit.
Go
Clicking the Go button will cause the program to execute normally until it terminates or reaches a
breakpoint. (Breakpoints are described later in this chapter.) If you are done debugging and want
the program to continue normally, click the Go button.
Step
Clicking the Step button will cause the debugger to execute the next line of code and then pause
again. The Debug Control window’s list of global and local variables will be updated if their values
change. If the next line of code is a function call, the debugger will “step into” that function and
jump to the first line of code of that function.
Over
Clicking the Over button will execute the next line of code, similar to the Step button. However, if
the next line of code is a function call, the Over button will “step over” the code in the function. The
function’s code will be executed at full speed, and the debugger will pause as soon as the function
call returns. For example, if the next line of code is a print() call, you don’t really care about code
inside the built-in print() function; you just want the string you pass it printed to the screen. For this
reason, using the Over button is more common than the Step button.
Out
Clicking the Out button will cause the debugger to execute lines of code at full speed until it returns
from the current function. If you have stepped into a function call with the Step button and now
simply want to keep executing instructions until you get back out, click the Out button to “step out”