syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me

Question:
In Python debugger, how do I step through a running script?

A common use-case for working with code is to ask the code to stop running at a specific line. Then I want a UI which allows me to inspect data which the code is interacting with. Also I want the UI to allow me to experiment with snippets of code which can interact with that data.

In Python, this UI is availble via a module called pdb.

In the script below, I show you how to add pdb-syntax to a Python script.

When I use Python to start the script, it will run until it encouncters pdb syntax.

Then, the script will stop.

Next, Python will present me a command line UI.

Here is the script:
# /tmp/python_pdb.python

# This script should demo how to use pdb.

# I should do this first:
import pdb

# Do something simple here:

avar = 1
bvar = 2
cvar = 3

# When Python sees next line,
# it should stop running the script 
# and then present a pdb command line UI to me:
pdb.set_trace()

# Once in pdb, I can type in the name of a variable to see its value:
# avar

dvar = 4

# done
Since the UI is command line based, it is easy for me to capture some of my interactions with it and display them below:
dan@hp ~/cjb4/fx $ 
dan@hp ~/cjb4/fx $ python /tmp/python_pdb.python 
> /tmp/python_pdb.python(22)()
-> dvar = 4
(Pdb) avar
1
(Pdb) bvar
2
(Pdb) cvar
3
(Pdb) dvar
*** NameError: name 'dvar' is not defined
(Pdb) dvar = 44
(Pdb) dvar
44
(Pdb) dvar += 1
(Pdb) dvar
45
(Pdb) c
dan@hp ~/cjb4/fx $ 
dan@hp ~/cjb4/fx $ 
I think that pdb is easy to understand and operate. The Python documentation offers more information at the URL listed below:

https://docs.python.org/2/library/pdb.html


syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me