Debug

Debugging

assert

檢查變數的值

x = 5
assert x == 5, "x should be 5"

assert type(username) == str, "username must be a string"
def calculate_square_root(x):
    assert x >= 0, "The input must be non-negative."
    return x ** 0.5

print(calculate_square_root(4))  # 輸出: 2.0
print(calculate_square_root(-1)) # 引發 AssertionError 並顯示 "The input must be non-negative."

檢查函示回傳值有無偶數

def get_even_number(numbers):
    for num in numbers:
        if num % 2 == 0:
            return num
    assert False, "No even number found in the list."

numbers = [1, 3, 5, 7, 10]
print(get_even_number(numbers))  # 輸出: 10
numbers = [1, 3, 5, 7]
print(get_even_number(numbers))  # 引發 AssertionError 並顯示 "No even number found in the list."

 

prinf debugging
print("Processing {}".format(basename))
strace
# Installation on RHEL if it's not installed
yum install strace

# Tracing system calls made by a program
strace ./my-program.py
strace -o my-program.strace ./my-program

Crash

pdb

功能:

pdb3 myprog.py

pdb-subcommands

(Pdb) continue
...
(Pdb) print(row)

Step 1: Set a breakpoint

import pdb


def add_numbers(a, b):
    pdb.set_trace()  # This will set a breakpoint in the code
    result = a + b
    return result


print(add_numbers(3, 4))

Setp 2: Enter the interactive debugger

Step 3: Inspect variables

To inspect the variables, simply type the single character, p, then the variable name to see its current value. For instance, if you have a variable in your code named sentiment_score, just type p sentiment_score at the pdb prompt to inspect its value.

Step 4: Modify variables

A big advantage of pdb is that you can change the value of a variable directly in the debugger. For example, to change sentiment_score to 0.9, you'd type !sentiment_score = 0.9.

To confirm these changes, use a or directly probe the value with p <value name>.

 Step 5: Exit the debugger

When you’re done, simply enter q (quit) to exit the debugger and terminate the program.

Post-mortem debugging

python -m pdb your_script.py

Memory Leaks

當不再需要的記憶體未釋放時,就會發生記憶體洩漏。即使重新啟動,仍需要大量記憶體的應用程式,很可能指向記憶體洩漏

memory_profiler

第一欄顯示每一行執行時所需的記憶體數量。第二欄顯示每一行所增加的記憶體

python3 -m memory_profiler myprog.py

In Code

from memory_profiler import profile

...
...

@profile
def main():
  ...
  ...
  


Revision #11
Created 2024-12-20 14:27:55 CST by A-Lang (Admin)
Updated 2025-12-17 13:22:46 CST by A-Lang (Admin)