Python Virtual Environment Management

PythonPythonBeginner
Practice Now

Introduction

Python virtual environment is a tool used to isolate different Python environments on a single machine. This is useful when working on projects that have different requirements, or when you want to avoid conflicting packages in your global Python environment.

Achievements

  • virtualenv Command
  • Activate Virtual Environment
  • Exit Virtual Environment
  • Assgin Python Version

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") subgraph Lab Skills python/variables_data_types -.-> lab-96{{"`Python Virtual Environment Management`"}} python/data_collections -.-> lab-96{{"`Python Virtual Environment Management`"}} end

Creating Virtual Environment

First, let us create a Python virtual environment.

virtualenv venv

Now we have a virtual environment named "venv". Next, we can install Python packages in the virtual environment.

1-1

Using Virtual Environment

Now, we use the source command to activate the virtual environment:

source venv/bin/activate
2-1

Then, we install a third-path package:

pip install pygame
2-2

pygame is success installed in this environment.

pip list
2-3

Finally, use deactivate command to exit the virtual environment:

2-4

We can see pygame is not installed in the main environment.

2-5

Different Python Versions

We can also create a virtual environment using the Python version we want.

e.g. create a Python3 virtual environment, first, we must know where the Python3 is:

which python3
3-1

then we can use -p to assign it:

virtualenv -p /usr/bin/python3 venv3
3-2

Summary

Congratulations! You have completed the Python Virtual Environment Lab.

In this lab, you learned how to:

  • Create a Python virtual environment.
  • Use PyPI package manager to install packages in a Python virtual environment.
  • Manage different Python virtual environments.