Discussion Session 5¶
Debuggin Python Program (pdb)¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | #####################################################################
#
# CAS CS 320, Fall 2014
# machine.py
#
def simulate(s):
instructions = s if type(s) == list else s.split("\n")
instructions = [l.strip().split(" ") for l in instructions]
mem = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: -1, 6: 0}
control = 0
outputs = []
while control < len(instructions):
# Update the memory address for control.
mem[6] = control
# Retrieve the current instruction.
inst = instructions[control]
# Handle the instruction.
if inst[0] == 'label':
pass
if inst[0] == 'goto':
control = instructions.index(['label', inst[1]]) #25
continue
if inst[0] == 'branch' and mem[int(inst[2])]:
control = instructions.index(['label', inst[1]]) #28
continue
if inst[0] == 'jump':
control = mem[int(inst[1])] #31
continue
if inst[0] == 'set':
mem[int(inst[1])] = int(inst[2]) #34
if inst[0] == 'copy':
mem[mem[4]] = mem[mem[3]] #36
if inst[0] == 'add':
mem[0] = mem[1] + mem[2] #38
# Push the output address's content to the output.
if mem[5] > -1:
outputs.append(mem[5]) #42
mem[5] = -1
# Move control to the next instruction.
control = control + 1
print("memory: "+str(mem))
return outputs
# Examples of useful helper functions from lecture.
def copy(frm, to):
return [\
'set 3 ' + str(frm),\
'set 4 ' + str(to),\
'copy'\
]
if __name__ == "__main__":
inss = [\
"set 1 100", \
"set 2 200", \
"add"] + \
copy(0, 5)
ret = simulate(inss)
print("ret is ", ret)
|
Debug Python program from command line.
python3 -m pdb simulate.py
Common commands for using pdb
- n(ext)
- c(ontinue)
- b(reak)
- q(uit)
- cl(ear)
An easy-to-read blog about pdb module in Python: http://pythonconquerstheuniverse.wordpress.com/category/python-debugger/
Generating program of machine language¶
mul(ax, ay, aret)
make_procedure(name, inss, stack)
make_call(name, stack)