Question

We need to find out if our code is running under a CPython executable built with debugging enabled, programmatically. sys module did not seem to have any information, at least on python3.4-dbg of Ubuntu 14.04. sys.flags.debug is set to 0. The reason for this is that our code unmodified actually crashes the debug versions of python. Update: specifically the code crashes with an assertion error on the C side.

Surely there must be better than see if 'd' in sys.executable.

Was it helpful?

Solution

The following code might be what you're after

Using python3.4:

>>> import sysconfig
>>> sysconfig.get_config_var('Py_DEBUG')
0

On the other hand using python3.4-dbg:

>>> import sysconfig
>>> sysconfig.get_config_var('Py_DEBUG')
1

However, there are also compile time options controlling "debug" behaviour, such as NDEBUG mentioned here: http://bugs.python.org/issue17411 .

In other words: though Py_DEBUG may be unset (0), the C-code asserts controlled by NDEBUG may still alter the behaviour of python. Setting Py_DEBUG always unsets NDEBUG resulting in asserts being applied. The lack of Py_DEBUG has no effect on NDEBUG - it may or may not be defined. If NDEBUG is defined, asserts will be defined as a void macro.

From http://en.wikipedia.org/wiki/Assert.h :

Programmers can eliminate the assertions just by recompiling the program, without changing the source code: if the macro NDEBUG is defined before the inclusion of , the assert() macro is defined simply as:

#define assert(ignore)((void) 0)

A possible, but unportable, solution would be to check compiler command line OPT for this:

>>> '-DNDEBUG' not in (sysconfig.get_config_var('OPT') or '')

where OPT could be for example

>>> sysconfig.get_config_var('OPT')
'-DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top