Installing Packages in the Virtual Environment
Now that you have created and activated a virtual environment, you can start installing Python packages within this isolated environment. This ensures that your project's dependencies are properly managed and do not conflict with other projects or the system's global Python installation.
Installing Packages
To install a package in the active virtual environment, you can use the pip
command, which is the package installer for Python. Here's an example of how to install the requests
package:
(my-env) $ pip install requests
The (my-env)
prefix in the terminal prompt indicates that the virtual environment is currently active. All packages installed using pip
will be installed within this virtual environment, not the system's global Python installation.
Listing Installed Packages
You can view the list of installed packages in the active virtual environment by running the following command:
(my-env) $ pip list
This will display a table of all the packages installed in the current virtual environment, along with their versions.
Exporting and Importing Dependencies
To share your project's dependencies with others or to recreate the same environment on another machine, you can export the list of installed packages to a requirements file. This file can then be used to install the same set of dependencies in a new virtual environment.
To export the dependencies to a requirements file:
(my-env) $ pip freeze > requirements.txt
This will create a requirements.txt
file in the current directory, which contains the list of installed packages and their versions.
To install the dependencies from the requirements file in a new virtual environment:
- Create a new virtual environment:
python3 -m venv new-env
- Activate the new virtual environment:
source new-env/bin/activate
- Install the dependencies from the requirements file:
(new-env) $ pip install -r requirements.txt
This will install the same set of packages and dependencies in the new virtual environment, ensuring that your project can be easily reproduced on other machines.
By following these steps, you can effectively manage and share the dependencies of your Python project using virtual environments and the pip
package installer.