A virtual environment is a tool used to isolate specific Python environments on a single machine, allowing you to work on multiple projects with different dependencies and packages without conflicts. This can be especially useful when working on projects that have conflicting package versions or packages that are not compatible with each other.
you can use the venv module that comes with Python. Here's an example of how to create a virtual environment and activate it:
# Create a virtual environment
python3 -m venv <your_virtual_environment_name> # this needs python3.10-venv package to be installed
# Activate the virtual environment (Linux/macOS)
source <your_virtual_environment_name>/bin/activate
# Activate the virtual environment (Windows)
<your_virtual_environment_name>\Scripts\activate.bat
Python3
command takes you to python environmentexit()
command throws you out of Python shell Pip
to install Python modules
# Deactivate the virtual environment
deactivate
requirements.txt
file, that lists the packages and their versions that your project depends on. To create a requirements.txt file, you can use the pip freeze command, which outputs a list of installed packages and their versions.
For example:
# Output the list of installed packages and their versions to a file
pip freeze > requirements.txt
To install the packages listed in the requirements.txt file, you can use the pip install command with the -r flag:
# Install the packages listed in the requirements.txt file
pip install -r requirements.txt
-r
is used to tell PiP that we are giving input & not to install a package.
otherwise pip will take
requirments.txt
as a package.
Using a virtual environment and a requirements.txt file can help you manage the dependencies for your Python projects and ensure that your projects are portable and can be easily set up on a new machine.