Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CMake: Check Python3 and Python packages presence

Tags:

python

pip

cmake

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.

like image 904
jbaptperez Avatar asked Aug 15 '26 06:08

jbaptperez


1 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.

like image 196
zaufi Avatar answered Aug 16 '26 19:08

zaufi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!