
A virtual environment in Python is an isolated environment on your computer, where you can run and test your Python projects. It allows you to manage project-specific dependencies without interfering with other projects or the original Python installation.
Think of a virtual environment as a separate container for each Python project. Each container:
Using virtual environments is important because:
Python has the built-in venv module for creating virtual environments. To create a virtual environment on your computer, open the command prompt, and navigate to the folder where you want to create your project, then type this command:
Run this command to create a virtual environment named myfirstproject:
python -m venv myfirstprojectThis will set up a virtual environment, and create a folder named "myfirstproject" with subfolders and files, like this:
myfirstproject
Include
Lib
Scripts
.gitignore
pyvenv.cfgTo use the virtual environment, you have to activate it with this command:
Activate the virtual environment:
myfirstproject\Scripts\activateAfter activation, your prompt will change to show that you are now working in the active environment:
(myfirstproject) C:\Users\Your Name>Once your virtual environment is activated, you can install packages in it, using pip. We will install a package called 'cowsay':
Install 'cowsay' in the virtual environment:
pip install cowsay'cowsay' is installed only in the virtual environment:
Collecting cowsay
Downloading cowsay-6.1-py3-none-any.whl.metadata (5.6 kB)
Downloading cowsay-6.1-py3-none-any.whl (25 kB)
Installing collected packages: cowsay
Successfully installed cowsay-6.1Now that the 'cowsay' module is installed in your virtual environment, let's use it to display a talking cow. Create a file called test.py on your computer. You can place it wherever you want, but I will place it in the same location as the myfirstproject folder - not in the folder, but in the same location. Open the file and insert these three lines in it:
Insert two lines in test.py:
import cowsay
cowsay.cow("Hello World")