Practice: Virtual Environments

« Read the chapter

Q1. Create an environment

BeginnerCoding

Use the venv module to create an environment folder named env without pip, and print whether the file env/pyvenv.cfg exists.

Goal: Create an environment

Q2. Find the scripts folder

IntermediateCoding

After creating an environment named env, print True if it has a folder named bin or Scripts.

Goal: Know the environment layout

Q3. Detect an environment

BeginnerCoding

Write in_venv(prefix, base) that returns True when the two values differ. Print the results for ('/a', '/a') and ('/a/.venv', '/a').

Goal: Detect an environment

Q4. Activation command

IntermediateCoding

Write activate_cmd(os_name) that returns '.venv\\Scripts\\activate' for 'nt' and 'source .venv/bin/activate' otherwise. Print the result for 'nt' and for 'posix'.

Goal: Know activation commands

Q5. Write a requirements file

BeginnerCoding

Write the lines 'rich==13.7.0' and 'attrs==23.1.0' to requirements.txt, read the file back and print the number of lines.

Goal: Save requirements

Q6. System site packages

AdvancedCoding

Create an environment env with system_site_packages=True and no pip. Read pyvenv.cfg and print the line that starts with include-system-site-packages.

Goal: Read environment settings

Q7. Ignore the environment in Git

BeginnerCoding

Write a .gitignore file with the single line '.venv/' and print the file's text without the trailing newline.

Goal: Keep environments out of Git

Q8. Same prefixes

BeginnerOutput

What does this print?

Code
prefix = "/usr"
base_prefix = "/usr"
print(prefix != base_prefix)

Goal: Detect an environment

Q9. Environment folder name

IntermediateOutput

What does this print?

Code
from pathlib import Path

p = Path("project") / ".venv" / "bin"
print(p.parent.name == ".venv")
print(p.parent.name)

Goal: Read paths

Q10. Read a setting

IntermediateOutput

What does this print?

Code
text = "home = /usr/bin\ninclude-system-site-packages = false\n"
settings = {}
for line in text.splitlines():
    k, _, v = line.partition(" = ")
    settings[k] = v
print(settings["include-system-site-packages"])

Goal: Read environment settings

Q11. Python inside the environment

AdvancedOutput

What does this print?

Code
import os, subprocess, venv
from pathlib import Path

venv.create("env", with_pip=False)
sub = "Scripts" if os.name == "nt" else "bin"
exe = "python.exe" if os.name == "nt" else "python"
out = subprocess.run([str(Path("env") / sub / exe), "-c", "import sys; print(sys.prefix != sys.base_prefix)"], capture_output=True, text=True)
print(out.stdout.strip())

Goal: Use the environment interpreter

Q12. Where do packages go?

IntermediateOutput

What does this print?

Code
import os, subprocess, venv
from pathlib import Path

venv.create("env", with_pip=False)
sub = "Scripts" if os.name == "nt" else "bin"
exe = "python.exe" if os.name == "nt" else "python"
out = subprocess.run([str(Path("env") / sub / exe), "-c", "import sys; print(any('site-packages' in p for p in sys.path))"], capture_output=True, text=True)
print(out.stdout.strip())

Goal: Know the layout

Q13. Fix the activation step

IntermediateDebugging

A student creates .venv, then runs python -m pip install rich and finds rich installed globally, not in .venv. Fix the program that builds the command so it uses the environment's python.

Code
cmd = ["python", "-m", "pip", "install", "rich"]
print(cmd[0])

Goal: Use the right interpreter

Q14. Fix the requirements writer

BeginnerDebugging

This code should store three package names in requirements.txt, one per line, but the file has one long line. Fix it.

Code
import sys
sys.path.insert(0, ".")
from pathlib import Path
names = ["a", "b", "c"]
Path("requirements.txt").write_text(" ".join(names))

Goal: Save requirements

Q15. Why isolate projects?

BeginnerConceptual

Give two reasons to use a separate virtual environment for each project.

Goal: Explain isolation

Q16. What does activation change?

IntermediateConceptual

Explain in your own words what activating a virtual environment does and what deactivate does.

Goal: Explain activation

Q17. Move a project to a new computer

IntermediateApplication

You finished a project in .venv and must run it on a colleague's laptop. List the steps, and say why you should not copy .venv.

Goal: Rebuild an environment