Is there a way to attach a debugger to a multi-threaded Python process?

前端 未结 9 2175
日久生厌
日久生厌 2020-12-13 18:49

I\'m trying to debug a deadlock in a multi-threaded Python application after it has locked up. Is there a way to attach a debugger to inspect the state of the process?

相关标签:
9条回答
  • 2020-12-13 19:21

    pdbinject allows you to inject pdb into an already running python process.

    The pdbinject executable only works under python2, but can inject into python3 just fine too.

    0 讨论(0)
  • 2020-12-13 19:26

    This can be used as a dead simple "remote" debugger:

    import sys
    import socket
    import pdb
    
    def remote_trace():
        server = socket.socket()
        server.bind(('0.0.0.0', 12345))
        server.listen()
        client, _= server.accept()
        stream = client.makefile('rw')
        sys.stdin = sys.stdout = sys.stderr = stream
        pdb.set_trace()
    
    remote_trace()
    
    # Execute in the shell: `telnet 127.0.0.1 12345`
    

    On Windows it's easier to use Netcat instead of Telnet (which will also work on linux).

    0 讨论(0)
  • 2020-12-13 19:27

    Yeah, gdb is good for lower level debugging.

    You can change threads with the thread command.

    e.g

    (gdb) thr 2
    [Switching to thread 2 (process 6159 thread 0x3f1b)]
    (gdb) backtrace
    ....
    

    You could also check out Python specific debuggers like Winpdb, or pydb. Both platform independent.

    0 讨论(0)
提交回复
热议问题