Worksheet 6 - Virtual Environments

From Sensors in Schools
Jump to navigation Jump to search

Set up Virtual Environment for Python

Here are some fun learning activities for students to engage with virtual environments (env) on a Raspberry Pi. These tasks encourage exploration of Python virtual environments and command-line tools while incorporating challenges to solidify their understanding:

Setting up Python programs in a virtual environment is a good practice, especially when working with Mosquitto and MQTT libraries like paho-mqtt. It ensures that your project dependencies remain isolated and don't conflict with other projects or system-wide packages.

Why Use a Virtual Environment?

  • Isolation: Keeps dependencies specific to your project and avoids conflicts with system-wide packages.
  • Control: You can install and manage different versions of libraries for different projects.
  • Portability: Makes it easier to share your project with others without worrying about dependency issues.

Task: Create a Virtual Environment

Challenge: Instruct students to create a virtual environment named myenv using Python's venv module.

python3 -m venv myenv

Extra Challenge: Verify the folder structure created by the environment and explain its purpose (e.g., bin, lib, etc.).

  • bin: This directory contains the Python binary for the virtual environment, along with executables like pip (pip installs python) and activate (for activating the environment). When you activate the environment, the bin directory is added to your shell's PATH, ensuring that the Python interpreter and other tools from this environment are used instead of the global versions.
  • lib: This folder contains all the packages you install while inside the virtual environment, organized by Python version.

Task: Activating and Deactivating the Virtual Environment

Challenge: Have students activate the virtual environment, run a basic Python script, and then deactivate it.

source myenv/bin/activate
deactivate

Extra Challenge: Try running Python code inside and outside the virtual environment and note any differences.

Task: Install Packages Inside the Virtual Environment

Challenge: Students install a package (like requests) inside the virtual environment and confirm it is only available there.

pip install requests

Extra Challenge: After deactivating, try importing the requests library globally (without the virtual environment) and explain what happens. To run python in the Terminal enter python or python3

python3

Then you can import requests.

import requests

Task: Freeze Dependencies

Challenge: After installing a few packages (like requests, numpy, matplotlib) using pip install <package_name>, students generate a requirements.txt file to capture the environment dependencies.

pip freeze > requirements.txt

Extra Challenge: Ask students to inspect the contents of requirements.txt and try to explain what each line represents.

Task: Recreate an Environment Using requirements.txt

Challenge: Students create a new virtual environment and install the dependencies from requirements.txt.

python3 -m venv newenv
source newenv/bin/activate
pip install -r requirements.txt

Extra Challenge: Explain why recreating environments like this is important for collaborative projects.


Task: List Installed Packages

Challenge: Students list all installed packages within the virtual environment.

pip list

Extra Challenge: Compare the packages installed in the virtual environment with those in the global Python environment.


Task: Delete the Virtual Environment

Challenge: Students deactivate and delete the virtual environment.

deactivate
rm -rf myenv


  • -r (recursive): This option tells the command to delete directories and their contents recursively. Without this, the rm command would not delete directories, only individual files.
  • -f (force): This option forces the command to ignore non-existent files and suppresses any prompts. It ensures that the command doesn’t ask for confirmation before deleting files or directories, even if they are write-protected.
  • man rm to find out more.

Task: Create a Virtual Environment with a Specific Python Version

Challenge: Create a virtual environment using Python 3.7 instead of the default Python version.

python3.7 -m venv myenv37

Extra Challenge: Run Python inside this environment and confirm the version using python --version.

python
python --version

Task: Isolating Different Projects with Separate Virtual Environments

Challenge: Set up two virtual environments for different projects (env_project1 and env_project2). Install different libraries in each and ensure that they don’t conflict.

python3 -m venv env_project1
python3 -m venv env_project2
source env_project1/bin/activate
pip install numpy
deactivate
source env_project2/bin/activate
pip install flask
deactivate

Extra Challenge: Write a script for each project and test them to ensure the environments are working independently.

Flask Example: A Simple Web Application

Flask is a lightweight web framework for building web applications. Here's a basic script that creates a simple web server that returns "Hello, World!" when accessed.

# Import the Flask library
from flask import Flask

# Create a new Flask application
app = Flask(__name__)

# Define a route (URL) for the web app
@app.route('/')
def hello_world():
    return 'Hello, World!'

# Run the application on localhost (127.0.0.1) and port 5000
if __name__ == '__main__':
    app.run(debug=True)

To run this Flask app:

Save two copies of the script as app.py in each of the virtual environments. Activate each virtual environment and run app.py in the terminal:

python app.py

Open a web browser and go to http://127.0.0.1:5000/