Python VirtualEnv


Virtual Environment in Python is a self-contained directory that contains a Python installation for a specific project. It keeps dependencies isolated from your global Python setup.


🔹 Why Use a Virtual Environment?

  • Prevents dependency conflicts between projects

  • Keeps your project environment clean and manageable

  • Lets you use different versions of packages for different projects


🔹 Create a Virtual Environment

Use the built-in venv module:

python -m venv myenv

✅ This will create a folder named myenv with the virtual environment inside it.


🔹 Activate the Virtual Environment

On Windows:
myenv\Scripts\activate
On macOS/Linux:
source myenv/bin/activate

✅ Once activated, your terminal will show the environment name like:
(myenv) C:\Users\...>


🔹 Install Packages Inside VirtualEnv

Now that you're inside the virtual environment, use pip as usual:

pip install flask

The installed packages stay isolated from your system Python.


🔹 Deactivate the Virtual Environment

When you're done:

deactivate

✅ You’ll exit the virtual environment and return to your global Python path.


🔹 Delete a Virtual Environment

Just delete the folder:

rm -r myenv

🔹 Check Installed Packages in VirtualEnv

pip list

You’ll only see packages installed within that environment.


Practice Questions

Q1. Write a Python command to create a virtual environment called projectenv.

Q2. Write a command to activate the virtual environment on Windows.

Q3. Write a command to install the django package inside the virtual environment.

Q4. Write a command to list all installed packages inside the virtual environment.

Q5. Write a command to deactivate the virtual environment.

Q6. Write a command to create a requirements.txt file using pip freeze.

Q7. Write a command to install dependencies from requirements.txt inside a virtual environment.

Q8. Write a command to delete a virtual environment folder named projectenv.

Q9. Write a short explanation or command to use a virtual environment to avoid package conflicts.

Q10. Write steps to use different versions of the same package in two separate virtual environments.


Go Back Top