In this Python tutorial, I am going to show you the correct way of using user local Python environment under PEP668.
PEP 668 focuses on ensuring Python packaging interoperability with system package managers. To maintain a clean and controlled environment for Python projects, it’s crucial to use virtual environments. This guide will walk you through creating and using a virtual environment in Python.
Step-by-Step Guide
Step 1: System Preparation
- Check Python Installation: Verify if Python is installed by running
python3 --versionin the terminal. If it’s not installed, download it from the Python official website. - Install python3-full (Optional): Some users might need the complete set of Python tools and libraries provided by
python3-full. This can be installed through your system’s package manager.
Step 2: Creating a Virtual Environment
- Create Environment: Execute the command:bash
python3 -m venv path/to/venvReplacepath/to/venvwith your preferred directory path.
Step 3: Activating the Environment
- Activate: From your terminal, navigate to your virtual environment directory and activate it using:
source path/to/venv/bin/activateYour terminal prompt should now indicate that the virtual environment is active.
Step 4: Working Inside the Virtual Environment
- Using Python: Inside the virtual environment, use:
path/to/venv/bin/pythonfor running Python scripts. - Installing Packages: Install packages specifically for this environment using:
path/to/venv/bin/pipThis ensures that your global Python installation remains unaffected.
Alternative Approach: Using System Python with Pip
- The
--break-system-packagesFlag: If, for some reason, you decide to use the system Python and want to install packages system-wide, pip can be run with the--break-system-packagesflag. However, this method is risky and can compromise the stability of your system Python environment.
Conclusion
Utilizing a virtual environment in Python is a best practice for project isolation and dependency management, especially in the context of PEP 668. It safeguards your system Python installation from unwanted changes. Always prefer using a virtual environment over modifying the system-wide Python setup.
If you want to exit the virtual environment, simply type deactivate in the terminal. This will return you to your system’s default Python environment.