The title says it all. When you are working R
and using RStudio
, its really easy and simple to debug something by dropping a browser()
call anywhere in your code and seeing what goes wrong. Is there a way to do that with Python? I'm slowly getting very sick of print statement debugging.
It looks like you are looking for ipdb
The basic usage is to set:
import ipdb
ipdb.set_trace()
in your code to explore; this will take you right to that part of code, so you can explore all the variables at that point.
For your specific use case: "Would it be a setting in my Console so that it Opens pdb right before something crashes" (a comment to another answer), you can use context manager: launch_ipdb_on_exception
For example:
from ipdb import launch_ipdb_on_exception
def silly():
my_list = [1,2,3]
for i in xrange(4):
print my_list[i]
if __name__ == "__main__":
with launch_ipdb_on_exception():
silly()
Will take you to ipdb
session:
5 for i in xrange(4):
----> 6 print my_list[i]
7
ipdb> i
3
you can use python's debugger
import pdb
pdb.set_trace()
this will pause the script in debug mode
Example:
my_file=open('running_config','r')
word_count={}
special_character_count={}
import pdb
pdb.set_trace() <== The code will pause here
for config_lines in my_file.readlines():
l=config_lines.strip()
lines=l.upper()
Console:
> /home/samwilliams/workspace/parse_running_config/file_operations.py(6)<module>()
-> for config_lines in my_file.readlines():
(Pdb) print special_character_count
{}
(Pdb)
launch_ipdb_on_exception
, see my updated answer. –
Librate Since python 3.7 there is now also a build-in function: breakpoint. So simply call breakpoint()
in your code like you would call browser()
in R.
Since it is a build-in function you do not have to first perform an import statement, like the other answers, that you might forget to remove afterwards.
Some additional details on breakpoint().
Under the hood, breakpoint
calls the function sys.breakpointhook which by default would call the debugger pdb.set_trace()
from the python debugger library pdb.
But you can configure the function to use any debugger you like, such as the ipython debugger ipyd.set_trace()
, via the PYTHONBREAKPOINT environment variable.
© 2022 - 2024 — McMap. All rights reserved.
print(dir())
orprint(locals())
– Zuniga