How To Debug Python Code In Ipython And Jupyter Notebook

When you run a python script file in the iPython command console or jupyter notebook web page, if your source code has an 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.

1.1 Python Source Code Without Enable Debug Mode.

  1. There are 4 ways to enable debug mode in iPython, I will show them to you one by one.
  2. But before that, I will create a python script file which name is zero_divide_exception.py, below is its source code. When you run the below python script file in iPython, and when you pass 0 to the third argument, it will throw a ZeroDivisionError error.
  3. 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.2 Run %debug Magic Command To Enable Debug Mode.

  1. Open a terminal and run the 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 the above python script file. It will throw a 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 the %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 the exit command in ipython debug mode.
    ipdb> exit
    
    In [5]:

1.3 Activate %pdb Magic Command.

  1. In ipython, if you want to run into debug mode automatically when executing the python script file, you can run the %pdb magic command before executing the python script file like below.
  2. When you input the %pdb command and press enter key, it will show you the 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.4 Enable Automatic Debug Mode By Add –pdb Argument When Start Ipython.

  1. Run ipython –pdb command to enter ipython interactive console.
    >ipython --pdb

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

  1. The -d argument will make the execution process pause at the first line of the python script file.
    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>
  2. 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.6 Set BreakPoint When Run Python Script File In Ipython.

  1. If you want to set a 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.

  1. To debug the python script file in jupyter notebook, it is much similar to 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.
  2. Start jupyter notebook web server, and create a jupyter notebook file DebugPythonScriptInIpython.ipynb(you can read the article How To Start Jupyter Notebook In Anaconda Python Virtual Environment ). The zero_divide_exception.py file is also in the list.
  3. Click DebugPythonScriptInIpython.ipynb file to edit it, and run the below command in the first line cell.
    %run -d -b10 zero_divide_exception.py
  4. 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.

Reference

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

Leave a Comment

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.