How can one get the version of the currently-running Python interpreter from within a Python extension module?

StackOverflow https://stackoverflow.com/questions/20223704

Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top