Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activate virtualenv in Makefile

Tags:

makefile

How can I activate virtualenv in a Makefile?

I have tried:

venv:
    @virtualenv venv

active:
    @source venv/bin/activate

And I've also tried:

active:
    @. venv/bin/activate

and it doesn't activate virtualenv.

like image 615
Regis Santos Avatar asked Aug 30 '25 15:08

Regis Santos


2 Answers

Here's how to do it:

You can execute a shell command in a Makefile using ();

E.g.

echoTarget: 
    (echo "I'm an echo")

Just be sure to put a tab character before each line in the shell command. i.e. you will need a tab before (echo "I'm an echo")

Here's what will work for activating virtualenv:

activate:
    ( \
       source path/to/virtualenv/activate; \
       pip install -r requirements.txt; \
    )
like image 181
wizurd Avatar answered Sep 13 '25 16:09

wizurd


UPD Mar 14 '21

One more variant for pip install inside virtualenv:

# Makefile

all: install run

install: venv
    : # Activate venv and install smthing inside
    . venv/bin/activate && pip install -r requirements.txt
    : # Other commands here

venv:
    : # Create venv if it doesn't exist
    : # test -d venv || virtualenv -p python3 --no-site-packages venv
    test -d venv || python3 -m venv venv

run:
    : # Run your app here, e.g
    : # determine if we are in venv,
    : # see https://stackoverflow.com/q/1871549
    . venv/bin/activate && pip -V

    : # Or see @wizurd's answer to exec multiple commands
    . venv/bin/activate && (\
      python3 -c 'import sys; print(sys.prefix)'; \
      pip3 -V \
    )

clean:
    rm -rf venv
    find -iname "*.pyc" -delete

So you can run make with different 'standard' ways:

  • make - target to default all
  • make venv - to just create virtualenv
  • make install - to make venv and execute other commands
  • make run - to execute your app inside venv
  • make clean - to remove venv and python binaries
like image 24
viktorkho Avatar answered Sep 13 '25 15:09

viktorkho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!