Python Debugging Techniques
In this page:
Print Statement से Debugging
Code में महत्वपूर्ण जगहों पर print() statements डालना ताकि execution के दौरान variable values दिखें, यह सबसे सरल debugging technique है -- इसके लिए किसी tool या setup की ज़रूरत नहीं, हालाँकि काम पूरा होने के बाद उन prints को हाथ से हटाना या comment out करना पड़ता है।
उदाहरण: Print Statement Debugging
def add(a, b):
print("a =", a, "b =", b) # simplest debugging technique, just inspect the values
return a + b
print(add(2, 3))
Assert Statements का इस्तेमाल
एक assert condition statement यह जाँचता है कि उस बिंदु पर code में condition सही है या नहीं, और अगर नहीं है तो तुरंत AssertionError raise कर देता है।
Asserts invalid internal state को उसके असली source के पास, जल्दी पकड़ने के लिए उपयोगी हैं, बजाय इसके कि bug कहीं आगे जाकर confusingly सामने आए।
उदाहरण: Using Assert Statements
def divide(a, b):
assert b != 0, "b must not be zero" # raises AssertionError immediately if violated
return a / b
print(divide(10, 2))
Logging Module
Built-in logging module बिखरे हुए print statements का production-grade replacement है: यह severity levels (DEBUG, INFO, WARNING, ERROR) को support करता है, code edit किए बिना on या off किया जा सकता है, और output को console की तरह ही आसानी से files में भी भेज सकता है।
उदाहरण: The Logging Module
import logging
logging.basicConfig(level=logging.DEBUG) # sets the minimum severity level to show
logging.debug("Starting process")
logging.info("Process running")
Programmatic Tracebacks
try/except block के अंदर, आप पूरे program को crash होने देने के बजाय, caught exception का पूरा traceback (traceback module के ज़रिए) programmatically capture और print कर सकते हैं।
इससे आप application को चलाए रखते हुए भी detailed error information log कर सकते हैं।
उदाहरण: Programmatic Tracebacks
import traceback
try:
1 / 0
except ZeroDivisionError:
traceback.print_exc() # prints the full traceback without crashing the program
pdb Module की अवधारणा
pdb, Python का built-in interactive command-line debugger है, जो आपको एक specific line पर execution रोकने (breakpoint() या import pdb; pdb.set_trace() के ज़रिए) और फिर एक-एक line करके code के through step करने, variables को live inspect करते हुए, देता है -- यह हाथ से print statements जोड़ने-हटाने से कहीं ज़्यादा powerful है।
उदाहरण: The pdb Module Concept
# import pdb; pdb.set_trace() # pauses execution here interactively
print("pdb lets you step through code line by line")
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first:
- Python PEP 8 Style Guide
- Python Debugging Techniques
- Python Testing with unittest
- Python Common Mistakes
- Python Interview Questions
- Python map() & filter()
- Python reduce()
- Python zip() & enumerate()
- Python sorted() & key Functions
- Python Comprehensions Advanced
- Python Turtle Graphics
- Python tkinter Introduction
- Python tkinter Widgets
- Python pygame Introduction
- Python Mini Projects