Skip to content

Instantly share code, notes, and snippets.

@muxator
Created October 24, 2019 08:58
Show Gist options
  • Save muxator/0c0faa05213477e03ce7e3b921616fd5 to your computer and use it in GitHub Desktop.
Save muxator/0c0faa05213477e03ce7e3b921616fd5 to your computer and use it in GitHub Desktop.
Manage your python projects with pyenv

Pyenv installation

Prerequisites:

Install the following packages as an administrator. They will be needed when building python.

sudo apt install build-essential libbz2-dev libsqlite3-dev libreadline-dev libssl-dev zlib1g-dev libgdbm-dev liblzma-dev uuid-dev libffi-dev

Install pyenv

As your user, download and install pyenv:

curl -L https://github.com/pyenv/pyenv-installer/raw/master/bin/pyenv-installer | bash

Pyenv has to be enabled adding the following lines at the end of <USER_HOME_DIRECTORY>/.bashrc:

export PATH="<USER_HOME_DIRECTORY>/.pyenv/bin:$PATH"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"

As a final step, logout & login to be able to use pyenv.

Build Python versions

This step must be executed only once per each python version you need.

  1. install the prerequisites as indicated in the first section

  2. Build your python version (e.g. 3.7.5):

    pyenv install 3.7.5

    This will make available a python 3.7.5 in your user environment

Creating a project

It is good practice to develop each project in its dedicated virtualenv (https://virtualenv.pypa.io/en/latest/). A virtualenv can be created in many ways. We'll use pyenv.

  1. Create a virtual environment:
    pyenv virtualenv 3.7.5 yourproject-venv

This will create a dedicated virtualenv for your project in an hidden directory somewhere.

  1. Clone your code (or create an empty repo if you are starting from scratch).

    cd ~
    git clone http://host/yourproject
  2. instruct pyenv to always activate the virtualenv you created.

    cd ~/yourproject
    pyev local yourproject-venv

    From that moment on, every time you'll go inside ~/yourproject, the dedicated virtualenv will be activated.

  3. install the libraries you need. From within the virtualenv, you are free to install all the packages you need.

    Install a single package:

    cd ~/yourproject
    pip install requests

    Install from the requirements file, if exists

    cd ~/yourproject
    pip install -r requirements.txt

    Save the list of your dependencies in requirements.txt. You may want to commit this file.

    cd ~/yourproject
    pip freeze > requirements.txt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment