How To Debug Python Code In Ipython And Jupyter Notebook

When you run python script file in ipython command console or jupyter notebook web page, if your source code has exception, it will throw out the exception and stop at the line where the exception occurred. In this situation, you can set breakpoints and run into ipython debug mode, then you can debug your python source code and fix the bugs. This article will tell you how to do it.

1. How To Debug Python Code In IPython.

There are 4 ways to enable debug mode in ipython, i will show them to you one by one. But before that, i will create a python script file which name is zero_divide_exception.py, below is it’s source code. When you run below python script file in ipython, and when you pass 0 to the third argument, it will throw ZeroDivisionError error.

zero_divide_exception.py

import sys

# this function will throw ZeroDivisionError if pass 0 to y. 
def zero_divide(x=1, y=0):

    z = int(x) / int(y)

    print(x,'/',y,' = ',z)

# print out command input arguments.
print('%run command has ',len(sys.argv),' arguments.')

# if there are 3 arguments in %run command.
if len(sys.argv) == 3:
    # get x, y value.
    x = sys.argv[1]
    y = sys.argv[2]

    zero_divide(x, y)
else:    
    zero_divide()

1.1 Run %debug Magic Command To Enable Debug Mode.

  1. Open a terminal and run command ipython to get into ipython interactive console.
    >ipython
  2. Run cd command to go to above file zero_divide_exception.py saved directory.
    In [1]: pwd
    Out[1]: 'C:\\Users\\song zhao'
    
    In [2]: cd C:/WorkSpace/JupyterExampleProject/
    C:\WorkSpace\JupyterExampleProject\
  3. Run command %run zero_divide_exception.py to execute above python script file. It will throw ZeroDivisionError error.
    In [3]: %run zero_divide_exception.py
    %run command has  1  arguments.
    ---------------------------------------------------------------------------
    ZeroDivisionError                         Traceback (most recent call last)
    C:\WorkSpace\JupyterExampleProject\JupyterSlideBarExample\zero_divide_exception.py in <module>
         16     zero_divide(x, y)
         17 else:
    ---> 18     zero_divide()
    
    C:\WorkSpace\JupyterExampleProject\JupyterSlideBarExample\zero_divide_exception.py in zero_divide(x, y)
          4 def zero_divide(x=1, y=0):
          5
    ----> 6     z = int(x) / int(y)
          7
          8     print(x,'/',y,' = ',z)
    
    ZeroDivisionError: division by zero
  4. If you want to get into debug mode, then run %debug command after ipython prompt, then you can see the prompt label is changed to ipdb>, now you can print out variable value to check the code.
    ZeroDivisionError: division by zero
    
    In [4]: %debug
    > c:\workspace\jupyterexampleproject\jupyterslidebarexample\zero_divide_exception.py(6)zero_divide()
          4 def zero_divide(x=1, y=0):
          5
    ----> 6     z = int(x) / int(y)
          7
          8     print(x,'/',y,' = ',z)
    # print out x, y's value in debug mode.
    ipdb> print(x, y)
    1 0
    ipdb>
  5. If you want to exit the debug mode, run exit command in ipython debug mode.
    ipdb> exit
    
    In [5]:

1.2 Activate %pdb Magic Command.

In ipython, if you want to run into debug mode automatically when execute python script file, you can runĀ %pdb magic command before execute the python script file like below.

READ :   How To Add Models To Django Admin Site

When you input %pdb command and press enter key, it will show you message Automatic pdb calling has been turned ON.

(env_jupyter_example) C:\Users\song zhao>ipython
Python 3.7.6 (default, Jan  8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 7.12.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: %pdb
Automatic pdb calling has been turned ON

In [2]: pwd
Out[2]: 'C:\\Users\\song zhao'

In [3]: %run C:/WorkSpace/JupyterExampleProject/zero_divide_exception.py 9 0
%run command has  3  arguments.
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
C:\WorkSpace\JupyterExampleProject\zero_divide_exception.py in <module>
     14     x = sys.argv[1]
     15     y = sys.argv[2]
---> 16     zero_divide(x, y)
     17 else:
     18     zero_divide()

C:\WorkSpace\JupyterExampleProject\zero_divide_exception.py in zero_divide(x, y)
      4 def zero_divide(x=1, y=0):
      5
----> 6     z = int(x) / int(y)
      7
      8     print(x,'/',y,' = ',z)

ZeroDivisionError: division by zero
> c:\workspace\jupyterexampleproject\zero_divide_exception.py(6)zero_divide()
      4 def zero_divide(x=1, y=0):
      5
----> 6     z = int(x) / int(y)
      7
      8     print(x,'/',y,' = ',z)

# print out variable values.
ipdb> print('x=',x,',y=',y)
x= 9 ,y= 0
ipdb>

1.3 Enable Automatic Debug Mode By Add –pdb Argument When Start Ipython.

Run ipython –pdb command to enter ipython interactive console.

>ipython --pdb

1.4 Add -d Parameter When Execute Python Script File Use %run Magic Command.

In [1]: %run -d C:/WorkSpace/JupyterExampleProject/zero_divide_exception.py
Breakpoint 1 at c:\workspace\jupyterexampleproject\zero_divide_exception.py:1
NOTE: Enter 'c' at the ipdb>  prompt to continue execution.
> c:\workspace\jupyterexampleproject\zero_divide_exception.py(1)<module>()
1---> 1 import sys
      2
      3 # this function will throw ZeroDivisionError if pass 0 to y.
      4 def zero_divide(x=1, y=0):
      5

ipdb>

The -d argument will make the execution process pause at the first line of the python script file. If you want to step over you can input s and press enter key.

ipdb> s
> c:\workspace\jupyterexampleproject\zero_divide_exception.py(4)<module>()
      2
      3 # this function will throw ZeroDivisionError if pass 0 to y.
----> 4 def zero_divide(x=1, y=0):
      5
      6     z = int(x) / int(y)

1.5 Set BreakPoint When Run Python Script File In Ipython.

If you want to set breakpoint at the line number which you want, you can add -d -b<line_number> arguments after %run magic command.

# run zero_divide_exception.py script in debug mode and set break point at code line 13.
In [5]: %run -d -b13 C:/WorkSpace/JupyterExampleProject/zero_divide_exception.py 9 3
Breakpoint 1 at c:\workspace\jupyterexampleproject\zero_divide_exception.py:13
NOTE: Enter 'c' at the ipdb>  prompt to continue execution.
> c:\workspace\jupyterexampleproject\zero_divide_exception.py(1)<module>()
----> 1 import sys
      2
      3 # this function will throw ZeroDivisionError if pass 0 to y.
      4 def zero_divide(x=1, y=0):
      5

# enter c to continue the script execution.
ipdb> c
%run command has  3  arguments.
# the execution process will stop at line 13.
> c:\workspace\jupyterexampleproject\zero_divide_exception.py(13)<module>()
     11
     12 # if there are 2 arguments
1--> 13 if len(sys.argv) == 3:
     14     x = sys.argv[1]
     15     y = sys.argv[2]

# you can print out local variable values.
ipdb> print(sys.argv)
['C:/WorkSpace/JupyterExampleProject/zero_divide_exception.py', '9', '3']
ipdb>

2. How To Debug Python Script File Source Code In Jupyter Notebook.

To debug python script file in jupyter notebook, it is much similar with section 1. What you need to do is just run the command ( %debug, %pdb, %run -d -b<line_number>) in jupyter notebook web page line cell.

  1. Start jupyter notebook web server, and create a jupyter notebook file DebugPythonScriptInIpython.ipynb like below picture ( How To Start Jupyter Notebook In Anaconda Python Virtual Environment ). The zero_divide_exception.py file is also in the list.
    debug python script file in jupyter notebook
  2. Click DebugPythonScriptInIpython.ipynb file to edit it, and run below command in the first line cell.
    %run -d -b10 zero_divide_exception.py
  3. Then you can see the execution process paused at the first line of zero_divide_exception.py file. Enter c and press enter key, it will continue to run and stop at the breakpoint that is set at code line number 10.
    run and pause at the first break point which is set at code line number 10
READ :   How To Add New Model Field To Exist Django Model

Reference

  1. How To Start Jupyter Notebook In Anaconda Python Virtual Environment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.