I have 2 versions of python installed, but cmake is using older version. How do I force cmake to use the newer version?

You may try either of these depending on what you need:

For CMake >= 3.12

According to the changelog:

New "FindPython3" and "FindPython2" modules, as well as a new
"FindPython" module, have been added to provide a new way to locate
python environments.

find_package(Python COMPONENTS Interpreter Development)

Docs:

This module looks preferably for version 3 of Python. If not found, version 2 is searched. To manage concurrent versions 3 and 2 of Python, use FindPython3 and FindPython2 modules rather than this one.

For CMake < 3.12

Docs:

find_package(PythonInterp 2.7 REQUIRED)
find_package(PythonLibs 2.7 REQUIRED)

Try to add -DPYTHON_EXECUTABLE:FILEPATH=/path/to/python2.7 It might be a path problem?

Also could specify the path to your python library,use your version that you want:

 cmake -DPYTHON_LIBRARIES=/Library/Frameworks/Python.framework/Versions/2.7/lib/libpython2.7.dylib .

I had a similar problem, and resolved it using Paul's answer as a hint. I needed to use python2.7 to compile an older library, but cmake keeps picking up my python3.2 libraries (and executable).

First, I ran cmake with default options, then edited the CMakeCache.txt file which it generated. I did it this way primarily because I didn't know the proper -D... incantations to cause cmake to get the python library and include paths, etc right in the first place.

In my CmakeCache.txt, I found lines like this

  • Path to a program

    PYTHON_EXECUTABLE:FILEPATH=/usr/bin/python
    
  • Path to a directory

    PYTHON_INCLUDE_DIR:PATH=/usr/include/python3.2
    
  • Path to a library

    PYTHON_LIBRARY:FILEPATH=/usr/lib/libpython3.2.so
    

And replaced every occurrence of python3.2 with python2.7. I also had to rename the PYTHON_EXECUTABLE to use python2.7, since python is a symlink to python3.2 on my system.

Then I reran cmake. Because it prefers its cached values to actually looking for the libraries, this should work in all cases. At least, it did in mine.