Creating a Virtual Environment or Virtual Environment is one of the best ways to manage Python projects. Simply put, a virtual environment allows you to manage dependencies for your projects in isolation, which means that different projects will have less interaction with each other. Suppose you are working on two projects that each require different versions of a library; in this case, using a virtual environment would be a suitable solution.
To create a virtual environment in Python, you first need to ensure that Python and the required packages for creating a virtual environment, namely venv
, are installed. The venv
module is provided by default with newer versions of Python. To get started, create a new directory and navigate to it. Then, execute the following command:
python -m venv myenv
By running this command, a new directory called myenv
will be created which includes all the libraries required to run your project.
Now that you have created your virtual environment, you need to activate it to use it. To activate it in Windows, execute the following command:
myenv\Scripts\activate
And on Unix or MacOS systems, use the following command:
source myenv/bin/activate
After activation, the name of the virtual environment must be shown before your command prompt in the terminal. This indicates that any libraries you install will only be added to this virtual environment.
For example, if you want to install the requests
library:
pip install requests
Keep in mind that to exit the virtual environment, simply enter the command deactivate
in the terminal.
Step by Step Explanation:
python -m venv myenv
→ A virtual environment named myenv
is created.myenv\Scripts\activate
→ On Windows, activates the virtual environment.source myenv/bin/activate
→ On Unix or Mac, activates the virtual environment.pip install requests
→ Installs the requests
library in the virtual environment.deactivate
→ Deactivates the virtual environment and returns to the original system environment.