gpt4 book ai didi

python - 如何在不退出程序的情况下在linux上打印最近的最后一次调用

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:36:54 26 4
gpt4 key购买 nike

当我在 linux 上执行 python 脚本并中断进程时,它给了我“最后一次调用”:

Traceback (most recent call last):
File "clustermptest.py", line 38, in <module>
if sequences[i][x:x+3]==CAI[cailength][1]:
KeyboardInterrupt

有没有办法在脚本仍在运行/不停止脚本的情况下查看最近调用的最后一个是什么,即当前正在处理的行?

最佳答案

你可以使用 winpdbattach 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

引用资料:

  1. The signal module (一定要阅读注意事项)
  2. The traceback module
  3. Doug Hellman's Python Module of the Week tutorial on usingsignal

关于python - 如何在不退出程序的情况下在linux上打印最近的最后一次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16309476/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com