gpt4 book ai didi

python - 检查程序是否在 Debug 模式下运行

转载 作者:太空狗 更新时间:2023-10-29 18:27:24 24 4
gpt4 key购买 nike

我使用 PyCharm IDE 进行 Python 编程。

是否可以检查我在运行程序时是否处于 Debug模式?

我将 pyplot 用作 plt,并且只希望在调试我的程序时显示一个图形。是的,我可以有一个由我自己设置的全局 bool 值 _debug_,但我正在寻找更好的解决方案。

最佳答案

根据文档,可以使用 settrace/gettrace 函数来实现 Python 调试器:

sys.settrace(tracefunc) 

Set the system’s trace function, which allows you to implement a Python source code debugger in Python. The function is thread-specific; for a debugger to support multiple threads, it must be registered using settrace() for each thread being debugged.

但是,这些方法可能并非在所有实现中都可用:

CPython implementation detail: The settrace() function is intended only for implementing debuggers, profilers, coverage tools and the like. Its behavior is part of the implementation platform, rather than part of the language definition, and thus may not be available in all Python implementations.

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

import sys


gettrace = getattr(sys, 'gettrace', None)

if gettrace is None:
print('No sys.gettrace')
elif gettrace():
print('Hmm, Big Debugger is watching me')
else:
print("Let's do something interesting")
print(1 / 0)

这个适用于 pdb:

$ python -m pdb main.py 
> /home/soon/Src/Python/main/main.py(3)<module>()
-> import sys
(Pdb) step
> /home/soon/Src/Python/main/main.py(6)<module>()
-> gettrace = getattr(sys, 'gettrace', None)
(Pdb) step
> /home/soon/Src/Python/main/main.py(8)<module>()
-> if gettrace is None:
(Pdb) step
> /home/soon/Src/Python/main/main.py(10)<module>()
-> elif gettrace():
(Pdb) step
> /home/soon/Src/Python/main/main.py(11)<module>()
-> print('Hmm, Big Debugger is watching me')
(Pdb) step
Hmm, Big Debugger is watching me
--Return--
> /home/soon/Src/Python/main/main.py(11)<module>()->None
-> print('Hmm, Big Debugger is watching me')

和 PyCharm:

/usr/bin/python3 /opt/pycharm-professional/helpers/pydev/pydevd.py --multiproc --qt-support --client 127.0.0.1 --port 34192 --file /home/soon/Src/Python/main/main.py
pydev debugger: process 17250 is connecting

Connected to pydev debugger (build 143.1559)
Hmm, Big Debugger is watching me

Process finished with exit code 0

关于python - 检查程序是否在 Debug 模式下运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38634988/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com