Reputation: 11367
I am creating a conda environment inside a Makefile. However, if this environment was created already, I'd like to skip that step. How can I check the following:
CONDA_ENV_NAME := myname
ifeq (,$(shell which conda))
HAS_CONDA=False
else
HAS_CONDA=True
CONDA_ACTIVATE=source $$(conda info --base)/etc/profile.d/conda.sh ; conda activate ; conda activate
endif
environment:
ifeq (True,$(HAS_CONDA))
@echo ">>> Detected conda, creating conda environment."
## Here I'd like to check if this environment already exists
conda env create -f environment.yml -n $(CONDA_ENV_NAME)
## ... and if the env should be activated (optional)
$(CONDA_ACTIVATE) $(CONDA_ENV_NAME)
else
@echo ">>> Install conda first."
endif
Upvotes: 4
Views: 4631
Reputation: 680
You can use this script activate.sh
(run it as source ./activate.sh
or . ./activate.sh
)
#! /usr/bin/env bash
ENV_NAME="<your env name>"
RED='\033[1;31m'
GREEN='\033[1;32m'
CYAN='\033[1;36m'
NC='\033[0m' # No Color
if ! (return 0 2>/dev/null) ; then
# If return is used in the top-level scope of a non-sourced script,
# an error message is emitted, and the exit code is set to 1
echo
echo -e $RED"This script should be sourced like"$NC
echo " . ./activate.sh"
echo
exit 1 # we detected we are NOT source'd so we can use exit
fi
if type conda 2>/dev/null; then
if conda info --envs | grep ${ENV_NAME}; then
echo -e $CYAN"activating environment ${ENV_NAME}"$NC
else
echo
echo -e $RED"(!) Please install the conda environment ${ENV_NAME}"$NC
echo
return 1 # we are source'd so we cannot use exit
fi
else
echo
echo -e $RED"(!) Please install anaconda"$NC
echo
return 1 # we are source'd so we cannot use exit
fi
conda activate ${ENV_NAME}
Upvotes: 1
Reputation: 11367
I solved the problem with the following:
ifeq (,$(shell which conda))
HAS_CONDA=False
else
HAS_CONDA=True
ENV_DIR=$(shell conda info --base)
MY_ENV_DIR=$(ENV_DIR)/envs/$(CONDA_ENV_NAME)
CONDA_ACTIVATE=source $$(conda info --base)/etc/profile.d/conda.sh ; conda activate ; conda activate
endif
environment:
ifeq (True,$(HAS_CONDA))
ifneq ("$(wildcard $(MY_ENV_DIR))","") # check if the directory is there
@echo ">>> Found $(CONDA_ENV_NAME) environment in $(MY_ENV_DIR). Skipping installation..."
else
@echo ">>> Detected conda, but $(CONDA_ENV_NAME) is missing in $(ENV_DIR). Installing ..."
conda env create -f environment.yml -n $(CONDA_ENV_NAME)
endif
else
@echo ">>> Install conda first."
exit
endif
Upvotes: 10