DEV Community

Cover image for How to Create Python Virtual Environments on Ubuntu
Luiz Gustavo Erthal
Luiz Gustavo Erthal

Posted on

How to Create Python Virtual Environments on Ubuntu

When working on different Python projects, it's often necessary to create isolated environments for specific tasks. This is where Python's Virtual Environments package comes in handy.

Use this post as a guide or a cheat sheet for future reference.

Creating a Virtual Environment

To create a new virtual environment, use the following command:

python3 -m venv .venv
Enter fullscreen mode Exit fullscreen mode

The .venv directory will contain your virtual environment. Using a dot (.) before the name makes it a hidden folder, which is a common practice. However, you can name it anything you like to suit your project structure.

Activating the Virtual Environment

To activate the virtual environment, run:

source .venv/bin/activate
Enter fullscreen mode Exit fullscreen mode

Once activated, you can install any required packages and libraries. These installations will be isolated within the .venv directory and will not affect global Python packages.

For example, to install pandas:

pip install pandas
Enter fullscreen mode Exit fullscreen mode

Deactivating the Virtual Environment

To deactivate the virtual environment, simply run:

deactivate
Enter fullscreen mode Exit fullscreen mode

Listing Installed Packages

While the virtual environment is activated, you can list all installed packages using:

List

pip list
Enter fullscreen mode Exit fullscreen mode
pip freeze
Enter fullscreen mode Exit fullscreen mode

The only difference between each command is that list will display a human-readable list while freeze will outputs installed packages in a machine-readable format.

Sharing Your Virtual Environment

If you need to share your project, ensure that others can replicate your environment. You can do this by exporting the installed packages to a requirements.txt file:

Save your venv into a .txt

pip freeze > requirements.txt
Enter fullscreen mode Exit fullscreen mode

If you receive a requirements.txt file from a colleague or friend, you can install all required packages by running:

Import the packages from a requirements.txt

pip install -r requirements.txt
Enter fullscreen mode Exit fullscreen mode

By following these steps, you can effectively manage your Python environments and ensure consistency across different projects.

Top comments (0)