【问题标题】:How to print the most recent last call on linux without exiting the program如何在不退出程序的情况下在 linux 上打印最近的最后一次调用
【发布时间】:2013-04-30 21:43:31
【问题描述】:

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

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

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

【问题讨论】:

    标签: python linux call


    【解决方案1】:

    您可以使用 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 using signal

    【讨论】:

      猜你喜欢
      • 2016-04-06
      • 2022-11-29
      • 2011-03-19
      • 2021-11-18
      • 1970-01-01
      • 2021-07-03
      • 2021-05-02
      • 2021-02-08
      • 1970-01-01
      相关资源
      最近更新 更多