How to create virtual environment in Python

How to create virtual environment in Python

While working on a new python project, it might happen that you need to install a new version of a package whose older version is already being used by another python project. If you install the new version system wide, it may create compatibility issues in your other python project.

To avoid this we need isolated environment for each python project so that any package installed in that isolated environment is available just for that particular project. This kind of isolated environment is called virtual environment in python.

This is how you can create a virtual environment :

CREATE

Open the terminal and go to your python project's root directory and type:

# Linux and macOS
python3 -m venv virtual_environment_name
# Windows
py -m venv venv virtual_environment_name

This creates a virtual environment in project's root directory with name virtual_environment_name.

ACTIVATE

To use this environment and install any packages, type:

# Linux and macOS
source virtual_environment_name/bin/activate
# Windows
.\virtual_environment_name\Scripts\activate

This activates the virtual environment, now whatever package you install with pip, will stay inside this virtual environment.

EXIT

You can exit the virtual environment by typing 'deactivate'.

# Linux, macOS and Windows
deactivate

BONUS

If you need to replicate this project in some other system or directory, simply copying this environment will not work. For that, first activate this environment and create a list of all packages by typing:

pip3 freeze > requirements.txt

This creates a .txt file with all packages listed inside.

Then go where you want to replicate the project and create a new virtual environment in project's root directory. Activate the new environment. Import the package list we just created. And finally run this command to install all the required packages.

pip3 install -r requirements.txt

That is all you need to do to isolate your python project dependencies.

I hope it helps you. If you have any suggestion or I missed out something, let me know in the comments.

I plan to write on python (and other topics) consistently. Find me on twitter here for regular notifications when I post something.