Once the post-mortem debugger kicks in, we can inspect all of the variables in the current frame and even run new code to help us figure out what's wrong and attempt to make a fix. Running 'cont' or 'step' will restart the program Let's try post-mortem debugging this error: $ python3 -mpdb script.pyįile "/usr/lib/python3.4/pdb.py", line 1661, in mainįile "/usr/lib/python3.4/pdb.py", line 1542, in _runscriptįile "/usr/lib/python3.4/bdb.py", line 431, in run Try running it normally and you will see one of the bugs: $ python3 script.py We're expecting the program to do some basic math operations on random numbers in a loop and print the result. To see how these basic debugging steps work, I'll be using this (buggy) program: import random From here, you can run Python code and debugger commands at the prompt to inspect the current program state. If the program throws an unhandled exception, you'll also see a (Pdb) prompt, but with the program execution stopped at the line that threw the exception. At this point, you can use quit / q or Ctrl+D to exit the debugger. If the program executes successfully, you will be taken back to the (Pdb) prompt where you can restart the execution again. To start execution, you use the continue or c command. You can run an existing script with the post-mortem debugger by using Python's -mpdb option: python3 -mpdb path/to/script.pyįrom here, you are dropped into a (Pdb) prompt. After that, you attempt to make a fix and repeat the process until the problem is resolved. This is where you run your program as usual, but whenever an unhandled exception is thrown, you drop down into the debugger to poke around in the program state. The first workflow I used after moving away from print debugging was pdb's "post-mortem debugging" mode. modules installed from PyPI) and the standard library. Once you get good at this, it means more time spent diving into issues and less time context switching back and forth between your editor and the command line.Īlso, by not touching the underlying source code, you will have the ability to step into third party code (e.g. With pdb, you have a lot more flexibility to run, resume, and alter the execution of your program without touching the underlying source. interactive debuggingįirst, why would you want to use an interactive debugger instead of inserting print or logging statements into your code? In this post I will show you a few tips I've picked up over the years to level up my interactive debugging skills. For a long time, I stuck to basic print-debugging and used pdb on a limited basis, which meant I missed out on a lot of features that would have made debugging faster and easier. Python's built-in pdb module is extremely useful for interactive debugging, but has a bit of a learning curve.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |