How to activate a virtualenv using a makefile?

2020-04-11 01:32发布

问题:

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?

回答1:

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.



回答2:

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.



回答3:

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