• When an error occurs while running a Python script, it will be raised and displayed to the user in the form of a "stack trace" • A stack trace shows the calling "stack" of statements all the way from the top-level script that is being executed down to the statement that has produced the error • The stack trace starts with the line beginning with Traceback and ends with the generated error message • How to read and understand what a stack trace is telling you: ◇ Read the Last Line First ◇ If you don't know what's going on, then review the call stack from Top to Bottom
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Debugging Your Code at Run Time
• Use features from advanced IDEs like executing your code line by line or inserting a break point to in your code to examine intermediate output • If advanced IDEs are not available, use the following methods
1. Using print statements
• To get the value of a certain variable at key points in your script ◇ Add visual prefixes like ==> or DEBUG: (or whatever you like) to highlight them in the output of your script
# Get the value of variable a print("DEBUG: a=", a)
• To see the flow of your script as it runs
# Identify flow of a script def my_function(): print("==> Starting my_function()") ...
2. Using the Python Interactive Shell
• You can instruct the Python interpreter to run your script and then stay in the interactive shell by passing it the -i option when running your script
python -i <script_name.py>
• This will help you to: ◇ Inspect module-scope variables ◇ Incrementally build your code ◇ Test out fixes to your code