Mikhail Genkin
Mikhail Genkin

Reputation: 3460

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

Upvotes: 4

Views: 7074

Answers (2)

Post169
Post169

Reputation: 708

If you want to debug code in Spyder, it's probably best to run the module it's in by clicking the blue Play/Pause button for debug.

So how do we debug a module that is all classes or functions, with no script? We add script that only runs when this module was the one we clicked Play for, by putting it all under if __name__=="__main__":. (See here for more info on how that works.)

Then we can put a break point in the function or class we want to debug, call that from within if __name__==__"__main__":, run the module with the blue Play/Pause button, and access what's happening from the IPython console.

Upvotes: 1

Sam Willis
Sam Willis

Reputation: 46

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")

Upvotes: 3

Related Questions