J. Hesters
J. Hesters

Reputation: 14748

How to activate a virtualenv using a makefile?

At the top of my makefile I have this line:

SHELL := /bin/sh

which is needed for most of the commands. However, I would like to also have a make command to activate my virtual env, which is on a different path.

Here is the code that I wrote for it:

activate:
    source ~/.envs/$(APP)/bin/activate; \

The problem with this is, that this just prints out what is written here, and it doesn't get executed. I read that it might have something todo with only bash knowing about source, but I can't figure out how to temporarily switch modes within the activate command.

How would I have to write this method, so that it activates my virtualenv?

Upvotes: 5

Views: 6008

Answers (3)

Cherlepops
Cherlepops

Reputation: 137

You can do it by using set, which allows you to set or unset values of shell options and positional parameters:

set -a && . venv/bin/activate && set +a

Upvotes: 0

Phil Lord
Phil Lord

Reputation: 3057

Create a file called "make-venv" like this:

#!/bin/bash
source ./.venv/bin/activate
$2

Then add this to the first line of your Makefile

SHELL=./make-venv

Now, make-venv activates virtualenv before every command runs. Probably inefficient, but functional.

Upvotes: 6

MadScientist
MadScientist

Reputation: 100781

It does get executed.

Virtualenv works by modifying your current process's environment (that's why you have to "source" it). However, one process cannot modify the environment of the other process. So, to run your recipe make invokes a shell and passes it your virtualenv command, it works, then the shell exits, and your virtualenv is gone.

In short, there's no easy way to do this in a makefile. The simplest thing to do is create a script that first sources the virtualenv then runs make, and run that instead of running make.

Upvotes: 10

Related Questions