Kasun Herath

Entries categorized as ‘Journey into Python’

Debugging in Python

September 7, 2009 · 1 Comment

Python has a simple yet powerful builtin module for debugging called pdb. Using this module you can debug your python code easily even without any IDE.

1. First step is to import the pdb module

2. Next step is to mark the entry point where the debugger would be called in. We use the set_trace() method for that.
pdb.set_trace()

3. When the program is run the execution would stop at the set_trace() method and would wait for debugging commands.

4. To run the next statment enter ‘n’ or ‘next’

5. To print a variable enter ‘pp variable_name’

6. To run until exit enter ‘c’ or ‘continue’

7. To display the current location enter ‘l’ or ‘list’
This would display an appropiate part of the source code with a pointer to the current statement.

8. To step into a method enter ’s’ or ’step’ when debugger is met with a method

9. To insert a break point enter ‘b filename:linenumber’

10. You can also dynamically assign values into variables.
Let’s assume there is a variable called num initialized to 10. You want to see what would happen when that variable is initialized to 20. You just do this. (pdb) num = 20 and then enter ‘n’ to execute next statement or enter ‘c’ to execute program until the end.

An example would look like this

import pdb

def method():
i = 10
name = ‘kasun’
last_letter = name[-1]

last_num = ord(last_letter)

print ‘last_num is’, last_num
if __name__ == ‘__main__’:
pdb.set_trace()
method()

Categories: Journey into Python · Programming
Tagged: , , ,

Journey into Python

May 10, 2009 · Leave a Comment

As I said earlier I am in the process of moving into python. I am in love with the beast at the moment and thought I would write down what I find interesting in python. Pros and cons, both. This is my journey into Python.

The first thing that I found of interest is the python interactive shell. It allows you to run python statements and expressions in the console. This is really handy when you are learning python or testing a python module. How many times have you skipped checking out some feature while learning a language like Java because writing a whole class and then running it to test a small feature is not worth all the trouble? I do it all the time. That is where the python interactive shell comes in.

python interactive shell

python interactive shell

Importing modules, instantiating variables and running statements can be done right in the console by using the python interactive shell.

Categories: Journey into Python
Tagged: , ,