We have already shown the use of execute_process when trying to find the NumPy Python module in Chapter 3, Detecting External Libraries and Programs, Recipe 3, Detecting Python modules and packages. In this example, we will use the execute_process command to find out whether a particular Python module (in this case, Python CFFI) is present, and if it is, we will discover its version:
- For this simple example, we will not require any language support:
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)
project(recipe-02 LANGUAGES NONE)
- We will require the Python interpreter to execute a short Python snippet, and for this we discover the interpreter using find_package:
find_package(PythonInterp REQUIRED)
- We then invoke execute_process to run a short Python snippet; we will discuss this command in more detail in the next section:
# this is set as variable to prepare
# for abstraction using loops or functions
set(_module_name "cffi")
execute_process(
COMMAND
${PYTHON_EXECUTABLE} "-c" "import ${_module_name}; print(${_module_name}.__version__)"
OUTPUT_VARIABLE _stdout
ERROR_VARIABLE _stderr
OUTPUT_STRIP_TRAILING_WHITESPACE
ERROR_STRIP_TRAILING_WHITESPACE
)
- Then, we print the result:
if(_stderr MATCHES "ModuleNotFoundError")
message(STATUS "Module ${_module_name} not found")
else()
message(STATUS "Found module ${_module_name} v${_stdout}")
endif()
- An example configuration yields the following (assuming the Python CFFI package is installed in the corresponding Python environment):
$ mkdir -p build
$ cd build
$ cmake ..
-- Found PythonInterp: /home/user/cmake-cookbook/chapter-05/recipe-02/example/venv/bin/python (found version "3.6.5")
-- Found module cffi v1.11.5