How to detect that Python code is being executed through the debugger?

Python debuggers (as well as profilers and coverage tools) use the sys.settrace function (in the sys module) to register a callback that gets called when interesting events happen.

If you're using Python 2.6, you can call sys.gettrace() to get the current trace callback function. If it's not None then you can assume you should be passing debug parameters to the JVM.

It's not clear how you could do this pre 2.6.


A solution working with Python 2.4 (it should work with any version superior to 2.1) and Pydev:

import inspect

def isdebugging():
  for frame in inspect.stack():
    if frame[1].endswith("pydevd.py"):
      return True
  return False

The same should work with pdb by simply replacing pydevd.py with pdb.py. As do3cc suggested, it tries to find the debugger within the stack of the caller.

Useful links:

  • The Python Debugger
  • The interpreter stack

Other alternative if you're using Pydev that also works in a multithreading is:

try:
    import pydevd
    DEBUGGING = True
except ImportError:
    DEBUGGING = False