How To Use Python breakpoint() Function To Debug Python Code

The breakpoint() function in Python can be used to debug Python code. When the breakpoint() function is called, it will pause the execution of the program and start a debugging session. In this article, I will tell you how to use the python breakpoint() function to enter python debug mode and debug python source code with examples.

1. How To Use Python breakpoint() Function To Debug Python Code.

  1. Below are the steps to use the breakpoint() function to debug Python code.
  2. Place the breakpoint() function in the code where you want to start the debugging session.
    def my_function(x, y):
        result = x + y
        print("before breakpoint()")
        breakpoint()   # start debugging session here
        print("after breakpoint()")
        return result
    
    result = my_function(1, 2)
    
    print(result)
  3. Run the Python script containing the breakpoint() function.
  4. When the breakpoint() function is reached during the execution of the Python script, the program will pause and enter a debugging session.
  5. In the debugging session, you can use various commands to inspect the state of the program and step through the code line by line. Some common commands include:
  6. n or next: Execute the next line of code.
  7. s or step: Step into a function call.
  8. c or continue: Continue the execution of the program until the next breakpoint or the end of the script.
  9. p or print: Print the value of a variable.
  10. q or quit: Quit the debugging session.

2. Use Python breakpoint() Function To Debug Python Code Example.

  1. Save the above python source code ( in section 1 ) in a python file Test.py.
  2. Run the python file in command line with the below command, when it run to the breakpoint() function, the source code pause.
  3. You can press key n to continue to run to the next line of code.
    (MyPython) D:\WorkSpace\Work\dev2qa.com-backup>python Test.py
    before breakpoint()
    > d:\workspace\work\dev2qa.com-backup\test.py(5)my_function()
    -> print("after breakpoint()")
    (Pdb) n
    after breakpoint()
    > d:\workspace\work\dev2qa.com-backup\test.py(6)my_function()
    -> return result
    (Pdb) n
    --Return--
    > d:\workspace\work\dev2qa.com-backup\test.py(6)my_function()->3
    -> return result
    (Pdb) n
    > d:\workspace\work\dev2qa.com-backup\test.py(10)<module>()
    -> print(result)
    (Pdb) n
    3
    --Return--
    > d:\workspace\work\dev2qa.com-backup\test.py(10)<module>()->None
    -> print(result)
    (Pdb) n

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.