How to set up an isolated Python environment?

venv.jpg

Image from CultureGeek

Why create a Python Virtual Environment (venv) ?

Using the Python venv module, you can create an isolated environment to test different combination of packages without it affecting the main installation.

You can have different combinations of packages for different projects in your virtual environment without having to install it on the main system

Additionally, you won't need administrator permissions to install those packages.

Since version 3.3, Python comes with venv installed. So you won't need to install it manually. If however for some reason you do not have venv installed, you can install it using the following command :

pip install virtualenv

Creating the virtual environment.

You must specify a path where you want to create a virtual environment. For example, you can create one in your local directory using the command:

virtualenv my_env

You can use any name you want for your virtual environment instead of the name 'my_env'

Activating the virtual environment.

Just creating the environment is not enough, you need to activate it to use it. You can activate it by running the command:

For Windows

my_env\Scripts\activate

For MacOS/Linux

source my_env/bin/activate

Upon successful activation you would see the name of your environment in brackets before the path in terminal like this:

(my_env) C:\Users\Saurav\projects\blog>

Deactivating the virtual environment.

It is recommended to always deactivate the virtual environment when you done. You can do that using the command:

deactivate

Provided you are in the activated virtual environment, the above command will deactivate it.

Congratulations! You just created a Virtual Environment for your python packages. Explore and experiment away!

Hope you enjoyed this post! If you happen to like it, feel free to share. You can also follow me on Twitter on my coding journey.