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 breakpointc: continue debugging until you hit a breakpoints: step through the coden: to go to next line of codel: list source code for the current file (default: 11 lines including the line being executed)u: navigate up a stack framed: navigate down a stack framep: 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 OverflowYes! 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 breakpointc: continue debugging until you hit a breakpoints: step through the coden: to go to next line of codel: list source code for the current file (default: 11 lines including the line being executed)u: navigate up a stack framed: navigate down a stack framep: 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.
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
Execute the next statement… with “n” (next)
Repeating the last debugging command… with ENTER
Quitting it all… with “q” (quit)
Printing the value of variables… with “p” (print)
a)
p aTurning off the (Pdb) prompt… with “c” (continue)
Seeing where you are… with “l” (list)
Stepping into subroutines… with “s” (step into)
Continuing… but just to the end of the current subroutine… with “r” (return)
Assign a new value
a)
!b = "B"Set a breakpoint
a)
break linenumberb)
break functionnamec)
break filename:linenumberTemporary breakpoint
a)
tbreak linenumberConditional 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/
bash - How to run python debugger with a script that takes command-line arguments? - Stack Overflow
how do I debug a python script?
Debug a python script being called from bash
debugging - How to debug a Python module run with python -m from the command line? - Stack Overflow
Videos
Try:
python -m pdb test.py arg1 arg2
Running python -m pdb runs pdb as a script. If test.py is somewhere in your path rather than your current working directory, this can be a helpful substitute:
python -m pdb "$(which test.py)" arg1 arg2
To debug a python script wit input arguments in Spyder IDE (2.3.4)
- Run > Configure...
- Select a run configuration > (Choose the script of interest that is open)
- General settings> Command line options:
arg1 arg2 arg3(use a space as delimiter just as in commandline) - Working directory: (Choose the folder)
- Click OK
Then Debug from menu. This is equivalent to execute the following in iPython console in Spyder.
debugfile('/Users/xxx/xxx/test.py', args='arg1 arg2', wdir='/Users/xxx/xxx/')
Doing it with PyCharm is quite similar.
- Run > Edit Configurations
- Choose the python script from the menu
- The
Configurationpane - Script parameters:
arg1 arg2
Then Run > Debug > Choose the file.
In iPyhton Console you can also try this (suppose test.py is in your current folder):
%run -d test.py arg1 arg2
im totally new in emacs and python itself, but my uni has specifically requested to use emacs so now i am trying to learn it. I have managed to write some python code but can't seem to find a way to run/debug it. any help would be greatly appreciated thank you.
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
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 )
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)