Dror
Dror

Reputation: 13051

Check if virtual environment is activated and act accordingly in a Makefile

I am using Python together with Anaconda and I want to have a rule test in my Makefile. However, I want to assert that when running make test, the right environment will be activated. When a conda environment is activated it defines the environment variable $(CONDA_DEFAULT_ENV).

First I did:

REPO_NAME = my_repo

define execute_in_env
  source activate $(REPO_NAME); \
  $1
endef

test:
    $(call execute_in_env, pytest -v --ignore=src/foo)

This way, when I executed make test it activated the virtual environment and ran the test inside. Problem is that it is length. I want to check if make is executed from an activated virtual environment. To that end, I modified the code:

.PHONY: test
REPO_NAME = my_repo
define execute_in_env =
    $@echo "Checking if in environment"
    ifeq ($(CONDA_DEFAULT_ENV),$(REPO_NAME))
        $1
    else
        source activate $(REPO_NAME); \
        $1
    endif
endef
test:
    $(call execute_in_env, pytest -v --ignore=src/rebuydsutils)

With this implementation, the testing doesn't happen. I get a

make: Nothing to be done for `test'.

Upvotes: 1

Views: 1269

Answers (2)

Dror
Dror

Reputation: 13051

Based on @John's answer, I wrote the following:

ifeq ($(CONDA_DEFAULT_ENV),$(REPO_NAME))
    ACTIVATE_ENV := true
else
    ACTIVATE_ENV := source activate $(REPO_NAME)
endif

# Execute python related functionalities from within the project's environment
define execute_in_env
    $(ACTIVATE_ENV) && $1
endef

Then, inside a rule I can have something like:

test:
    $(call execute_in_env, pytest -v --ignore=src/somepackage)

Upvotes: 0

blackghost
blackghost

Reputation: 1825

The root problem is with the = in define execute_in_env =. (you're also using an ifeq inside of a define, which is a bit of a sharp stick, but I don't think it will hurt you in this particular case). Note that you're using functions where you don't need to -- functions are not very readable, and make the makefiles harder to maintain. A simpler and cleaner way of doing the same thing would be:

ifeq ($(CONDA_DEFAULT_ENV),$(REPO_NAME))
    ACTIVATE_ENV := source activate $(REPO_NAME);
else
    ACTIVATE_ENV := true
endif

test: 
    $(ACTIVATE_ENV) && pytest -v --ignore=src/rebuydsutils;

Upvotes: 2

Related Questions