Web and API Dev Essentials
Lesson Summary: Virtual Environments in Python
Introduction & Purpose
- Virtual environments are essential to run code in isolated environments, separate from the system’s default Python installations.
Creating and Managing Virtual Environments
- Installation: Use
sudo dnf install python3-virtualenv -yto install the necessary tool. - Creating: Create a virtual environment using
python -m venv <directory_name>. - Activating: Activate it with
source <directory_name>/bin/activate. - Deactivating: Deactivate it simply by typing
deactivate. - Removing: Completely remove it using
rm -rf <directory_name>.
Role of Virtual Environments
- They allow using specific Python interpreters and packages without affecting the system-wide Python setup.
Package Management with pip
- Installing pip:
sudo dnf install python3-pip. - Version Check: Ensure the versions of Python and pip match using
python --versionandpip --version. - Basic Commands:
pip install <package>to install.pip uninstall <package>to uninstall.pip listto show installed packages.pip search <package>to search for packages.pip install --upgrade <package>to upgrade a package.
- Use
pip install --userto avoid permission errors or activate a virtual environment before installation.
Saving and Reusing Package Requirements
- Freeze Requirements: Use
pip freeze > requirements.txtto create a requirements file. - Install from Requirements: Use
pip install -r requirements.txtto install all packages listed.
Helpful Tips
- Use
pip --helpto see all available commands and options. - Be cautious with the
rm -rfcommand as it permanently deletes the directory and its contents.
Conclusion
- The lesson addresses how to create, manage, and destroy virtual environments, save required packages, and manage packages using pip.
- Emphasizes the importance of version compatibility between Python and pip.
- Advises against using elevated privileges with pip unless absolutely necessary.
This article is incomplete and work is being done on this.
This post is licensed under CC BY 4.0 by the author.