我想将Python调试器附加到正在运行的进程。在this comment之后,我尝试了pdb-clone
,但感到困惑。这是我要附加的脚本:
import os
import time
from pdb_clone import pdbhandler
pdbhandler.register()
def loop(my_pid):
print("Entering loop")
while True:
x = 'frog'
time.sleep(0.5)
print("Out of Loop")
if __name__ == '__main__':
my_pid = os.getpid()
print("pid = ", my_pid)
loop(my_pid)
如果我在一个终端中运行python3 target_code_1.py
并看到PID = 95439
,则在另一个终端中尝试
sudo pdb-attach --kill --pid 95439
我收到一条错误消息(包括在下面)。
但是,假设我在第三个终端中同时运行python3 target_code_1.py
。现在,我可以正确运行sudo pdb-attach --kill --pid 95439
了,但是当我打印my_pid
时,该值为95440。另一方面,如果我运行sudo pdb-attach --kill --pid 95440
并打印my_pid
,则该值是95439。(换句话说,pdb-attach
似乎已经交换了它要连接到的线程。)此行为似乎是可重复的。发生了什么事?
为进行记录,初始错误消息如下:
sudo pdb-attach --kill --pid 95440
Traceback (most recent call last):
File "/usr/local/bin/pdb-attach", line 4, in <module>
attach.main()
File "/usr/local/lib/python3.7/site-packages/pdb_clone/attach.py", line 646, in main
attach(address)
File "/usr/local/lib/python3.7/site-packages/pdb_clone/attach.py", line 596, in attach
for count in asock.connect_retry(address, verbose):
File "/usr/local/lib/python3.7/site-packages/pdb_clone/attach.py", line 115, in connect_retry
self.connect(address)
File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncore.py", line 342, in connect
raise OSError(err, errorcode[err])
OSError: [Errno 22] EINVAL
FWIW,我正在macOS Mojave 10.14.2,Python 3.7.0,Clang 9.1.0上运行。
(如果我以错误的方式解决了这个问题,例如,如果有一个更好的Python模块可以附加到实时进程中,我很乐意使用它。)