我有一个包含许多函数的 .py 文件。现在我在调试代码,发现有时程序会卡在某个地方。
如果我只是把它放在那里等待很长时间,就会出现错误消息:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 9, in generate
File "<stdin>", line 7, in choosePath
MemoryError
我不知道卡在哪里,因为我有几个while 和for 循环。有什么简单的方法可以轻松解决这个问题吗?我真的不愿意逐个调试一个循环。
请您参考如下方法:
点击 CTRL-C 并查看回溯。
例如,下面的代码将进入一个永无止境的循环:
import time
def foo():
while True:
time.sleep(1)
def bar():
for i in range(10):
foo()
bar()
当我打断它时,我看到:
$ 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
回溯结束于第 5 行的 foo。这是我中断程序时 Python 忙的地方。回溯还告诉我,第一个 bar() 被调用,它调用了 foo(),所以我可以看到我们是如何到达那里的。
请注意,如果您有一个裸 except 处理程序,则这不一定有效;使用 try: 捕获所有 异常 except: 也捕获 KeyboardInterrupt。始终使用 except Exception:至少要防止捕获系统异常。
