How to attach debugger to a python subproccess?

前端 未结 8 2288
旧巷少年郎
旧巷少年郎 2020-12-22 23:49

I need to debug a child process spawned by multiprocessing.Process(). The pdb degugger seems to be unaware of forking and unable to attach to alrea

8条回答
  •  情深已故
    2020-12-23 00:27

    This is an elaboration of Romuald's answer which restores the original stdin using its file descriptor. This keeps readline working inside the debugger. Besides, pdb special management of KeyboardInterrupt is disabled, in order it not to interfere with multiprocessing sigint handler.

    class ForkablePdb(pdb.Pdb):
    
        _original_stdin_fd = sys.stdin.fileno()
        _original_stdin = None
    
        def __init__(self):
            pdb.Pdb.__init__(self, nosigint=True)
    
        def _cmdloop(self):
            current_stdin = sys.stdin
            try:
                if not self._original_stdin:
                    self._original_stdin = os.fdopen(self._original_stdin_fd)
                sys.stdin = self._original_stdin
                self.cmdloop()
            finally:
                sys.stdin = current_stdin
    

提交回复
热议问题