Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if the CPython executable is the debug version, in python?

Tags:

python

cpython

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.

like image 919

1 Answers

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'
like image 197
Ilja Everilä Avatar answered Nov 02 '22 06:11

Ilja Everilä