Sibbs Gambling
Sibbs Gambling

Reputation: 20355

How to find out inside which loop Python is stuck?

I have a .py file that has a number of functions. Now I am debugging the codes and find that sometimes the program is stuck somewhere.

If I just leave it there and wait for a super long time, error message shows up:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 9, in generate
  File "<stdin>", line 7, in choosePath
MemoryError

I have no idea where it is stuck, as I have several while and for loops. Is there any easy way to figure out that easily? I feel really reluctant to debug one loop by another.

Upvotes: 1

Views: 877

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121524

Hit CTRL-C and look at the traceback.

For example, the following code will hit a never-ending loop:

import time

def foo():
    while True:
        time.sleep(1)

def bar():
    for i in range(10):
        foo()

bar() 

and when I interrupt it I see:

$ bin/python endless_demo.py 
^CTraceback (most recent call last):
  File "test.py", line 11, in <module>
    bar() 
  File "test.py", line 9, in bar
    foo()
  File "test.py", line 5, in foo
    time.sleep(1)
KeyboardInterrupt

The traceback ends in foo, on line 5. This is where Python was busy when I interrupted the program. The traceback also tells me that first bar() was called, which called foo(), so I can see how we got there.

Note that if you have a bare except handler this won't necessarily work; catching all exceptions with try: except: catches KeyboardInterrupt too. Always use except Exception: at a minimum to prevent catching system exceptions.

Upvotes: 10

Related Questions