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 overriden if the other Python was a higher vrsion.

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.

Example

find_package(Python3 COMPONENTS Interpreter)

add_test(NAME Foo COMMAND ${PYTHON3_EXECUTABLE} myscript.py -arg1 bar)