Python Virtual Environments — A Beginner Guide
Why do we need Virtual Environments?
When we are working on projects, there might be a few or many external packages we need to install and use in our projects. We can install those packages on our local machine (globally) and that’s what most beginners do. This makes your local machine cluttered with so many packages and if you’re working on several projects at once and if you remove/ update some packages, this may cause issues with dependencies as well. Also sharing your project becomes a nightmare as well.
To overcome all of those mentioned issues we can use virtual environments which manage the packages required for a particular project. We can have one virtual environment for each project that we’re working on. This way, all the packages that you install will be installed inside that virtual environment. So let’s take a look at how to set up virtual environments for your python project.
[In this guide I assume that you’re comfortable with basic shell commands]
So how to start?
Before we proceed, if you’d like to see the packages that you’ve installed on your local machine (globally); run the following command,
pip3 list
We can use a built-in venv module to create virtual environments. To create a new virtual environment on the current location: run,
python3 -m venv ./venv
If you want to create the venv somewhere else you can specify the path instead of .
. Eg: python3 -m venv {path}/venv
Now we have successfully created our virtual environment.
Now, you have to activate the venv before you use it. if you’re using zsh or bash shell, run the following command,
source ./bin/activate
If you have created the venv somewhere else, adjust your path accordingly.
You may notice that your shell prompt gets changed if you’re using shells; fish
, zsh
with ohmyzsh
configured or a high-level terminal emulator such as Warp Terminal.
If you run pip3 list
now, you’ll see the packages that you’ve installed in the currently activated environment.
How to Deactivate an activated virtual environment
Just type deactivate
and hit enter
key.
You can run rm -f {path}/venv
to delete the environment completely.
Additionally
If you wanted to export all the packages used within a virtual environment with their versions,
pip3 freeze > requirement.txt
This requrements.txt file will come in handy when you share your project with someone else (They can install all the packages/ dependencies listed in the requirements.txt file) or when deploying your app on a platform like Heroku.
When creating a new environment we can install the packages from a requirements.txt file.
pip3 install -r requirements.txt
I hope now you have a good understanding of how python virtual environments are made with venv module.
Thank you for reading and I Hope to see you with another article.
See you there!