Creating A Virtual Python Environment (Python)

One of the issues I’ve hit when using Python is that sometimes a certain version of a Python module/library is needed and conflicts can arise. So if you are like me and fire up PIP to play with modules/libraries you probably have lots of them installed in the Global Python install. Using Docker can resolve this issue but for those that don’t want to use Docker there is also the option of using a Python Virtual Environment.

To create a Python Virtual Environment:

  • Open Terminal / BASH
  • Create a folder for your project (mkdir folder_name)
  • Navigate to the project folder (cd folder_name)
  • Create the virtual environment (python3 -m venv ./venv)
  • Activate the virtual environment (source ./venv/bin/activate)
Terminal commands to create Python Virtual Environment
It only takes a few commands to create a virtual environment

As the above screen shot shows, it only takes a few commands to create and activate the virtual environment. The ls command is just to show that the folder was empty and the final line (with the venv prefix) shows that the virtual environment is activated.

There are a few commands that can be used to double check that a virtual environment is now in use:

python_virtenv_geektechstuff_2
New Python Virtual Environment
  • which python – displays where Python is running from
  • which pip3 – displays where Pip is running from
  • pip list – displays the modules/libraries installed by pip, in a new virtual environment this should be minimal.

The virtual environment can be turned off using the deactivate command.

The below shows my regular Python environment, which compared to my new Python virtual environment is packed with modules/libraries.

python_virtenv_geektechstuff_3
Non-Virtual Environment Python

3 responses to “Creating A Virtual Python Environment (Python)”

  1. Installing Django (Python) – Geek Tech Stuff Avatar

    […] it. My recommendation is to install Django in a virtual Python environment, which my previous blog post discusses. After creating and activating the virtual Python environment, the installation of Django […]

    Like

  2. Creating A Docker Image – Geek Tech Stuff Avatar

    […] Python Virtual Environment […]

    Like

  3. Jenkins – Connecting To GitHub and some Python – Geek Tech Stuff Avatar

    […] commands create a virtual Python environment , activates it and then uses pip to install all the requirements for my […]

    Like

Welcome to GeekTechStuff

my home away from home and where I will be sharing my adventures in the world of technology and all things geek.

The technology subjects have varied over the years from Python code to handle ciphers and Pig Latin, to IoT sensors in Azure and Python handling Bluetooth, to Ansible and Terraform and material around DevOps.

Let’s connect