Debug

Debugging

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

assert type(username) == str, "username must be a string"
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 #9
Created 20 December 2024 14:27:55 by Admin
Updated 20 December 2024 16:35:38 by Admin