How to activate a virtualenv using a makefile?

2020-04-11 01:15发布

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?

3条回答
The star\"
2楼-- · 2020-04-11 01:31

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

查看更多
Root(大扎)
3楼-- · 2020-04-11 01:51

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.

查看更多
干净又极端
4楼-- · 2020-04-11 01:52

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.

查看更多
登录 后发表回答