Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I put a breakpoint in a running Python program that drops to the interactive terminal?

Tags:

python

I'm not sure if what I'm asking is possible at all, but since python is an interpreter it might be. I'm trying to make changes in an open-source project but because there are no types in python it's difficult to know what the variables have as data and what they do. You can't just look up the documentation on the var's type since you can't be sure what type it is. I want to drop to the terminal so I can quickly examine the types of the variables and what they do by typing help(var) or print(var). I could do this by changing the code and then re-running the program each time but that would be much slower.

Let's say I have a program:

def foo():     a = 5     my_debug_shell()     print a  foo() 

my_debug_shell is the function I'm asking about. It would drop me to the '>>>' shell of the python interpreter where I can type help(a), and it would tell me that a is an integer. Then I type 'a=7', and some 'continue' command, and the program goes on to print 7, not 5, because I changed it.

like image 440
sashoalm Avatar asked Apr 24 '11 07:04

sashoalm


People also ask

Can you set breakpoints in Python code?

It's easy to set a breakpoint in Python code to i.e. inspect the contents of variables at a given line. Add import pdb; pdb. set_trace() at the corresponding line in the Python code and execute it.

How do you enter a breakpoint in Python?

You can insert a breakpoint with the breakpoint() function at any position in your code . This is new in Python 3.7, and is equivalent to the older import pdb; pdb. set_trace() command. # my_script.py a = int(0.1) b = 3.0 c = a + b breakpoint() # a lot of more code here...

Can you run Python in debug mode?

Python Debugger Commands If you're working with Python, not only can you look through the code during debugging, but you can also run the code that's written in the command line or even affect the process by changing the variables' value. Python has a built-in debugger called pdb .

Which function may be used to break into the debugger from a running program?

Use the command b (break) to set a breakpoint. You can specify a line number or a function name where execution is stopped. If filename: is not specified before the line number lineno , then the current source file is used. Note the optional 2nd argument to b : condition .


1 Answers

http://docs.python.org/library/pdb.html

import pdb pdb.set_trace() 
like image 142
Amber Avatar answered Oct 14 '22 00:10

Amber