Python Virtual Environments: Basic Stuff
Installation, setup and basic usage of virtual envsIn this simple and short post, I tell you how to use python’s virtual environments at it’s most basic form. I’ll be writing more articles that talk about using more related tools and some advanced stuff.
Intro
We need virtual environments when we want to develop python applications on the same system or computer. a python environment is a collection of versioned python packages found in specific folders. And since each project may require different package versions, We use virtualenvs to create separate worlds for each application, these are called isolated python environments.
You can read this post from realpython.com to learn more details about virtual environments. I’ll just assume you know the basics and give you a quick handy guide to use as a reference.
Setup
make sure to have both python and pip installed and then to install virtualenv on your system:pip install virtualenv
. That's it.
Make sure to install this as a system package and not within another virtual environment.
Creating a virtual environment
Where to install
You can create the new virtual environment where ever you heart desire, and you can put the environment’s directory either:
Just navigater to where the project repository is located and setup the new virtual environment, read below.
If you go with this make sure to ignore the folder and it’s content. Add this to your .gitignore: myvenv/
.
B. In an external directory
Usually the user’s home directory. I personaly prefer this, since this way I always know where to find all my environments. Just for better organization.
Either way, you navigate to the desired directory where you want to create the virtualenv and then:
for python 2 use virtualenv xxx
and for python 3, use python3 -m venv xxx
.
where xxx is the virtual environment name. developers usually name xxx after the project's name .
Using it
To activate the virtual environment, from within the directory you installed the xxx virtual environment, use source ./xxx/bin/activate
.
Your terminal prompt is now prefixed with the environment name $ (xxx)
. And you are now within the scope of the xxx virtualenv, anything you install using pip will be available only to this environment.
To get back to the global python scope, you deactivate the virtual enviromnet with deactivate
.