In this Python virtual environment tutorial I will show you how to manage different projects that might require different versions of packages or modules.
By default all packages or modules are installed in the same location (this location is dependent on your system).
If you are writing a project that requires version 1.0 of a certain package and another project that requires version 1.5 of a certain package you have a bit of a problem.
This is where the Python virtual environment comes in.
It allows you install certain versions of packages within the virtual environment which is specific to your project.
What is a Virtual Environment in Python?
Page Contents
Basically a virtual environment is a folder with a few scripts in it that allows you to create an isolated environment to work on your project.
There is no limit to how many virtual environments you can have as it’s just a folder.
You can use virtualenv or venv to create this virtual environment.
Both perform the same job but venv is installed by default with Python and virtualenv has to be installed as a package.
If you are running Python2 you need to install virtualenv, if you are running Python 3 then venv is the way to go.
How do you create a virtual environment in Python 3 using venv?
First I would recommend you create a folder on your system where you have all your virtual environments.
mkdir VENVS cd VENVS
Then to create your environment use the command
python3 -m venv <name of your environment>
So if I wanted to create a virtual environment called env1 I would type
python3 -m venv env1
If I now do an ls in my VENVS folder I will see another folder called env1
To use this you now have to go into the folder and activate it, this will setup your shell so use the environments Python executable and it’s site packages by default.
Activate Python Virtual Environment
From within my VENVS folder I enter the command
source env1/bin/activate
You will now observe that your prompt changes
I am now working within an isolate environment. First let’s see what version of Python we are running with which python
We actually are running an isolated version of Python from within this folder.
Then we will see what packages we have installed with pip3 freeze
You can see there are none – compared to if we exit the venv this list would have all the packages.
To exit a virtual environment you use the command deactivate
Create Python Virtual Environment using virtualenv // Video
Conclusion
If you are just starting out learning Python you might not have a need to create a virtual environment, but as you write more code and different projects with different dependencies, you will find you are using the venv command every day!
I use Python for Network Automation if you like these posts and want to learn more check my other posts.
Leave a Reply