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
.
Example
Either specify minimum CMake version 3.15:
cmake_minimum_required(VERSION 3.15)
OR where older CMake versions must be accommodated:
if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.15)
cmake_policy(SET CMP0094 NEW)
endif()
then do like:
find_package(Python3 COMPONENTS Interpreter REQUIRED)
add_test(NAME Foo COMMAND ${PYTHON3_EXECUTABLE} myscript.py -arg1 value)