I use the PyCharm IDE for Python programming.
Is there a possibility to check, whether I'm in debugging mode or not when I run my program?
I use pyplot as plt and want a Figure only to be shown if I debug my program. Yes, I could have a global boolean _debug_
which is set by myself, but I look for a better solution.
According to the documentation, settrace
/ gettrace
functions could be used in order to implement Python debugger:
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.
However, these methods may not be available in all implementations:
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.
You could use the following snippet in order to check if someone is debugging your code:
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)
This one works for 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')
And 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With