Practice: Virtual Environments
Q1. Create an environment
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
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
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
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
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
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
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
What does this print?
prefix = "/usr"
base_prefix = "/usr"
print(prefix != base_prefix)Goal: Detect an environment
Q9. Environment folder name
What does this print?
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
What does this print?
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
What does this print?
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?
What does this print?
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
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.
cmd = ["python", "-m", "pip", "install", "rich"]
print(cmd[0])Goal: Use the right interpreter
Q14. Fix the requirements writer
This code should store three package names in requirements.txt, one per line, but the file has one long line. Fix it.
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?
Give two reasons to use a separate virtual environment for each project.
Goal: Explain isolation
Q16. What does activation change?
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
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