How to create virtual env with Python 3?
How do you set up a virtual environment in Python 3 to manage project-specific dependencies? What commands can you use to create and activate it across different operating systems?
Creating a virtual environment in Python 3 is a best practice because it allows you to manage project-specific dependencies without affecting your system-wide Python installation. This is especially helpful when working on multiple projects that may require different versions of the same package.
Here’s how you can create and use a virtual environment in Python 3:
Step 1: Check Python Installation
Make sure Python 3 is installed by running:
python3 --version
Step 2: Create a Virtual Environment
Use the built-in venv module:
python3 -m venv myenv
Here, myenv is the name of your virtual environment folder. You can choose any name you like.
Step 3: Activate the Virtual Environment
On Linux/MacOS:
source myenv/bin/activate
On Windows (Command Prompt):
myenvScriptsctivate
Once activated, you’ll notice the environment name (e.g., (myenv)) appear in your terminal prompt.
Step 4: Install Packages
With the environment active, you can install dependencies locally using pip:
pip install requests
Step 5: Deactivate When Done
To leave the virtual environment, simply run:
deactivate
In short, creating a virtual environment in Python 3 is simple and ensures clean, isolated workspaces for each project. This avoids version conflicts and keeps your global Python installation clean.