105
Using The Debugger In Python “In industry there is a term for programmers who do not make extensive use of the debugger: unemployed.” – The Wizard of Oz

Using The Debugger In Python - Michigan State … The Debugger In Python “In industry there is a term for programmers who do not make extensive use of the debugger:unemployed.”

  • Upload
    vomien

  • View
    237

  • Download
    0

Embed Size (px)

Citation preview

Using The Debugger In Python

“Inindustrythereisatermforprogrammerswhodonotmakeextensiveuseofthedebugger: unemployed.”– TheWizardofOz

Background

JuniorCSEMemberofDSE(DataSci &Eng)ResearchLab

TopicsWe’llCover

•Python3’sbuilt-inPDBDebuggingmodule.•Debugging,whyweneedit,modesofthought,usingitformorethanfixing.

TheOnlineReference

http://atbe.me

ClicktheUsingTheDebuggerInPython- WorkshopReference linkonthefrontpage.

WhatDoesaProgramDo?

Whateveryoutellitto.

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

DebuggingPythonCode

We’regoingtobeusingPDB

Yes,therearealternatives,I’llbrieflyreviewthoseattheend.

GetaLinuxDocker

We’regoingtobeusinganonlineIDEprovidedbytutorialspoint.

http://atbe.me

ClicktheUsingTheDebuggerInPython- WorkshopReference linkonthefrontpage.

Terminal

Files

ProjectSettings

FileSettingsRunCodeButton

Editor

Import

Upload

Notice

Forexample

```

ls```

Meanstypelsinyourterminal,andpressenter.

Anywherewhereyousee```,thatiscodetoberunintheterminal.

Terminal

Debugging– StartingtheDebugger

HereisonewaytostartaprograminPDB:

Runthistostartourfirstdebuggingsession:

```

python3–mpdb hello_world.py```

Debugging– StartingtheDebugger

Debugging– StartingtheDebugger

Startingthedebuggerataspecificpointinyourprogramonlyrequiresonelineofcode.

Debugging– StartingtheDebugger

Startingthedebuggerataspecificpointinyourprogramonlyrequiresonelineofcode.

AddthefollowingcodetoanyPythonfile:

```

importpdb;pdb.set_trace()```

Debugging– Allthecommands– Use`help`Command

BREAKPOINTS

Breakpointsarekeytoefficientdebugging

Breakpoints arekeytoefficientdebugging

Whenthedebuggerseesabreakpoint,itwillstopandpromptyouforacommand

Letstryandsetabreakpointinthetime_activity_mapper.py program

b(break)

Theb(break)commandisusedtoseeallthesetbreakpoints,andtosetabreakpoint.

PDBCommandà b

Theb(break)commandisusedtoseeallthesetbreakpoints,andtosetabreakpoint.

b ->willlistallthebreakpoints

PDBCommandà b

Thebcommandisusedtoseeallthesetbreakpoints,andtosetabreakpoint.

b ->willlistallthebreakpoints

b#->willsetabreakpointatline#

PDBCommandà b

cl(clear)

Thecl(clear)commandallowsyoutoremoveabreakpoint.

PDBCommandà cl

Thecl(clear)commandallowsyoutoremoveabreakpoint.

cl#à Removesthebreakpointwithnumber#.

PDBCommandà cl

l(list)

Thel(list)commandisusedtolistthecodesurroundingourcurrentline.

PDBCommandà l

Thel(list)commandisusedtolistthecodesurroundingourcurrentline.

Typinglmorethanoncewillprintthenext 11lines.

PDBCommandà l(list)

Thel(list)commandisusedtolistthecodesurroundingourcurrentline.

Typinglmorethanoncewillprintthenext 11lines.

l ->printsthe11surroundinglines

PDBCommandà l(list)

p(print/evaluate)

Thep(print)commandallowsyoutoprintthevalueofanyofthevariablesinyourprogram.

PDBCommandà p

Thep(print)commandallowsyoutoprintthevalueofanyexpression.

p{expression}->Executesandprintsthevalueofsomeexpression.

PDBCommandà p

NameError: name 'activity_time' isnot defined

n(next)

Then(next)commandtellsthedebuggertoevaluatethecurrentline,andmovetothenext.

PDBCommandà n

c(continue)

Thec(continue)commandtellsthedebugger“continueexecutinguntilyouencountera

breakpoint.”

PDBCommandà c

Thec(continue)commandtellsthedebugger“continueexecutinguntilyouencountera

breakpoint.”

Handywhenyouneedtodeferexecutionuntilyoureachthebreakpointyouset(example:loops).

PDBCommandà c

STEPPING

Stepping isimportantwhenyou’removingaroundwithinsomecodeinthedebugger.(recursion…coughcough)

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

Steppingisimportantwhenyou’removingaroundwithinsomecodeinthedebugger.

Stepover.Stepinto.Stepoutof.

```python3–mpdb function_parts.py

```

until

Theuntilcommandtellsthedebugger“runtheprogramuntilyouhitthislinenumber.”

PDBCommandà until

Theuntilcommandtellsthedebugger“runtheprogramuntilyouhitthislinenumber.”

until{line#}à Runscodeuntilline#isreached,andwaits.

PDBCommandà until

s(step)

Thes(step)commandwillstepintoafunctioncalledonthecurrentline.

PDBCommandà s(step)

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)

r(return)

Ther(return)commandcontinuestheexecutionofthecurrentfunctionuntilthefunctionreturns.

PDBCommandàr(return)

Ther(return)commandcontinuestheexecutionofthecurrentfunctionuntilthefunctionreturns.

Youcanthinkofr(return) asaStepOutOf command.

PDBCommandàr(return)

n(next)…remembern?

Then(next)commandcanbethoughtofasStepOver.

PDBCommandàn(next)

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”

STACKFRAMES

ThinkofStackFramesasthelistofsteps takenasaprogramwasrunning.

StackFrames

ThinkofStackFramesasthelistofsteps takenasaprogramwasrunning.

MovingthroughStackFramesisveryusefulwhenworkingwithrecursive functions.

StackFrames

ThinkofStackFramesasthelistofsteps takenasaprogramwasrunning.

MovingthroughStackFramesisveryusefulwhenworkingwithrecursive functions.

PythonNote: AllPythonprogramsarestartedwiththeexecfunction.SoexecalwaysatthetopoftheStack.

StackFrames

ThinkofStackFramesasthestepstakenwhileaprogramisrunning.

Stackframestellus:

StackFrames

• Whatfunction(s) gotustowhereweare.• Whichstatement fromeachfunctionexecutedthecurrentfunction.• Wherethecodeforeachfunctioniscontained.

ThinkofStackFramesasthestepstakenwhileaprogramisrunning.

StackFrames

WhatdoestheStackFrameherelooklike?

StackFrames

JustLookAttheStepsTakensay_helloiscalled

say_hellorunning

year_to_seciscalled

year_to_secrunning

PythonPDBStackTrace– say_hello

LetsseewhattheStackFrameslooklikeforarecursiveFactorial(n)functionforn=4

StackFrames

```python3–mpdb factorial_recursive.py

```

StackFrames

w(where)/bt

Thew(where)/bt commandwillprintthecurrentStackFrameoftheprogram.

PDBCommandàw(where)/bt

Thew(where)/bt commandwillprintthecurrentStackFrameoftheprogram.

ThisiswhatPythonsPDBmoduleprintsoutwhenweusetheworbt command

(yes,theybothdothesamething)

PDBCommandàw(where)/bt

PythonPDBStackTrace– Factorial(4)

CurrentFrame

TopFrame CurrentLineNumberInFrame

CodeOnLine

LetsseewhattheStackFrameslooklikeforarecursiveFactorialfunctionforn=4

StackFrames

exec()

Factorial(4)

Factorial(1)

Factorial(2)

Factorial(3)

Factorial(0)

exec()

Factorial(4)

Factorial(1)

Factorial(2)

Factorial(3)

Factorial(0)

6

1

2

1

24

exec()returns

WhatifEachSpike RepresentedasaBlockOfMemoryBeingUsed(TheStacks)

0

1

2

Mem

ory

Time

3

Youcanmoveupanddowninastackframe.

Thismeansmovinguptoafunctionthatcalledyou,ormovingintoafunctionyoucalled.

StackFrames

u(up)

Theu(up)commandwillmoveyourprogramupinthestackframe.

PDBCommandàu(up)

Theu(up)commandwillmoveyourprogramupinthestackframe.

u(up) couldalsobeusedasaStepOutOf.

PDBCommandàu(up)

Theu(up)commandwillmoveyourprogramupinthestackframe.

u(up) functionsasaStepOutOfaswell.

u(up)#Moveupthestackframe#frames.

PDBCommandàu(up)

d(down)

Thed(down)commandwillmoveyourprogramdowninthestackframe.

PDBCommandàd(down)

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.

Mostoftheconceptswe’velearneduptillnowcanbeusedwithdebuggersforotherlanguages.

lldb/gdb – C/C++jdb – Java

debugger(browser)– Javascriptpudb – Python

Pudb – AvisualPythonDebugger

DebugginginSpyder – StartingTheDebugger

DebugginginSpyder – StartingOptions

DebugginginSpyder – SampleOutput

DebugginginSpyder – SettingBreakpoints

That’sAllForTonight,Folks

tht_roony

atbe.me

atbe

Questions