[英]How can I tell a Python script to halt for debugger attach to process?
不同的 IDE 可以使用不同的方法附加到進程,但是 PyCharm、Eclipse、Visual Studio 和 VS Code 都使用pydevd (VS/VSC,通過它們的 Python 插件通過ptvsd )來提供它們的進程內調試器實現。 因此,我們可以用一段代碼來定位那些。
這個想法是等到pydevd被導入,然后在斷點處停止。
import sys
import threading
from importlib.abc import MetaPathFinder
class NotificationFinder(MetaPathFinder):
def find_spec(self, fullname, _path, _target=None):
if 'pydevd' in fullname:
with t:
t.notify()
t = threading.Condition()
sys.meta_path.insert(0, NotificationFinder())
with t:
t.wait()
breakpoint()
由於 pydevd 創建__builtins__.breakpoint
,無論 Python 版本如何,這都應該有效。 我在 PyCharm(社區版 2019.1.3)中進行了測試。 我啟動了腳本,在我的 IDE 中附加了“附加到進程”選項,並且能夠成功附加。 然后腳本按預期在breakpoint()
處停止。
安裝ipython 和 ipdb 。 之后你就可以使用
import ipdb
ipdb.set_trace()
並直接從控制台調試。 您還可以使用開箱即用的 pdb :
import pdb
pdb.set_trace()
這是您可以等待pydevd
另一種方法:
while not (pydevd.connected and get_global_debugger().ready_to_run):
sleep(0.3)
breakpoint()
在我的設置中, MetaPathFinder
僅在我第一次與pydevd
連接時pydevd
。 使用 while 循環,您應該能夠重新連接,因為您不依賴於pydevd
import 副作用。
改進 Timofey Solonin 的回答https://stackoverflow.com/a/66841531/324204 。
# ...
import pydevd
import time
while pydevd.get_global_debugger() is None or not pydevd.get_global_debugger().ready_to_run:
time.sleep(0.3)
breakpoint() # breaks here
# ...
改進是不使用pydevd.connected
。 它沒有在 pydevd 2.8 版中定義。
請注意,在 Linux 上,您可能會遇到無權附加到進程的問題。 嘗試將 GDB 附加到進程時如何解決“不允許 ptrace 操作”?
您可以使用我的工具madbg來做到這一點。 把它放在你的程序中:
madbg.set_trace()
此行將阻塞,直到調試器使用以下方式連接:
madbg connect
madbg
可以從同一台機器或通過.network 連接。 它還可以搶先停止您的進程並附加到它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.