Python Virtual Environments
Why Use Virtual Environments
When working with Python projects, you may find yourself in need of installing libraries that aren't included in the base installation of Python. Often, these libraries depend on other libraries, and sometimes very specific versions of them. This can result in the dependencies for one library conflicting with those of another.
To avoid this, it is recommended that you use virtual environments for each of your projects in order to ensure there are no conflicting libraries.
Additionally, using virtual environments allows you to install Python libraries via pip without needing root access or requesting the IT staff to install the libraries for you.
Creating a Virtual Environment
To create a virtual environment, run the following in the terminal:
python3 -m venv <name>
This will create a new folder in the current directory called <name> which will contain your virtual environment and any libraries you install.
For example, to create a virtual environment called my_project:
python3 -m venv my_project
Activating a Virtual Environment
After creating a virtual environment, you can activate it by running:
source /path/to/environment/<name>/bin/activate
Where /path/to/environment is the location of the virtual environment folder and <name> is the name of your virtual environment.
For example, if you created a virtual environment named my_project in your home directory:
source ~/my_project/bin/activate
When you activate a virtual environment, you will see the name of your virtual environment in front of the prompt in your terminal:
(my_project) [netID@computername ~]$
If you're activating the virtual environment for the first time, you should upgrade pip:
pip install --upgrade pip
Installing Packages
Once you have activated your virtual environment, you can install packages through pip. To find packages, visit PyPI (Python Package Index) and search for the package you need.
To install a package:
pip install <package>
For example, to install the requests library:
pip install requests
After installing a package, you can use it with any Python script or the Python interpreter as long as you are still inside your virtual environment.
Remember that packages installed in a virtual environment are only available within that environment.
Using requirements.txt
To make your project reproducible, you can save your installed packages to a requirements.txt file:
pip freeze > requirements.txt
To install all packages from a requirements.txt file (useful when sharing a project or setting up on a new machine):
pip install -r requirements.txt
Deactivating a Virtual Environment
When finished using Python in the virtual environment, or if you need to switch to a different one, exit the current virtual environment by running:
deactivate
Deleting a Virtual Environment
If you no longer need a virtual environment and wish to delete it, simply delete the directory that contains it:
rm -r <name>
For example:
rm -r my_project