Use Python with virtualenv in Makefiles

In this article I will show you how I use Python with virtualenv in my Makefiles to automate deployments and other things.

I think it is a good idea to automate recurring tasks to save time and reduce errors. In some of my projects I use multiple Python and Shell scripts to automate the tasks and use a Makefile to glue the pieces together. I also use Pythons virtualenv to keep my Python environments as clean as possible.

In the following snipped you can find an example how my Makefiles might look like.

.PHONY: prepare_venv cache build deploy

VENV_NAME?=venv
PYTHON=${VENV_NAME}/bin/python

prepare_venv: $(VENV_NAME)/bin/activate

$(VENV_NAME)/bin/activate: requirements.txt
    test -d $(VENV_NAME) || virtualenv -p python3 $(VENV_NAME)
    ${PYTHON} -m pip install -U pip
    ${PYTHON} -m pip install -r requirements.txt
    touch $(VENV_NAME)/bin/activate

cache: prepare_venv
    ${PYTHON} do_cacheing.py

build: prepare_venv
    ${PYTHON} build.py

deploy: build
    scp -r output/example server:/srv/files/

As you might have noticed every regular task requires the prepare_venv task to prepare the virtualenv. The prepare task checks if the virtualenv exists and create it if it is missing. Than it checks if the requirements.txt file has changed since the last pip install and runs it if required.

Links

Verwandte Artikel