Create and activate Python conda environment with CMake

I have the following in a CMakeLists.txt file. The goal is to use cmake to check if a Python conda environment named myenv is already installed and activate that environment. If the environment does not exist, then create the environment and activate it. This assumes that conda is already installed via Anaconda (or Miniconda).

# Create and activate a Python environment.

cmake_minimum_required(VERSION 3.18)

# Define the project

# Specify the C++ standard

# Make sure Python is installed
find_package(Python REQUIRED)

# Activate conda environment, assume Anaconda or Miniconda is already installed
if(EXISTS /opt/miniconda3/envs/myenv)
    execute_process(COMMAND conda activate myenv)
    execute_process(COMMAND conda create --yes --quiet --name myenv python)
    execute_process(COMMAND conda activate myenv)

When I run the above cmake file, I get the error:

CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'.

However, conda is installed on my system and I can activate the environment manually in the terminal. Why does the environment not get activated via cmake?

conda activate won’t work in CMake because it modifies the caller’s environment through either being sourced (if conda is a shell function) or by launching a new command (which also can’t affect CMake).

Environments like that need to be set up outside of CMake whether it be HomeBrew, Nix, vcpkg, spack, or conda.

So for a project with C++ and Python code, does the following sound reasonable.

Step 1. Create the Python environment by running the following in the terminal

$ conda env create -f environment.yml
$ conda activate myenv

Step 2. Build and install the C++ environment using CMakeLists.

Or is there another approach that could accomplish this in one step?

Not really, no. You could write a shell script or Makefile-like thing to do it for you, but unless conda is actually the only way to build the software, I would just document the recommended way of building it using conda (e.g., someone using vcpkg probably isn’t going to care about conda). Compilers and the build environment are the choice of the builder. The project can sanity check it, but making things too strict is closer to premature optimization IMO.

Ok, thank you @ben.boeckel for the comments.