When working on different Python projects, it's often necessary to create isolated environments for specific tasks. This is where Python's Virtual Environments package comes in handy.
Use this post as a guide or a cheat sheet for future reference.
Creating a Virtual Environment
To create a new virtual environment, use the following command:
python3 -m venv .venv
The .venv directory will contain your virtual environment. Using a dot (.) before the name makes it a hidden folder, which is a common practice. However, you can name it anything you like to suit your project structure.
Activating the Virtual Environment
To activate the virtual environment, run:
source .venv/bin/activate
Once activated, you can install any required packages and libraries. These installations will be isolated within the .venv directory and will not affect global Python packages.
For example, to install pandas:
pip install pandas
Deactivating the Virtual Environment
To deactivate the virtual environment, simply run:
deactivate
Listing Installed Packages
While the virtual environment is activated, you can list all installed packages using:
List
pip list
pip freeze
The only difference between each command is that list will display a human-readable list while freeze will outputs installed packages in a machine-readable format.
Sharing Your Virtual Environment
If you need to share your project, ensure that others can replicate your environment. You can do this by exporting the installed packages to a requirements.txt file:
Save your venv into a .txt
pip freeze > requirements.txt
If you receive a requirements.txt file from a colleague or friend, you can install all required packages by running:
Import the packages from a requirements.txt
pip install -r requirements.txt
By following these steps, you can effectively manage your Python environments and ensure consistency across different projects.
Top comments (0)