Using Python in CMake script

CMake FindPython prioritizes location over version number. Prior to CMake 3.15, even specifying Python_ROOT could be overridden if the other Python was a higher version.

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

Example:

find_package(Python COMPONENTS Interpreter REQUIRED)

add_test(NAME Foo COMMAND ${Python_EXECUTABLE} myscript.py -arg1 value)