วิธีที่ง่ายที่สุดในการ Debug โปรแกรมด้วย Jupyter Notebook คือการใช้ Magic Command %debug เมื่อใดก็ตามที่เราเจอ Error ให้เราสร้าง cell ขึ้นมาใหม่ แล้วพิมพ์ว่า %debug แล้วสั่งรัน ระบบจะเปิด command line

ดีบักโปรแกรมด้วย %debug กับ Python debugger

ให้เราสามารถทดสอบโค้ด และดูค่าตัวแปรต่าง ๆ ได้ทันที มีคำสั่งที่ใช้บ่อย ๆ ดังนี้

  • ชื่อตัวแปร แสดงค่าของตัวแปร
  • N (Next) รันบรรทัดต่อไป ( สังเกตเครื่องหมาย → คือบรรทัดที่รันอยู่ )
  • S (Step) รันบรรทัดต่อไป ถ้าเป็นฟังก์ชันก็เข้าไปในฟังก์ชัน
  • R (Return) รันต่อไปจน Return ออกจากฟังก์ชันปัจจุบัน
  • W (Where) ดู Stack Trace
  • L (List) ลิสต์ดู Source Code
  • C (Continue) รันไปจน breakpoint ถัดไป
  • A (Argument) ดูรายการ Argument ของฟังก์ชันปัจจุบัน
  • P (Print) Print ค่าตัวแปร เช่น p i หรือ ถ้าเป็น Expression ก็ Eval แล้ว print ออกมา เช่น p i+500
  • Q (Quit) ออกจาก debugger
import iPython debugger แล้วใส่คำสั่ง set_trace() เพื่อสร้าง breakpoint

หรือเราสามารถ import iPython debugger แล้วใส่คำสั่ง set_trace() เพื่อสร้าง breakpoint ไว้ตรงบรรทัดที่ต้องการ

เมื่อเราสั่งรันระบบจะรัน cell นั้นจนมาหยุดที่ breakpoint แรก ที่เราสร้างไว้ เราก็สามารถใช้คำสั่ง python debugger เรียกดูค่าตัวแปรได้เหมือนด้านบน

from IPython.core.debugger import set_trace

set_trace()

แชร์ให้เพื่อน:

Surapong Kanoktipsatharporn on FacebookSurapong Kanoktipsatharporn on LinkedinSurapong Kanoktipsatharporn on Rss
Surapong Kanoktipsatharporn
Solutions Architect at Bua Labs
The ultimate test of your knowledge is your capacity to convey it to another.

Published by Surapong Kanoktipsatharporn

The ultimate test of your knowledge is your capacity to convey it to another.