Python Virtual Environment

DevOps Python

A very quick overview of how you can use Python virtual environments.

https://packaging.python.org/en/latest/guides/installing-using-pip-and-virtual-environments/

Install the Virtual Environment

First install the virtual environment.

pip install virtualenv
sudo apt install python3.10-venv

Create the Virtual Environment

Let’s say I have a project called “python-static-site”, so we’ll create the virtual environment within this project directory along with all the source files.

cd ~/python-static-site/
python3 -m venv env

The second argument is the location to create the virtual environment. Generally, you can just create this in your project and call it env.

venv will create a virtual Python installation in the “env” folder.

NOTE: You should exclude your virtual environment directory from your version control system using .gitignore or similar.

Activating a Virtual Environment

To use your virtual environment you need to activate it.

cd ~/python-static-site/
source env/bin/activate
which python

This should be showing “python” installed within your virtual environment, rather than somewhere centrally on the machine, as long as you are in this virtual environment any specific environment changes will only affect this virtual environment.

When you need to deactivate your virtual environment just run:

deactivate

1 thought on “Python Virtual Environment

Leave a Reply

Your email address will not be published. Required fields are marked *