Managing Python Environments in Ubuntu: A Guide to Avoiding “Externally Managed” Errors

by Pete
4 minutes read

If you’re working with Python on Ubuntu, you might have encountered the frustrating “This environment is externally managed” error. This often happens when trying to use pip to install packages in a Python environment managed by Ubuntu’s system package manager, apt. This error can halt your project’s progress, leaving you scratching your head. But worry not! Today, I’ll guide you through setting up and using Python environments properly to avoid this issue.

Why Use Virtual Environments?

Python applications can have varying dependencies with specific version requirements. Using a virtual environment allows you to manage these dependencies independently of the system packages, which is crucial for avoiding conflicts and ensuring that your projects run reliably.

Step-by-Step Guide to Setting Up Python Virtual Environments

1
Install Python 3

Ubuntu usually comes with Python 3 pre-installed. You can verify this by running:

python3 --version

If Python is not installed, you can install it along with the virtual environment package by using:

sudo apt update
sudo apt install python3 python3-venv

2
Create a Virtual Environment

Creating a virtual environment is simple. Just decide on a directory where you want to place your environment and run:

python3 -m venv myenv

Replace myenv with your preferred name for the environment. This command creates a new directory myenv containing the environment.

3
Activate the Virtual Environment

Before using the environment, you must activate it:

source myenv/bin/activate

Your command prompt will change to show that you are now working inside the myenv environment, which is isolated from the system’s packages.

4
Install Packages Using Pip

With the environment activated, you can now safely use pip to install any necessary packages:

pip3 install numpy

This will install packages into your virtual environment without affecting global system settings, thereby avoiding the “externally managed” error.

or from a requirements file:

pip3 install -r requirements.txt

5
Deactivate the Environment

Once you’re done, you can exit the environment by running:

deactivate

Conclusion

Using virtual environments in Python is a best practice that not only helps in avoiding conflicts with system packages but also keeps your project’s dependencies well-organized and controlled. Remember, always activate your virtual environment before running or developing your Python projects on Ubuntu. This simple habit ensures your development environment remains clean and manageable.

By following these steps, you can seamlessly manage Python packages and avoid the pitfalls of an “externally managed” environment. Happy coding!