Python Virtual Environments: How to Create and Manage Isolated Python Environments
A Python virtual environment is a concept in Python that lets you create isolated Python environments without affecting the global Python environment or other Python virtual environments. This is very useful, especially when you need to use multiple Python projects or applications, and they may require different versions of Python or packages.
Create a virtual environment
There are several ways to create a Python virtual environment, the most common of which is to use the venv module that comes with Python. Here are the steps to create a virtual environment using venv:
- Open a command line window (Windows) or terminal (Mac and Linux).
- Create a new directory to store your virtual environment, and change into that directory.
- Run the following command to create a virtual environment:
python -m venv myenv
where myenv is the name of the virtual environment you want to create.
Activate the virtual environment. On Windows, run the following command:
myenv\Scripts\activate
On Mac and Linux, run the following command:
source myenv/bin/activate
install package
Installing packages in a virtual environment works the same way as installing packages in the global Python environment. For example, run the following command to install the requests package:
pip install requests
run the application
When a virtual environment is active, running a Python application in a command line window or terminal will use the Python interpreter and packages in the virtual environment.
Exit the virtual environment
After finishing the work, you need to exit the virtual environment. On Windows, run the following command:
myenv\Scripts\deactivate
On Mac and Linux, run the following command:
deactivate
Using a Python virtual environment is a very useful tool that can help you manage and maintain Python projects and applications. Now you can try to create your own virtual environments and start using them.
If my article is helpful to you, please thank you three times.