In a nutshell, a virtual environment is a named, isolated, working copy of Python that that maintains its own files, directories, and paths so that you can work with specific versions of libraries or Python itself without affecting other Python projects.
Why the Need for Virtual Environments?
At its core, the main purpose of Python virtual environments is to create an isolated environment for Python projects. This means that each project can have its own dependencies, regardless of what dependencies every other project has.
Create virtual environments with Anaconda
With conda, you can create, export, list, remove, and update environments that have different versions of Python and/or packages installed in them. Besides that, it is possible to switch or move between environments by simply activating the environment. You can also share an environment file.
- Check conda is installed and in your PATH
- Open a terminal client.
conda -Vinto the terminal command line and press enter.
- If conda is installed you should see something like the following.
$ conda -V
Check conda is up to date
In the terminal client enter
$ conda update conda
2. Creating an environment with commands
Use the terminal or an Anaconda Prompt for the following steps:
- To create an environment:
conda create --name yournewenv
This creates the
yournewenv environment in
/envs/. No packages will be installed in this environment.
To create an environment with a specific version of Python:
conda create -n yournewenv python=3.7
To create an environment with a specific package:
conda create -n yournewenv numpy
conda create -n yournewenv python
conda install -n yournewenv numpy
To create an environment with a specific version of Python and multiple packages:
conda create -n yournewenv python=3.7 numpy=1.19.0 astroid babel
3. Activate your virtual environment.
To activate or switch into your virtual environment, simply type the following where
yournewenv is the name you gave to your environment at creation.
conda activate yournewenv
Install additional Python packages to a virtual environment.
conda install -n yournewenv [package]
4. Deactivate your virtual environment.
To end a session in the current environment, enter the following. There is no need to specify the
yournewenv — which ever is currently active will be deactivated, and the PATH and shell variables will be returned to normal.
5. Delete a no longer needed virtual environment
To delete a conda environment, enter the following, where
yournewenv is the name of the environment you wish to delete.
conda remove -n yournewenv -all
For more information, please refer to the conda official documentation that can be found here.