Yes! There's a Python debugger called pdb just for doing that!

You can launch a Python program through pdb via python -m pdb myscript.py.

There are a few commands you can then issue, which are documented on the pdb page.

Some useful ones to remember are:

  • b: set a breakpoint
  • c: continue debugging until you hit a breakpoint
  • s: step through the code
  • n: to go to next line of code
  • l: list source code for the current file (default: 11 lines including the line being executed)
  • u: navigate up a stack frame
  • d: navigate down a stack frame
  • p: to print the value of an expression in the current context

If you don't want to use a command line debugger, some IDEs like Pydev, Wing IDE or PyCharm have a GUI debugger. Wing and PyCharm are commercial products, but Wing has a free "Personal" edition, and PyCharm has a free community edition.

Answer from user193476 on Stack Overflow
🌐
Python
docs.python.org › 3 › library › pdb.html
pdb — The Python Debugger
List source code for the current file. Without arguments, list 11 lines around the current line or continue the previous listing. With . as argument, list 11 lines around the current line. With one argument, list 11 lines around at that line. With two arguments, list the given range; if the second argument is less than the first, it is interpreted as a count. The current line in the current frame is indicated by ->. If an exception is being debugged, the line where the exception was originally raised or propagated is indicated by >>, if it differs from the current line.
Top answer
1 of 15
409

Yes! There's a Python debugger called pdb just for doing that!

You can launch a Python program through pdb via python -m pdb myscript.py.

There are a few commands you can then issue, which are documented on the pdb page.

Some useful ones to remember are:

  • b: set a breakpoint
  • c: continue debugging until you hit a breakpoint
  • s: step through the code
  • n: to go to next line of code
  • l: list source code for the current file (default: 11 lines including the line being executed)
  • u: navigate up a stack frame
  • d: navigate down a stack frame
  • p: to print the value of an expression in the current context

If you don't want to use a command line debugger, some IDEs like Pydev, Wing IDE or PyCharm have a GUI debugger. Wing and PyCharm are commercial products, but Wing has a free "Personal" edition, and PyCharm has a free community edition.

2 of 15
87

By using Python Interactive Debugger 'pdb'

First step is to make the Python interpreter enter into the debugging mode.

A. From the Command Line

Most straight forward way, running from command line, of python interpreter

$ python -m pdb scriptName.py
> .../pdb_script.py(7)<module>()
-> """
(Pdb)

B. Within the Interpreter

While developing early versions of modules and to experiment it more iteratively.

$ python
Python 2.7 (r27:82508, Jul  3 2010, 21:12:11)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pdb_script
>>> import pdb
>>> pdb.run('pdb_script.MyObj(5).go()')
> <string>(1)<module>()
(Pdb)

C. From Within Your Program

For a big project and long-running module, can start the debugging from inside the program using import pdb and set_trace() like this:

#!/usr/bin/env python
# encoding: utf-8
#

import pdb

class MyObj(object):
    count = 5
    def __init__(self):
        self.count= 9

    def go(self):
        for i in range(self.count):
            pdb.set_trace()
            print i
        return

if __name__ == '__main__':
    MyObj(5).go()

Step-by-Step debugging to go into more internal

  1. Execute the next statement… with “n” (next)

  2. Repeating the last debugging command… with ENTER

  3. Quitting it all… with “q” (quit)

  4. Printing the value of variables… with “p” (print)

    a) p a

  5. Turning off the (Pdb) prompt… with “c” (continue)

  6. Seeing where you are… with “l” (list)

  7. Stepping into subroutines… with “s” (step into)

  8. Continuing… but just to the end of the current subroutine… with “r” (return)

  9. Assign a new value

    a) !b = "B"

  10. Set a breakpoint

    a) break linenumber

    b) break functionname

    c) break filename:linenumber

  11. Temporary breakpoint

    a) tbreak linenumber

  12. Conditional breakpoint

    a) break linenumber, condition

Note: All these commands should be executed from pdb

For in-depth knowledge, refer:

  • https://pymotw.com/2/pdb/

  • https://pythonconquerstheuniverse.wordpress.com/2009/09/10/debugging-in-python/

Discussions

Learn how to use the debugger
print("HERE") print("INSIDE LOOP") Never quittinh this. More on reddit.com
🌐 r/learnpython
39
147
December 12, 2024
How to debug

To clarify, are you looking to learn debugging methods, or how to use a debugger in your editor?

If the latter, which editor are you using?

More on reddit.com
🌐 r/learnpython
7
9
September 16, 2021
Need tips for debugging a Python project in VS Code with over 100 lines of code
100 lines of code is extremely short so don’t get intimidated by the size. spend some time refactoring, making it readable, use descriptive function and variable names use breakpoints and go line by line and see when a variables value is different than you expected determine why it’s different than you expected and fix it rinse and repeat! More on reddit.com
🌐 r/learnprogramming
9
1
September 5, 2023
Learning your IDE Debugger will change your life
Debugging and unit testing is something beginners should learn early on, yet most courses and books barely talk about it. More on reddit.com
🌐 r/learnpython
66
443
August 24, 2021
🌐
Visual Studio Code
code.visualstudio.com › docs › python › debugging
Python debugging in VS Code
November 3, 2021 - You can then launch the program normally, causing it to pause until the debugger attaches. Launch the remote process through debugpy, for example: python3 -m debugpy --listen 1.2.3.4:5678 --wait-for-client -m myproject · This starts the package myproject using python3, with the remote computer's private IP address of 1.2.3.4 and listening on port 5678 (you can also start the remote Python process by specifying a file path instead of using -m, such as ./hello.py). Local computer: Only if you modified the source code on the remote computer as outlined above, then in the source code, add a commented-out copy of the same code added on the remote computer.
🌐
Medium
medium.com › @yellalena › a-guide-to-debugging-python-code-and-why-you-should-learn-it-ae30d20419b7
A Guide to Debugging Python code (and why you should learn it) | by Aliona Matveeva | Medium
August 15, 2023 - Why is it None then? We could continue playing a guessing game, but this is actually the perfect moment to start debugging. Python provides you with an awesome built-in code debugger: the pdb module.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-debugger-python-pdb
Python Debugger – Python pdb - GeeksforGeeks
November 4, 2022 - You just have to run the following command in terminal · python -m pdb exppdb.py (put your file name instead of exppdb.py) This statement loads your source code and stops execution on the first line of code.
🌐
OnlineGDB
onlinegdb.com › online_python_debugger
Online Python Debugger - online editor
IDE Shortcuts: New file : Ctrl-M Run Code : F9 Debug Code : F8 Save Project : Ctrl-S Beautify Code : Ctrl-B Settings Menu : Ctrl-Shift-S Info : Ctrl-I Editor Shortcuts: showSettingsMenu : Ctrl-, goToNextError : Alt-E goToPreviousError : Alt-Shift-E selectall : Ctrl-A gotoline : Ctrl-L fold ...
🌐
JetBrains
jetbrains.com › help › pycharm › part-1-debugging-python-code.html
Part 1. Debugging Python Code | PyCharm Documentation
Click the (Step Into) button, and you will see that after the line a = int(input("a: ")) the debugger goes into the file parse.py: If you want to concentrate on your own code, use the (Step Into My Code) button — thus you'll avoid stepping ...
Find elsewhere
🌐
freeCodeCamp
freecodecamp.org › news › python-debugging-handbook
Python Debugging Handbook – How to Debug Your Python Code
January 24, 2024 - In your Python script, you start by importing the pdb module. This module provides the functionality for debugging Python code. import pdb · import pdb def example_function(x, y): pdb.set_trace() result = x + y return result
🌐
Real Python
realpython.com › python-debugging-pdb
Python Debugging With Pdb – Real Python
May 19, 2023 - In this first example, we’ll look at using pdb in its simplest form: checking the value of a variable. Insert the following code at the location where you want to break into the debugger: ... When the line above is executed, Python stops and waits for you to tell it what to do next.
🌐
Reddit
reddit.com › r/learnpython › learn how to use the debugger
r/learnpython on Reddit: Learn how to use the debugger
December 12, 2024 -

I know a lot of you out there who are just getting started in python are probably using print statements to debug. While this is an easy way to debug your code there’s a lot of drawbacks when comparing it to debuggers especially in professional environments. Python has its own debugger package called pdb which uses the command line. I prefer the interactive debugger in vscode but every IDE has a debugger.

A debugger will let you mark points in code where you want to examine things further called break points. When the code reaches a break point in the debugger it will pause there allowing you to see details like variable values at that point in execution. From here you can run the code line by line as well as “step into” or out of functions. There’s also a python repl which lets you run code using all of the variables available at the breakpoint; this lets you test out different bits of code without needing to rerun everything.

If you’re still wondering why a debugger can be better than print statements in professional environments then here’s why:

  • You should not be committing any code with print statements. Anything that needs to be outputted to stdout should be with the logger.

  • Some code can take a while to run so if you’re using a debugger you don’t have to run it multiple times to test out different snippets.

  • In large code bases it can be difficult to trace things through; add to that layers of abstraction from object oriented programming and it can be hard sometimes to keep up. Using the debugger helps you understand what’s happening line by line.

🌐
CodeHS
codehs.com › tutorial › calvin › using-the-python-debugger
Tutorial: Using the Python Debugger | CodeHS
Press "Run" to start the debugger, and "Step" to start stepping through the code ... Step - steps to the very next instruction, regardless of which function the instruction is located in · Next - skips to the next instruction in the current function. Next will not step into any function calls, it will always go to the next command within the current function. Continue - continues to run the program without pausing ... When debugging Python programs, we generally want to use Next anytime we are on an import statement, or about to call a Python library function that we didn't write ourselves.
🌐
Workik
workik.com › ai-powered-python-code-debugger
FREE AI-Powered Python Code Debugger – Debug Python Code Efficiently
Integrating Workik AI for our Python projects has enhanced our code quality. It’s a strategic asset for any tech leader. ... Popular use cases include but are not limited to: * Debugging web development issues in Django and Flask. * Identifying and optimizing data science errors with NumPy, pandas, Matplotlib.
🌐
Python Tutor
pythontutor.com › python-compiler.html
Online Python Compiler, Visual Debugger, and AI Tutor
Free online Python compiler and visual debugger. Step-by-step visualization with AI tutoring to learn data structures and recursion.
🌐
JetBrains
jetbrains.com › help › pycharm › debugging-your-first-python-application.html
Debug your first Python application | PyCharm Documentation
The script is telling us that the car has travelled 0 kilometers! It's an unexpected result, because we've pushed the accelerator once, so the car should have covered some distance.
🌐
freeCodeCamp
freecodecamp.org › news › debugging-in-python-using-pdb
How to Debug Your Python Code with the Python Debugger (pdb)
September 27, 2022 - What if you want to read the raw database query? In that case you can call pdb from inside the Python function. To break into the pdb debugger, you need to call import pdb; pdb.set_trace() inside your function. Let's understand this with a nested function example:
🌐
Python
docs.python.org › 3 › library › debug.html
Debugging and Profiling — Python 3.14.3 documentation
These libraries help you with Python development: the debugger enables you to step through code, analyze stack frames and set breakpoints etc., and the profilers run code and give you a detailed breakdown of execution times, allowing you to identify bottlenecks in your programs. Auditing events provide visibility into runtime behaviors that would otherwise require intrusive debugging or patching. ... © Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
🌐
Microsoft Learn
learn.microsoft.com › en-us › visualstudio › python › debugging-python-in-visual-studio
Debug Python code, set breakpoints, inspect code - Visual Studio (Windows) | Microsoft Learn
To change this behavior, right-click any exception and modify the Continue When Unhandled in User Code option. To break less often for the exception, deselect this option. To configure an exception that doesn't appear in the Exception Settings window, select Add (plus symbol). Enter a name for the exception to watch. The name must match the full name of the exception. By default, the debugger starts your program with the standard Python launcher, no command-line arguments, and no other special paths or conditions.
🌐
CodeRed
coderedcorp.com › blog › breakpoint-a-simple-way-to-debug-your-python-code
breakpoint(): A Simple Way to Debug Your Python Code — CodeRed
February 11, 2022 - Before Python 3.7, this method is written as pdb.set_trace() but it essentially functions the same way. When you debug, you may need to use several different methods of debugging the code in order to find out what's wrong and figure out how to fix it.
Address   6815 Euclid Ave., 44103, Cleveland
🌐
Microsoft Learn
learn.microsoft.com › en-us › visualstudio › python › tutorial-working-with-python-in-visual-studio-step-04-debugging
Tutorial Step 4: Use Visual Studio Debugger - Python
Continue stepping over the code ... Value column for a variable to edit the value. In this example, change the value for the s variable to 'Hello, Python ......
🌐
Mostly nerdless
mostlynerdless.de › home › let’s create a python debugger together: part 1
Let's create a Python Debugger together: Part 1 - Mostly nerdlessMostly nerdless
November 10, 2023 - (See below for example usage). ... bpython formats code using the TerminalFormatter of pygments. We can do the same to show the current context in our shell: This is also supported when no bpython package is present, albeit without the syntax highlighting. We created our first Python debugger in a few lines of code (ignoring new lines and comments), you can find the full code at dbg_breakpoint.py.