检查程序是否在 PyCharm 2023 中以调试模式运行

问题描述 投票:0回答:1

我使用 PyCharm IDE 进行 Python 编程。我之前使用检查程序是否在调试模式下运行中描述的方法来检查运行程序时是否处于调试模式。

但是,在 PyCharm 2023.3 更新后,这些方法停止工作。例如,

sys.gettrace() is None
无论是否处于调试模式,

都会评估为

True

python debugging pycharm
1个回答
0
投票

我想我已经找到了一个新的解决方案,它建立在 awesoon 的这个答案的基础上。

根据文档,可以使用

settrace
/
gettrace
函数
breakpointhook
function 来实现 Python 调试器:

sys.settrace(tracefunc)

设置系统的trace功能,可以让你在Python中实现Python源代码调试器。函数是 线程特定的;对于支持多线程的调试器,它必须 使用 settrace() 为每个正在调试的线程进行注册。

sys.breakpointhook()

该钩子函数由内置的breakpoint()调用。默认情况下,它 将您带入 pdb 调试器,但它可以设置为任何其他 函数,以便您可以选择使用哪个调试器。

您可以使用以下代码片段来检查是否有人正在调试您的代码:

import sys
has_trace = hasattr(sys, 'gettrace') and sys.gettrace() is not None
has_breakpoint = sys.breakpointhook.__module__ != "sys"
is_debug = has_trace or has_breakpoint
print(f"{has_trace=} {has_breakpoint=} {is_debug=}")

这个适用于 pdb:

PS C:\Users\pvillano> python -m pdb main.py
> c:\users\pvillano\main.py(1)<module>()
-> import sys
(Pdb) step
> c:\users\pvillano\main.py(2)<module>()
-> has_trace = hasattr(sys, 'gettrace') and sys.gettrace() is not None
(Pdb) step
> c:\users\pvillano\main.py(3)<module>()
-> has_breakpoint = sys.breakpointhook.__module__ != "sys"
(Pdb) step
> c:\users\pvillano\main.py(4)<module>()
-> is_debug = has_trace or has_breakpoint
(Pdb) step
> c:\users\pvillano\main.py(5)<module>()
-> print(f"{has_trace=} {has_breakpoint=} {is_debug=}")
(Pdb) step
has_trace=True has_breakpoint=False is_debug=True
--Return--
> c:\users\pvillano\main.py(5)<module>()->None
-> print(f"{has_trace=} {has_breakpoint=} {is_debug=}")

现在它适用于 PyCharm:

C:\Users\pvillano\AppData\Local\pypoetry\Cache\virtualenvs\...\Scripts\python.exe -X pycache_prefix=C:\Users\pvillano\AppData\Local\JetBrains\PyCharm2023.3\cpython-cache "C:/Users/python/AppData/Local/Programs/PyCharm Professional/plugins/python/helpers/pydev/pydevd.py" --multiprocess --qt-support=auto --client 127.0.0.1 --port 50772 --file C:\Users\pvillano\main.py 
Connected to pydev debugger (build 233.11799.259)
has_trace=False has_breakpoint=True is_debug=True

Process finished with exit code 0

它也适用于 Visual Studio Code

PS C:\Users\pvillano>  c:; cd 'c:\Users\pvillano'; & 'C:\Program Files\Python312\python.exe' 'c:\Users\pvillano\.vscode-oss\extensions\ms-python.python-2023.20.0-universal\pythonFiles\lib\python\debugpy\adapter/../..\debugpy\launcher' '51165' '--' 'C:\Users\pvillano\main.py'
has_trace=True has_breakpoint=True is_debug=True
© www.soinside.com 2019 - 2024. All rights reserved.