12

How can I detect in my python script if its being run by the debug interpreter (ie python_d.exe rather than python.exe)? I need to change the paths to some dlls that I pass to an extension.

eg Id like to do something like this at the start of my python script:

#get paths to graphics dlls
if debug_build:
    d3d9Path   = "bin\\debug\\direct3d9.dll"
    d3d10Path  = "bin\\debug\\direct3d10.dll"
    openGLPath = "bin\\debug\\openGL2.dll"
else:
    d3d9Path   = "bin\\direct3d9.dll"
    d3d10Path  = "bin\\direct3d10.dll"
    openGLPath = "bin\\openGL2.dll"

I thought about adding an "IsDebug()" method to the extension which would return true if it is the debug build (ie was built with "#define DEBUG") and false otherwise. But this seems a bit of a hack for somthing Im sure I can get python to tell me...

1
  • 1
    Have you considered using raw strings to avoid excess escaping? r'bin\debug\direct3d9.dll' Commented Mar 15, 2009 at 12:46

3 Answers 3

16

Distutils use sys.gettotalrefcount to detect a debug python build:

# ...
if hasattr(sys, 'gettotalrefcount'):
   plat_specifier += '-pydebug'
  • this method doesn't rely on an executable name '*_d.exe'. It works for any name.
  • this method is cross-platform. It doesn't depend on '_d.pyd' suffix.

See Debugging Builds and Misc/SpecialBuilds.txt

Sign up to request clarification or add additional context in comments.

3 Comments

This is an old answer, but I'm a person from the future here to confirm that this still works fine on Python 3.7.1.
Here is an example one-liner: python -c "import sys; sys.exit(int(hasattr(sys, 'gettotalrefcount')))" # returns 0 if is a non-debug build, 1 if is a debug build Here is a bash test: if [[ python -c "import sys; sys.exit(int(hasattr(sys, 'gettotalrefcount')))" ]]; then PYTHON_DEBUG= ; else: PYTHON_DEBUG="y" fi
sorry remove the square brackets in the bash example to have it working
3

Better, because it also works when you are running an embedded Python interpreter is to check the return value of

imp.get_suffixes()

For a debug build it contains a tuple starting with '_d.pyd':

# debug build:
[('_d.pyd', 'rb', 3), ('.py', 'U', 1), ('.pyw', 'U', 1), ('.pyc', 'rb', 2)]

# release build:
[('.pyd', 'rb', 3), ('.py', 'U', 1), ('.pyw', 'U', 1), ('.pyc', 'rb', 2)]

Comments

2

An easy way, if you don't mind relying on the file name:

if sys.executable.endswith("_d.exe"):
  print "running on debug interpreter"

You can read more about the sys module and its various facilities here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.