您可以使用 winpdb 到 attach to your running program 并允许您在不同的时间点中断、检查和恢复它。
或者,您可以定义一个信号处理程序,尽管这可能不是一个完全可靠的解决方案,尤其是在您使用线程时:
import signal
import traceback
def sigint_handler(signal, frame):
# ctrl-c generates SIGINT
traceback.print_stack()
print('-'*80)
def foo():
total = 0
for i in range(10**8):
total += i
return total
if __name__=='__main__':
signal.signal(signal.SIGINT, sigint_handler)
print(foo())
运行test.py,并在不同的时刻按下C-c会产生:
C-c C-c File "/home/unutbu/pybin/test.py", line 20, in <module>
print(foo())
File "/home/unutbu/pybin/test.py", line 14, in foo
for i in range(10**8):
File "/home/unutbu/pybin/test.py", line 9, in sigint_handler
traceback.print_stack()
--------------------------------------------------------------------------------
C-c C-c File "/home/unutbu/pybin/test.py", line 20, in <module>
print(foo())
File "/home/unutbu/pybin/test.py", line 15, in foo
total += i
File "/home/unutbu/pybin/test.py", line 9, in sigint_handler
traceback.print_stack()
--------------------------------------------------------------------------------
4999999950000000
参考资料:
-
The signal module(请务必阅读注意事项)
- The traceback module
- Doug Hellman's Python Module of the Week tutorial on using
signal