What is a python virtual environment?
A Python virtual environment is an isolated environment for Python projects. This means that each project can have its own dependencies and let other projects have their own
It also means each project can have its own python version. For example, Project X could be using Python 2.7, and Project Y uses Python 3.6.
The creation of python environments is done using the
venv module in python. The
venv is an inbuilt Python module, no need for any installation if you have python already installed.
Virtual Environments are created for specific python projects. So to create one, you have to know the path to your project's main directory.
Creating a Project directory or folder
Run the following code in your command line or terminal:
mkdir first_project && cd first_project
mkdir first_project creates a directory or folder called
first_project and the cd f
irst_project navigates into the directory.
&& just represents "and".
It is just the same as creating an empty folder and then opening it.
first_project is the directory where all your project files are going to be. It is also the same directory where our virtual environment will be created
Creating the virtual environment
To create a virtual environment, run the
venv module as a script. Note: You should be navigated into your project directory in the command line before running this:
python -m venv firstproject-env
firstproject-env is the name given to the virtual environment being created, you could call it whatever you want. python tells the virtual environment to be created with the Python version available.
If you have multiple versions of Python on your system, you can select a specific Python version by running
python3 or whichever version you want like this:
python3 -m venv firstproject-env
.The first one is required when you have only one python version installed
So running the command will create the
firstproject-env directory if it doesn’t exist, and also create directories inside it containing a copy of the Python interpreter, the standard library, and various supporting files.
Activating virtual environment
Once you’ve created a virtual environment, you may activate it.
On windows :
On Mac OS
Activating the virtual environment will change your shell’s prompt to show what virtual environment you’re using.
On windows it looks something like this:
That's it. You can then install, upgrade, and remove packages using pip. The packages installed will be isolated only for a given project.
You should not worry about virtual environments if you are using an IDE like PyCharm. It automatically creates a virtual environment whenever you create a new python project.