Python project and environment setup

09 Jan 2020

Python projects use packages to extend the base language set. Both virtualenv and pipenv provide a way to manage the packages in a project

Background

Pre-requisites

  1. Install Python 3 globally sudo apt install python3

  2. Install pip3 globally sudo apt install pip3

PIPENV setup

  1. Install pipenv locally pip install --user pipenv

  2. As the user bin path to python is not accessible globally, and not defined by the installation, add the following into the ~/.profile file to declare the path to python

     # add Python pip and pipenv paths
     PYTHON_BIN_PATH="$(python3 -m site --user-base)/bin"
     if [ -d "$PYTHON_BIN_PATH" ] ; then
       PATH="$PATH:$PYTHON_BIN_PATH"
     fi
    

VIRTUALENV setup

  1. Install virtualenv globally sudo pip install virtualenv, which allows other host users to use virtualenv also

Project Setup (Linux)

Create the project directory

  1. Create the project directory mkdir <project_dir>

  2. Change to the project directory cd <project_dir>

Create GIT repository

  1. Create a local git repository git init

  2. Create a git ignore file touch .gitignore

Managing Project Packages via virtualenv

These operations are on the project, and the command should only be run from within the project root folder.
Operation Command
Get version virtualenv --version
Create virtual environment venv (or any other name) virtualenv venv
Activating a virtual environment, (use when not activated already) source venv/bin/activate
Leave the virtual environment deactivate
Delete a virtual environment rm -rf venv

Managing Project Packages via pipenv

These operations are on the project, and may modify the cache. Only run these commands from within the project root folder.
Operation Command
Create a pipenv enabled environment pipenv install
Open a shell for the environment pipenv shell
Exit the shell exit
Add a package pipenv install <package_name>
Remove a package pipenv uninstall <package_name>
Update a package pipenv update <package_name>
Run a project outside the environment shell pipenv run python3 <python_file.py>
Run a project inside the environment shell python3 <python_file.py>
Clean the package cache, removing packages found which are not in the Pipfile.lock pipenv clean

Environment consistency with virtualenv or pipenv

Operation Command
Freeze packages creates a file which lists the packages inside a local virtual environment pip freeze > requirements.txt
Install requirements from a freeze list file pip install -r requirements.txt

Project Hierarchy

If your project contains subfolders which contain python scripts which cross reference other folders, accessing those folders requires a root python folder.

  1. In the root folder create an empty init file touch __init__.py