Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R's browser() equivalent in Python

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.

like image 684
Adam Avatar asked Jun 23 '17 18:06

Adam


2 Answers

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
like image 155
Akavall Avatar answered Sep 19 '22 00:09

Akavall


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) 
like image 43
Sam Williams Jebaraj Avatar answered Sep 21 '22 00:09

Sam Williams Jebaraj