CMake: Check Python3 and Python packages presence

Viewed 1262

I'm currently creating a CMake project in which a couple of Python scripts are called as commands/targets whenever some classic targets are properly executed (classic compilation).

I want CMake to Check the presence of 2 kind of elements (error if not found):

  1. Presence of Python interpreter (let's say Python 3 but both Python 2.7 and 3 are compatible),
  2. Presence of Python packages installed by pip(3).

For the first part, I use that code snippet which seems to work well:

find_package(
        Python3
        REQUIRED
        COMPONENTS Interpreter
)

But how to specify that I want some pip packages (like pycryptodome) to be installed?

Note: The Python scripts I use are third-party scripts which are only run as post-compilation tools: They are not required as development dependency for any target.

2 Answers

The other approach, which doesn't require pip (which also need to be found first before use %) is to execute Python:

execute_process(
    COMMAND Python3::Interpreter -c "import your_python_package"
    RESULT_VARIABLE EXIT_CODE
    OUTPUT_QUIET
)

Note, modern CMake (and FindPython module) allows you to use imported targets.

If you need some details you can print __file__, __path__, or even try importlib.metadata to get required details about the package.

Thanks to KamilCuk, I could succeed in what I wanted using the following commands:

find_package(
        Python3
        REQUIRED
        COMPONENTS Interpreter
)

execute_process(
        COMMAND pip show pycryptodome
        RESULT_VARIABLE EXIT_CODE
        OUTPUT_QUIET
)

if (NOT ${EXIT_CODE} EQUAL 0)
    message(
            FATAL_ERROR
            "The \"pycryptodome\" Python3 package is not installed. Please install it using the following command: \"pip3 install pycryptodome\"."
    )
endif()
Related