tags:

views:

313

answers:

4

Is there a simple way to detect, within Python code, that this code is being executed through the Python debugger?

I have a small Python application that uses Java code (thanks to JPype). When I'm debugging the Python part, I'd like the embedded JVM to be given debug options too.

+2  A: 

From taking a quick look at the pdb docs and source code, it doesn't look like there is a built in way to do this. I suggest that you set an environment variable that indicates debugging is in progress and have your application respond to that.

$ USING_PDB=1 pdb yourprog.py

Then in yourprog.py:

import os
if os.environ.get('USING_PDB'):
    # debugging actions
    pass
dowski
+3  A: 

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.

wilberforce
+1  A: 

You can try to peek into your stacktrace.

http://www.python.org/doc/2.5.2/lib/inspect-stack.html

when you try this in a debugger session:

import inspect inspect.getouterframes(inspect.currentframe() you will get a list of framerecords and can peek for any frames that refer to the pdb file.

do3cc
A: 

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:

Steph