Deactivating a Python Virtual Environment
After you finish working with a virtual environment, you may want to return to the system's global Python environment. This process is called deactivation.
How to Deactivate a Virtual Environment
-
Make sure your virtual environment is currently activated. You should see (myenv) at the beginning of your command prompt.
-
To deactivate the virtual environment, simply run:
deactivate
-
Notice that your command prompt has changed back to normal. The (myenv) prefix has disappeared:
labex:python_env_demo/ $
Verifying the Deactivation
To confirm that your virtual environment has been deactivated and you're back to using the system Python, run the following checks:
-
Check which Python interpreter is being used:
which python3
You should see output like:
/usr/bin/python3
This shows that the python3 command now points to the system-wide Python interpreter.
-
Try running the script we created earlier:
python3 test_requests.py
Depending on whether the requests package is installed in your system Python, you might see an error:
Traceback (most recent call last):
File "/home/labex/project/python_env_demo/test_requests.py", line 1, in <module>
import requests
ModuleNotFoundError: No module named 'requests'
This error occurs because the requests package was installed in your virtual environment, not in the system Python. This is one of the key benefits of virtual environments - isolating packages for different projects.
Reactivating the Virtual Environment
If you need to work with your project again, you can easily reactivate the virtual environment:
source myenv/bin/activate
Your command prompt will once again show (myenv), indicating that the virtual environment is active.
Common Virtual Environment Commands Summary
Here's a quick reference for the commands we've covered:
| Command |
Description |
python3 -m venv myenv |
Create a new virtual environment named "myenv" |
source myenv/bin/activate |
Activate the virtual environment |
pip install package_name |
Install a package in the active virtual environment |
pip list |
List installed packages in the active virtual environment |
deactivate |
Deactivate the current virtual environment |
These commands form the foundation of working with Python virtual environments, allowing you to create, use, and manage isolated Python environments for your projects.