Creating and Using Virtual Environments (venv) in Python¶
In this notebook, we will cover how to create a virtual environment, activate it, and install dependencies within the environment.
Step 1: Check if venv
is installed¶
Before creating a virtual environment, let’s ensure that the venv
module is available. It is included with Python 3.3+ by default.
In [ ]:!python3 -m venv –help
Step 2: Create a virtual environment¶
To create a virtual environment, you can use the venv
module that comes with Python. It will create a new folder containing the virtual environment files.
In [ ]:!python3 -m venv myenv
Here, myenv
is the name of the virtual environment folder. You can choose any name you like.
Step 3: Activate the virtual environment¶
Once the virtual environment is created, you need to activate it. The command to activate the virtual environment is different depending on your operating system.
-
- For Linux/MacOS:
source myenv/bin/activate
-
- For Windows:
myenv\Scripts\activate
After activation, you will notice that the terminal prompt changes, showing the name of the environment (e.g., (myenv)
), indicating that the environment is active.
Step 4: Install dependencies within the virtual environment¶
While the virtual environment is activated, you can install any Python packages, and they will be installed only within that environment. For example, you can install numpy
:
In [ ]:!pip install numpy
Step 5: Deactivate the virtual environment¶
When you’re done working with the virtual environment, you can deactivate it by simply running the deactivate
command:
In [ ]:!deactivate
This will return you to the global Python environment.
Step 6: Delete the virtual environment¶
To delete the virtual environment, simply remove the folder created for it. For example, to remove myenv
, you can use the following command:
-
- Linux/MacOS:
rm -rf myenv
- Linux/MacOS:
-
- Windows:
rmdir /s myenv
- Windows:
GIPHY App Key not set. Please check settings