Using Python in CMake script

Finding Python is made more robust in CMake >= 3.15, which prioritizes location over version number. Prior to CMake 3.15, even specifying Python3_ROOT could be overridden if the other Python was a higher version.

Using the Python interpreter in CMake should generally be via ${PYTHON3_EXECUTABLE} and not Python3::Interpreter. CMake provides the imported target Python3::Interpreter only when the CMAKE_ROLE is PROJECT. This means that Python3::Interpreter is not available when using CTest, which is often when using the Python3 interpreter is desired. Normally, to use Python interpreter from a CMake script, including in execute_process or add_test, use PYTHON3_EXECUTABLE.

If the project must support CMake older than 3.15, you can still get the benefits of better Python3_ROOT behavior by using CMake maximum version policy like:

cmake_minimum_required(VERSION 3.13...3.15)

The “3.15” can be set to even newer versions of CMake as well. As long as the user is using CMake ≥ 3.15, you’ll get the modern FindPython3 behavior. The “3.13” is arbitrary, it’s whatever old CMake version your project must support.

then do like:

find_package(Python3 COMPONENTS Interpreter REQUIRED)

add_test(NAME Foo COMMAND ${PYTHON3_EXECUTABLE} -arg1 value)