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
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/

🌐
Visual Studio Code
code.visualstudio.com › docs › python › debugging
Python debugging in VS Code
November 3, 2021 - In the terminal, start Python with the script, for example, python3 myscript.py. You should see the "Waiting for debugger attach" message that's included in the code, and the script halts at the debugpy.wait_for_client() call.
Discussions

bash - How to run python debugger with a script that takes command-line arguments? - Stack Overflow
I have a python script that takes input arguments and runs in response to the following command in terminal (bash, Mac OSX). python test.py arg1 arg2 Is there a good way to run the same script in ... More on stackoverflow.com
🌐 stackoverflow.com
how do I debug a python script?
In emacs you can run `M-x pdb` which will run `pdb` debugger. Assuming you have a simple script called homework1.py , you can do M-x pdb in the prompt that follows enter "python -m pdb homework1.py " Emacs will pop a pdb shell in another window and you can run commands. There will also be a little arrow on the sides of the source code window showing you which number line you are in. Honestly, I would recommend simply doing the debugging via a terminal since you are rather new to emacs and you might be overloaded with unnecessary info at this point. More on reddit.com
🌐 r/emacs
8
0
January 11, 2024
Debug a python script being called from bash
You can use pdb. Just add the line Import pdb; pdb.set_trace() and you have a debugger at that spot More on reddit.com
🌐 r/pycharm
6
3
February 19, 2023
debugging - How to debug a Python module run with python -m from the command line? - Stack Overflow
I know that a Python script can be debugged from the command line with python -m pdb my_script.py if my_script.py is a script intended to be run with python my_script.py. However, a python module More on stackoverflow.com
🌐 stackoverflow.com
🌐
Python
docs.python.org › 3 › library › pdb.html
pdb — The Python Debugger
The debugger’s prompt is (Pdb), ... names are offered as arguments of the p command. You can also invoke pdb from the command line to debug other scripts....
🌐
W3Resource
w3resource.com › python-interview › how-do-you-start-the-python-debugger-pdb-from-the-command-line.php
Initiating Python debugger (pdb) from command line
August 12, 2023 - The -m pdb option tells Python to run the script under the control of the pdb debugger. Here's the command to initiate the Python debugger (pdb) from the terminal or command prompt:
🌐
Red Hat
redhat.com › en › blog › python-debugger-pdb
How to use the Python debugger (pdb)
November 20, 2025 - For the sake of argument, maybe you want the program to enter the debug mode if a module is missing (in fact, you insist there is a Celeri module). The change in the code is simple; just capture the ImportError and call the breakpoint() function (before you show the stack trace using traceback): #!/usr/bin/env python """ Script that show a basic Airflow + Celery Topology """ try: import argparse from diagrams import Cluster, Diagram from diagrams.onprem.workflow import Airflow from diagrams.onprem.queue import Celeri except ImportError: breakpoint()
Find elsewhere
🌐
YouTube
youtube.com › watch
How to Debug Python Code From Command Line
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
🌐
jdhao's digital space
jdhao.github.io › 2019 › 01 › 16 › debug_python_in_terminal
How to Debug Python Code in Terminal · jdhao's digital space
October 16, 2021 - To execute next line of code, use n. To run the code until a break point, use c. For more usage, press h. Overall, it is quite powerful, considering that it is implemented in a terminal. In this post, I introduced three Python debuggers — pdb, ipdb and pudb.
🌐
JetBrains
jetbrains.com › help › pycharm › part-1-debugging-python-code.html
Part 1. Debugging Python Code | PyCharm Documentation
The debugger suspends the program at the first breakpoint. It means that the line with the breakpoint is not yet executed. The line becomes blue: By the way, you can enter Python commands in the Debug Console when the program is suspended:
🌐
GeeksforGeeks
geeksforgeeks.org › 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. We can navigate in pdb prompt using n (next), u (up), d (down). To debug and navigate all throughout the Python code, we can navigate using the mentioned commands. ... Post-mortem debugging means entering debug mode after the program is finished with the execution process (failure has already occurred).
🌐
Packt Publishing
hub.packtpub.com › debugging-and-profiling-python-scripts-tutorial
Debugging and Profiling Python Scripts [Tutorial]
March 21, 2019 - Using this script as an example to learn Python debugging, we will see how we can start the debugger in detail. To start the debugger from the Python interactive console, we are using run() or runeval(). Start your python3 interactive console.
🌐
Towards Data Science
towardsdatascience.com › home › latest › a comprehensive guide to debugging python scripts in vs code
A comprehensive guide to debugging Python scripts in VS Code | Towards Data Science
March 5, 2025 - Then, we can run the script in the terminal by pressing the green play button in the top right corner of the window (or right-click somewhere in the editor pane and select "Run Python File in Terminal"). We can see the result in the screenshot below. Clearly, something went wrong (the log is capped a bit, so there is more of the traceback there). We can either try to figure it out from here or just jump right into debugging...
🌐
Reddit
reddit.com › r/pycharm › debug a python script being called from bash
r/pycharm on Reddit: Debug a python script being called from bash
February 19, 2023 -

This is my use case. After sshing into a server, I have a bash script which creates a tunnel and then runs a python script inside that tunnel. Is is possible to debug the python script? Like adding breakpoints and stuff. Can pycharm do this? It seems to be nigh impossible in vscode

🌐
CodeBurst
codeburst.io › how-i-use-python-debugger-to-fix-code-279f11f75866
How I Use Python Debugger to Fix Code | by Vadym Zakovinko | codeburst
July 19, 2019 - But now you can run the application from the debugger and set breakpoints without any changes in the source code. To execute the application with the debugger, use the command python -m pdb <python script>.
🌐
Towards Data Science
towardsdatascience.com › home › latest › debug python scripts like a pro
Debug Python Scripts Like a Pro | Towards Data Science
March 5, 2025 - You can do it by clicking before the line number. A red indicator will appear for every breakpoint you create. Now, start the debugger by clicking the "Run and Debug" button and selecting "Python file" in the dropdown.
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-use-the-python-debugger
How To Use the Python Debugger | DigitalOcean
August 20, 2021 - We can now run this program through the Python debugger by using the following command: ... The -m command-line flag will import any Python module for you and run it as a script.
Top answer
1 of 6
16

You can't do it now, because -m terminates option list

python -h
...
-m mod : run library module as a script (terminates option list)
...

That means it's mod's job to interpret the rest of the arguments list and this behavior fully depends on how mod is designed internally and whether it support another -m

Lets check out what's happening inside pdb of python 2.x. Actually, nothing intereseting, it only expects a script name to be supplied:

   if not sys.argv[1:] or sys.argv[1] in ("--help", "-h"):
        print "usage: pdb.py scriptfile [arg] ..."
        sys.exit(2)

    mainpyfile =  sys.argv[1]     # Get script filename
    if not os.path.exists(mainpyfile):
        print 'Error:', mainpyfile, 'does not exist'
        sys.exit(1)

    del sys.argv[0]         # Hide "pdb.py" from argument list

    # Replace pdb's dir with script's dir in front of module search path.
    sys.path[0] = os.path.dirname(mainpyfile)

    # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
    # modified by the script being debugged. It's a bad idea when it was
    # changed by the user from the command line. There is a "restart" command
    # which allows explicit specification of command line arguments.
    pdb = Pdb()
    while True:
        try:
            pdb._runscript(mainpyfile)

Same for the currently released versions of python 3.x

Good news

The pull request that allows to do what you're asking has been merged 5 days ago. What a mysterious coincidence! Here's the code

So just wait a bit for the upcoming python 3.x versions to have this issue resolved )

2 of 6
15

Python 3.7 adds that feature

From the docs, it looks that your command:

python -m pdb -m my_module

will start working on Python 3.7:

New in version 3.7: pdb.py now accepts a -m option that execute modules similar to the way python3 -m does. As with a script, the debugger will pause execution just before the first line of the module.

Tested on Ubuntu 23.10, Python 3.11.2:

main.py

a = 1
print(a)
a = 2
print(a)

then:

python -m pdb -m main

leads to:

> /home/ciro/test/main.py(1)<module>()
-> a = 1
(Pdb)