We’ve been looking at a whole lot of Python programming and have tested out lots of Python packages. In order to do this, of course, we need Python installed on the computer we are working on. As we know, Python comes with a fantastic package manager called PIP. PIP makes it super easy to download and install any of the fantastic libraries available in Python. Here is the catch. As you begin to install more and more software packages, you could run into some problems. In software, so many times less is more. So instead of installing so many Python libraries globally on your machine, you can instead use Python Virtual Environments and only make use of what is needed for a particular project.
Python Standard Library
Once you have Python installed, you have access to the Python Standard Library. A standard library in Python is the library made available for common programming tasks. It consists of built-in modules that provide system functionality like input/output as well as modules written in Python that provide standardized solutions for many problems that occur in everyday programming.
The Python standard library is great for doing all kinds of things with Python programming. Part of the fun of Python, however, is making use of all the Python Libraries that are available. For example, we have been working a fair bit with the Django Web Framework recently, and this is one example of when it makes perfect sense to use a virtual environment in Python. We install these packages using PIP. PIP is the package manager for Python. It is a tool that makes it possible to install libraries that are not part of the standard library. Once you start playing around with PIP, you’ll likely find yourself installing all kinds of software on your machine, and this is great! The drawback, however, is that after some time, you may have so many different libraries that they start to clash and produce unexpected results. This is where virtualenv comes into play.
What is a Python Virtual Environment?
A cooperatively isolated runtime environment that allows Python users and applications to install and upgrade Python distribution packages without interfering with the behavior of other Python applications running on the same system.
Checking Python Version
Ok, this sounds like fun so let’s get a virtual environment set up and working. To start, we need to ensure Python is installed. Simply typing python or python -v at the command line will do the trick.
If you did enter the Python shell like we just did, you can exit out of it by typing exit() and then hitting enter.
Verifying PIP Installation
We are going to use PIP to install the virtualenv module so first, we need to ensure that PIP itself is ready to go. Just type pip freeze at the terminal, and there should be some output that shows all of the currently installed Python libraries.
The output shows we have asgiref, astroid, autopep8, colorama, Django, django-debug-toolbar, isort, lazy-object-proxy, mccabe, MouseInfo, Pillow, PyAutoGUI, pycodestyle, PyGetWindow, pylint, PyMsgBox, pyperclip, PyRect, PyScreeze, PyTweening, pytz, six, sqlparse, virtualenv, virtualenvwrapper-win, and wrapt installed. By using a virtual environment, we’ll be able to start with a clean slate instead.
Folder to hold virtual envs
You can create or navigate to a directory on your machine to hold your virtual environments. It’s not a bad idea to simply create a new virtual environment for each project you work on. That way you could have a virtual environment for working with Django, one for Flask, one for Numpy, and so on. We are going to simply use a folder located at
/c/python like we see.
Now at the command prompt in the directory of your choosing just type
pip install virtualenv. Once complete, you should be able to run
pip freeze once again, and virtualenv should be one of the listed softwares available.
Add a folder to hold your virtualenv
Inside of our chosen path,
/c/python, lets add a parent directory to hold the virtualenv we are about to create. We can create venv1, and then change into venv1.
Create a Virtualenv
We are ready to create a virtual environment! We will type
virtualenv . at the command line like so.
venv1 $virtualenv . Using base prefix 'c:\users\yourname\appdata\local\programs\python\python38-32' New python executable in C:pythonvenv1Scriptspython.exe Installing setuptools, pip, wheel... done
Now we can type
ls and we should see the new files and folders like Include/, LICENSE.txt, Lib/, Scripts/, and tcl/.
Everything is in place. Before you can use your new virtualenv, you need to activate it. This can be done by typing
source ./Scripts/activate in the virtualenv folder. This should activate the virtualenv and a new prompt should appear like (venv1) venv1 $ indicating that the venv1 virtual environment is now active.
Notice No Packages
From within the virtualenv, you can now once again type pip freeze to list any Python modules installed. Hint: There shouldn’t be any just yet! This is your blank slate that is ready for development.
Install Django In Virtualenv
Django will be the first package we install in this virtual environment by typing pip install django. Let’s do it!
(venv1) venv1 $pip install Django Collecting Django Using cached Django-3.0.3-py3-none-any.whl (7.5 MB) Collecting sqlparse>=0.2.2 Using cached sqlparse-0.3.1-py2.py3-none-any.whl (40 kB) Collecting pytz Using cached pytz-2019.3-py2.py3-none-any.whl (509 kB) Collecting asgiref~=3.2 Using cached asgiref-3.2.3-py2.py3-none-any.whl (18 kB) Installing collected packages: sqlparse, pytz, asgiref, Django Successfully installed Django-3.0.3 asgiref-3.2.3 pytz-2019.3 sqlparse-0.3.1 (venv1) venv1 $pip freeze asgiref==3.2.3 Django==3.0.3 pytz==2019.3 sqlparse==0.3.1 (venv1) venv1 $
By installing Django, we can see some additional dependencies are also installed like asgiref, pytz, and sqlparse. This is the beauty of working in virtual environments. It’s like a way to organize and manage your software, projects, and code, without having to set up a full-blown virtual machine or container workflow.
Launch A Django Project
Now let’s go ahead and create a new Django project inside of the virtual environment we have set up by typing django-admin startproject djangoproject.
Running the Django project works!
(venv1) djangoproject $python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. March 03, 2020 - 13:08:56 Django version 3.0.3, using settings 'djangoproject.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK.
Now let’s stop the server with Ctrl-C.
When your done working on a particular project in a virtual environment, you should deactivate the virtualenv. To do so, simply type deactivate at the command line inside of the given virtual environment.
Learn More About Virtualenv
- Python Virtual Environments (towardsdatascience.com)
- How To Setup A Python Virtual Environment On Centos (liquidweb.com)
- How To Setup A Python Virtual Environment On Windows 10 (liquidweb.com)
- Virtualenv 20 0 0 Beta1 Is Available (discuss.python.org)
- Effective Python Environment (realpython.com)
- Virtualenv.pypa.io En Latest User_Guide.html (virtualenv.pypa.io)
- Python Virtualenv Virtualenvwrapper (hackersandslackers.com)
- Python With Virtualenv (robbinespu.gitlab.io)
- Basics How To Use Python Virtualenv (pythonforbeginners.com)
- Developer.mozilla.org En Us Docs Python Virtualenv (developer.mozilla.org)
- Pypi.org Project Virtualenv (pypi.org)
- Docs.python Guide.org Dev Virtualenvs (docs.python-guide.org)
- How To Install Virtualenv Python (pythoncentral.io)
- Docs Tutorial Venv.html (docs.python.org)
Python Virtual Environment Summary
Using Virtualenv is not mandatory for Python development, especially when you are first starting out. In the beginning, all you need to do is get Python installed, and then you can begin tinkering with the language learning about variables, statements, expressions, loops, functions, and so on. As you begin to leverage more Python packages using the PIP package manager, it makes sense to start isolating each project. With this approach, you tackle the problem of dependencies and versions, and sometimes permissions. Imagine you have an application that needs version 1 of HappyTime, but another application requires version 2 of HappyTime. If you install everything into your host python you’ll end up in a situation where two packages have conflicting requirements. To fix this, we set up a virtualenv for each different Python project we work on. In this tutorial, we did the following:
- Learned What A Python Virtual Environment is
- Checked our Python install version
- Ensured PIP is installed
- Added a directory to hold virtualenvs
- Installed the virtualenv software
- Created a new virtualenv
- Activated the virtualenv
- Installed Django in a virtualenv
- Created a new Django project in a virtualenv
- Launched a Django server in a virtualenv
- Deactivated the virtualenv