DEV Community

Cover image for Debugging Techniques: Python and Linux Using Error Catching
Johnny Santamaria
Johnny Santamaria

Posted on

Debugging Techniques: Python and Linux Using Error Catching

Python and Linux complement each other for projects due to Python's flexibility and Linux's powerful scripting, ideal for automation and development.

Debugging is an essential skill for developers. Whether you’re working in Python or Linux, effective debugging techniques can save hours of frustration. This article explores multiple techniques for debugging in Python and Linux, focusing on error-catching approaches.

Debugging Techniques in Python and Linux Using Error Catching

Debugging is an essential skill for developers. Whether you’re working in Python or Linux, effective debugging techniques can save hours of frustration. This article explores multiple techniques for debugging in Python and Linux, focusing on error-catching approaches.

Debugging in Python

  1. Using try and except Blocks

Python’s try and except blocks allow you to catch and handle exceptions gracefully.

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Error: {e}")
Enter fullscreen mode Exit fullscreen mode

Best Practice: Catch specific exceptions rather than using a generic except block.

  1. Logging Errors

Using the logging module provides more flexibility than print statements for error tracking.

import logging

logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')

try:
    result = 10 / 0
except ZeroDivisionError as e:
    logging.error("Exception occurred", exc_info=True)
Enter fullscreen mode Exit fullscreen mode

Tip: Save logs to a file for persistent error tracking.

  1. Debugging with pdb (Python Debugger)

The pdb module offers an interactive debugging environment.

import pdb

def buggy_function(x, y):
    pdb.set_trace()
    return x / y

buggy_function(10, 0)
Enter fullscreen mode Exit fullscreen mode

To navigate through the code, use commands like n (next), c (continue), and q (quit).

  1. Using Assertions

Assertions help catch errors early by testing conditions that must be true.

x = -1
assert x > 0, "x must be positive"
Enter fullscreen mode Exit fullscreen mode

Warning: Assertions should not be used for input validation in production code.

  1. Third-Party Debugging Tools

ipdb: An enhanced version of pdb with tab completion and syntax highlighting.

pyringe: A powerful debugging tool for inspecting live Python processes.

Debugging in Linux

  1. Checking Logs

Logs are invaluable for diagnosing issues in Linux. Common locations include:

System logs: /var/log/syslog or /var/log/messages

Application-specific logs

sudo tail -f /var/log/syslog

  1. Using strace

strace helps you trace system calls made by a process.

strace -o trace.log python3 script.py

Analyze the trace.log file to identify problematic system calls.

  1. Using gdb (GNU Debugger)

gdb is essential for debugging compiled applications, but it also works for Python with the python-gdb extension.

gdb python3
(gdb) run script.py
Enter fullscreen mode Exit fullscreen mode

Use bt (backtrace) to investigate crashes.

  1. Monitoring Resource Usage

High resource usage can cause errors. Tools like top, htop, and iotop are excellent for monitoring system performance.

top

  1. Using dmesg for Kernel Messages

Definition: kernel
the core component of an operating system that manages hardware resources and facilitates communication between hardware and software. It acts as a bridge, handling tasks such as process management, memory allocation, and input/output operations.

dmesg displays kernel-related messages, useful for diagnosing hardware or driver issues.

dmesg | tail -20

Combining Python and Linux Debugging

When debugging Python applications on Linux, you often need to combine techniques from both domains.

Example: Debugging a Python Script with File Permissions Issue

Python Side: Add exception handling for file operations.

try:
    with open("/root/secret.txt", "r") as file:
        data = file.read()
except PermissionError as e:
    print(f"Permission error: {e}")
Enter fullscreen mode Exit fullscreen mode

Linux Side: Check file permissions.

ls -l /root/secret.txt

Trace System Calls: Use strace to trace the issue.

strace -e open python3 script.py

General Debugging Tips

Reproduce the Issue: Consistently reproducing the bug helps narrow down the problem.

Use Version Control: Tools like Git allow you to track changes and isolate problematic commits.

Document Fixes: Maintain a record of issues and resolutions for future reference.

Automate Tests: Use frameworks like unittest or pytest to prevent regressions.

Conclusion

By mastering these debugging techniques in Python and Linux, you can significantly improve your efficiency and problem-solving skills. Remember, debugging is not just about fixing errors—it’s about understanding your code and system behavior more deeply.

Image credit

Top comments (0)