
Python Virtual Environments: Managing Dependencies
Creating a Virtual Environment
The first step in managing dependencies with virtual environments is creating a new environment.
# Creating a virtual environment named 'myenv' python -m venv myenv
Activating the Virtual Environment
To start using the virtual environment, you need to activate it.
# On Windows myenvScriptsactivate # On Unix or Linux source myenv/bin/activate
Installing Packages with Pip
With the virtual environment activated, you can now install packages using pip
. Pip is a package manager for Python that allows you to easily install, upgrade, and remove packages.
To install a package, simply use the pip install
command followed by the name of the package.
pip install package_name
If you want to install a specific version of a package, you can specify it using the ==
operator.
pip install package_name==version_number
You can also specify a minimum version using the >=
operator.
Managing Dependencies
Pip makes it easy to manage dependencies within a virtual environment. When you install a package, pip will automatically install any required dependencies as well.
You can use the pip freeze
command to generate a list of installed packages and their versions.
pip freeze
This will output a list of packages and their versions in the format package_name==version_number
. You can redirect this output to a file to save the dependencies.
pip freeze > requirements.txt
You can then share this file with others working on the project, allowing them to easily install the same set of dependencies.
To install dependencies from a requirements file, you can use the pip install -r
command followed by the path to the file.
Deactivating the Virtual Environment
To deactivate the virtual environment and return to the global Python environment, you can use the deactivate
command.
deactivate
With this, you now have a solid understanding of virtual environments and how to manage dependencies using Python.