using the debugger in python - michigan state … the debugger in python “in industry there is a...
Post on 07-Mar-2018
232 Views
Preview:
TRANSCRIPT
Using The Debugger In Python
“Inindustrythereisatermforprogrammerswhodonotmakeextensiveuseofthedebugger: unemployed.”– TheWizardofOz
TopicsWe’llCover
•Python3’sbuilt-inPDBDebuggingmodule.•Debugging,whyweneedit,modesofthought,usingitformorethanfixing.
TheOnlineReference
http://atbe.me
ClicktheUsingTheDebuggerInPython- WorkshopReference linkonthefrontpage.
WhatHappensWhenWeRunOurcode?
Onasinglecoreprocessor,only 1 instruction atanyonemomentintimecanexecute.
What’sAnInstruction?
Wedon’tcareatm.Justthinkittermsoflinesofcode.Onelinemeansdoing1thing.
Caveat: Functions arespecial.Askforonething,theydomany.Ifyou’reconfusedit’sokay,it’llstarttoclearupbythetimewestartdebugging.
What’sADebugger?
Adebuggerisatoolthatcanhelpyoupause aprogram.
Whenaprogramispaused,it’sstate ispreservedandyoucantinkeraroundandchangethingsasyou’dlike.
WhyDoWeNeedDebuggers?
Alotofpeoplemightarguethatwedon’tneeddebuggersorthattheycancodejustfinewithoutthem.
Butinreality,debuggersaresomeofthemosthelpfultoolswhenworkingonsystemsthathavethousandsorevenhundredsofthousands oflinesofcode.
“Themosteffectivedebuggingtoolisstillcarefulthought,coupledwithjudiciouslyplacedprintstatements.”–BrianKernighan
WhyDoWeNeedDebuggers?(continued)
Exception:We’retalkingaboutscripting/systemslanguages.Youcan’tdebugMarkupcodelikehtmlalone.
WhenToUseTheDebugger?
Justafew ofmanyexamples:
Whenyourcodeisbroken (didn’tdowhatyouexpecteditto).
Whenyouwanttotestarareconditionforanifstatement.
Whenyou’rereadingsomeoneelse'scodeandwanttounderstandtheflowof
execution.(Idothisalot)
Whenyouwanttoseethevalues ofyourvariables atagivenmoment;maybe
they’renotwhatyouexpectedthemtobe.
HowDoWedebug,correctly?
Debuggingisafourstepprocess:
• DiscoveringtheBug. Isthereone?Itisnotalwaysobviousthatyouhaveabug.(Why?)• IsolatingtheBug.Whereisit?Locatethepart(s)ofthecodethatiscausingthebug.• FindingtheBug. Whatexactlyiswrongwiththebuggycodefragment?• FixingtheBug. Howshouldthebuggyfragmentberewritten?
Source:https://courses.engr.illinois.edu/ece390/books/labmanual/debugging.html
GetaLinuxDocker
We’regoingtobeusinganonlineIDEprovidedbytutorialspoint.
http://atbe.me
ClicktheUsingTheDebuggerInPython- WorkshopReference linkonthefrontpage.
Notice
Forexample
```
ls```
Meanstypelsinyourterminal,andpressenter.
Anywherewhereyousee```,thatiscodetoberunintheterminal.
Debugging– StartingtheDebugger
HereisonewaytostartaprograminPDB:
Runthistostartourfirstdebuggingsession:
```
python3–mpdb hello_world.py```
Debugging– StartingtheDebugger
Startingthedebuggerataspecificpointinyourprogramonlyrequiresonelineofcode.
Debugging– StartingtheDebugger
Startingthedebuggerataspecificpointinyourprogramonlyrequiresonelineofcode.
AddthefollowingcodetoanyPythonfile:
```
importpdb;pdb.set_trace()```
Breakpoints arekeytoefficientdebugging
Whenthedebuggerseesabreakpoint,itwillstopandpromptyouforacommand
Theb(break)commandisusedtoseeallthesetbreakpoints,andtosetabreakpoint.
b ->willlistallthebreakpoints
PDBCommandà b
Thebcommandisusedtoseeallthesetbreakpoints,andtosetabreakpoint.
b ->willlistallthebreakpoints
b#->willsetabreakpointatline#
PDBCommandà b
Thecl(clear)commandallowsyoutoremoveabreakpoint.
cl#à Removesthebreakpointwithnumber#.
PDBCommandà cl
Thel(list)commandisusedtolistthecodesurroundingourcurrentline.
Typinglmorethanoncewillprintthenext 11lines.
PDBCommandà l(list)
Thel(list)commandisusedtolistthecodesurroundingourcurrentline.
Typinglmorethanoncewillprintthenext 11lines.
l ->printsthe11surroundinglines
PDBCommandà l(list)
Thep(print)commandallowsyoutoprintthevalueofanyexpression.
p{expression}->Executesandprintsthevalueofsomeexpression.
PDBCommandà p
Thec(continue)commandtellsthedebugger“continueexecutinguntilyouencountera
breakpoint.”
PDBCommandà c
Thec(continue)commandtellsthedebugger“continueexecutinguntilyouencountera
breakpoint.”
Handywhenyouneedtodeferexecutionuntilyoureachthebreakpointyouset(example:loops).
PDBCommandà c
Steppingisimportantwhenyou’removingaroundwithinsomecodeinthedebugger.
Beforewelearntostep,weneedtobeabletovisualizewhatastepis.
Programstarts
get_person_nameiscalled
get_person_namerunning
get_person_namereturns
get_person_ageiscalled
get_person_agerunning
get_person_agereturns
say_helloiscalled
say_hellorunning
year_to_seciscalled
year_to_secrunning
say_helloreturns
say_hellorunning
year_to_secreturns
Programends
Theuntilcommandtellsthedebugger“runtheprogramuntilyouhitthislinenumber.”
until{line#}à Runscodeuntilline#isreached,andwaits.
PDBCommandà until
Thes(step)commandwillstepintoafunctioncalledonthecurrentline.
Ifthereisn’tafunctiononthecurrentline,s(step)actsliken(next) andsimplyexecutesthecurrentline
andmovestothenextline.
PDBCommandà s(step)
Thes(step)commandwillstepintoafunctioncalledonthecurrentline.
Ifthereisn’tafunctiononthecurrentline,s(step)actsliken(next) andsimplyexecutesthecurrentline
andmovestothenextline.
Youcanthinkofs(step) asaStepInto command.
PDBCommandà s(step)
Ther(return)commandcontinuestheexecutionofthecurrentfunctionuntilthefunctionreturns.
PDBCommandàr(return)
Ther(return)commandcontinuestheexecutionofthecurrentfunctionuntilthefunctionreturns.
Youcanthinkofr(return) asaStepOutOf command.
PDBCommandàr(return)
Commands:
• b(break)Setbreakpoint• cl(clear)Deletebreakpoint• l(list)list11surroundinglines• p(print)Evaluateandprintcodeoncurrentline• n(next)“StepOver”• c(continue)Continueexecution,stopatbreakpoints• untilExecuteuntilgivenlinenumber
• s(step)“StepInto”• r(return)“StepOutOf”
ThinkofStackFramesasthelistofsteps takenasaprogramwasrunning.
MovingthroughStackFramesisveryusefulwhenworkingwithrecursive functions.
StackFrames
ThinkofStackFramesasthelistofsteps takenasaprogramwasrunning.
MovingthroughStackFramesisveryusefulwhenworkingwithrecursive functions.
PythonNote: AllPythonprogramsarestartedwiththeexecfunction.SoexecalwaysatthetopoftheStack.
StackFrames
ThinkofStackFramesasthestepstakenwhileaprogramisrunning.
Stackframestellus:
StackFrames
• Whatfunction(s) gotustowhereweare.• Whichstatement fromeachfunctionexecutedthecurrentfunction.• Wherethecodeforeachfunctioniscontained.
Thew(where)/bt commandwillprintthecurrentStackFrameoftheprogram.
ThisiswhatPythonsPDBmoduleprintsoutwhenweusetheworbt command
(yes,theybothdothesamething)
PDBCommandàw(where)/bt
Youcanmoveupanddowninastackframe.
Thismeansmovinguptoafunctionthatcalledyou,ormovingintoafunctionyoucalled.
StackFrames
Theu(up)commandwillmoveyourprogramupinthestackframe.
u(up) couldalsobeusedasaStepOutOf.
PDBCommandàu(up)
Theu(up)commandwillmoveyourprogramupinthestackframe.
u(up) functionsasaStepOutOfaswell.
u(up)#Moveupthestackframe#frames.
PDBCommandàu(up)
Thed(down)commandwillmoveyourprogramdowninthestackframe.
d(down)#àMovedownthestackframe#frames.
PDBCommandàd(down)
LookintoStackFramessomemoreifyoucan.
TherearesomemorethingstobelearnedaboutStackFrames.Checkouttherecommendedreadings.
StackFrames
OtherusefulPDBCommands
• source obj – printsthesourcecodeofobj.• interact – startsapythonREPLwhocanaccess
anyvariablesthecurrentlineofcodecouldhave.• restart – restartthecurrentdebuggedprogram
anddebuggingsession.• whatis arg – printthetypeofthearg.• longlist – printthewholesourcecodeforthe
currentfunctionorframe.
Mostoftheconceptswe’velearneduptillnowcanbeusedwithdebuggersforotherlanguages.
lldb/gdb – C/C++jdb – Java
debugger(browser)– Javascriptpudb – Python
…
top related