3

This question is about how to detect the version of the Python interpreter being used to execute an extension module, from within an extension module (i.e. one written in C).

As background, it's straightforward inside a Python extension module to get the version of Python against which the extension was compiled. You can just use one of the macros defined in patchlevel.h that are included when including the standard Python header Python.h (e.g. the macro PY_VERSION).

My question is whether it's possible from within an extension module to get at run-time the version of the interpreter currently being used to run the extension. For example, if Python 2.5 is accidentally being used to run an extension module compiled against Python 2.7, I'd like to be able to detect that at run-time from within the extension module. For concreteness, let's assume the extension module is compiled against Python 2.7.

cjerdonek
  • 5,814
  • 2
  • 32
  • 26
  • Aside from doing the C equivalent of inspecting `sys.version` (or just running Python code that does so)? –  Nov 26 '13 at 17:20
  • Yes, it has to be just from C, though if there's a way to guarantee that certain pure Python code will execute whenever importing the extension, that might also work but is less ideal. – cjerdonek Nov 26 '13 at 17:30
  • I don't see the problem: C code runs when importing the extension, and said C code should be able to use the whole CPython API. But Martijn Pieters gave a more promising answer anyway. –  Nov 26 '13 at 17:32
  • There is no problem. I just wasn't aware of that part of the API. :) – cjerdonek Nov 26 '13 at 17:40

2 Answers2

3

Use the Py_GetVersion() API:

Return the version of this Python interpreter. This is a string that looks something like

"1.5 (#67, Dec 31 1997, 22:34:28) [GCC 2.7.2.2]"

The first word (up to the first space character) is the current Python version; the first three characters are the major and minor version separated by a period. The returned string points into static storage; the caller should not modify its value. The value is available to Python code as sys.version.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

Import sys. Examine hexversion.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358