Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debugging Python function (or class) from the command line in Spyder

I am a new Python user and I have been programming in Matlab, so I decided to use Spyder IDE (which looks pretty much like Matlab IDE).

Right now I want to debug through (execute line by line in order to understand) some python code that is written as a class with several built-in functions. So, I inserted a breakpoint at the __init__ function of the class, however, when I started a debugging it did not go to the specified breakpoint (since I have to call for a class initialization, rather than just code execution).

Is it possible to start class debugging from the command line? In Matlab I would just call a function from the command line and it would stop at a specified breakpoint. Here I have to start a debugger, rahter than calling a function. If I simply call the following:

import energy_model
x = energy_model.EnergyModel()

It will just execute and ignore my breakpoint.

Hope my question is clear. Thanks, Mikhail

like image 289
Mikhail Genkin Avatar asked Sep 13 '25 15:09

Mikhail Genkin


1 Answers

First up, make sure you are hitting the debug button in spyder, not the run button. The run button does not trigger breakpoints, so you will need to hit debug, and then continue to get to the first breakpoint in your code.

If that's failing, one option is to use the python debugger (pdb). This is entirely from the command-line, i.e. running debug commands and receiving debug information will also be through the command-line.

class EnergyModel:
     __init__(self):
          # set breakpoint
          import pdb; pdb.set_trace()
          ...

Running from the command-line will then pause execution within the __init__ method.

Some of the commands you can issue pdb when the breakpoint is hit are listed here: https://nblock.org/2011/11/15/pdb-cheatsheet/

Update #1

Example of a function that spyder can trigger breakpoints on

def test(a_string):
    print(a_string) # breakpoint set here will be hit

test("hello world")
like image 72
Sam Willis Avatar answered Sep 16 '25 05:09

Sam Willis