Debugging basic program crashes

In this section, we are going to see the trace module. The trace module helps in tracing the program execution. So, whenever your Python program crashes, we can understand where it crashes. We can use trace module by importing it into your script as well as from the command line.

Now, we will create a script named trace_example.py and write the following content in the script:

class Student:
def __init__(self, std):
self.count = std

def go(self):
for i in range(self.count):
print(i)
return
if __name__ == '__main__':
Student(5).go()

The output will be as follows:

student@ubuntu:~$ python3 -m trace --trace trace_example.py
--- modulename: trace_example, funcname: <module>
trace_example.py(1): class Student:
--- modulename: trace_example, funcname: Student
trace_example.py(1): class Student:
trace_example.py(2): def __init__(self, std):
trace_example.py(5): def go(self):
trace_example.py(10): if __name__ == '__main__':
trace_example.py(11): Student(5).go()
--- modulename: trace_example, funcname: init
trace_example.py(3): self.count = std
--- modulename: trace_example, funcname: go
trace_example.py(6): for i in range(self.count):
trace_example.py(7): print(i)
0
trace_example.py(6): for i in range(self.count):
trace_example.py(7): print(i)
1
trace_example.py(6): for i in range(self.count):
trace_example.py(7): print(i)
2
trace_example.py(6): for i in range(self.count):
trace_example.py(7): print(i)
3
trace_example.py(6): for i in range(self.count):
trace_example.py(7): print(i)
4

So, by using trace --trace at the command line, the developer can trace the program line-by-line. So, whenever the  program crashes, the developer will know the instance where it crashes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset