This guide shows how to get started programming with Python, the very first thing you need to understand before programming Python is virtual environments.
By default, the global Python packages are used but if we are creating a new Python app then a new environment is required so that the packages of the new environment can be used instead of the global libraries.
Creating a new virtual environment
Check the packages in your global virtual environment using the pip list command.
pip list
Install virtualenv using pip.
pip install virtualenv
Create a new folder for a new Python project.
mkdir project1
Change to the new Python project.
cd project1
Create the new virtual environment within this project.
python3 -m venv env
Switch the current virtual environment to the env that was just created.
source env/bin/activate
Verify that the virtual environment has changed check the libraries using the pip list.
pip list
Create a requirements.txt file with the current packages installed in the virtual environment.
pip freeze > requirements.txt
Switch back to the global Python environment using the following command.
deactivate
Verify that the global libraries are in use using the pip list command.
pip list
Using existing requirements.txt file
The requirements.txt is supposed to be bundled with your Python files and the virtual environment (env folder) is excluded from your Python files.
The reason is that when other developers want to run your Python project, they can use the requirements.txt file to load up the libraries for a new virtual environment.
Create the new virtual environment inside of the project.
python3 -m venv env
Activate the new virtual environment.
source env/bin/activate
Now install the packages using the requirements.txt file.
pip install -r requirements.txt