KatInterview

Bootstrapping a Reproducible Python Environment with Bash

StringsModel answer
MediumModel answerStringsbashshell-scriptingpython-venv

Last updated

Write and explain a Bash script that creates or reuses a Python virtual environment and installs dependencies, covering strict mode, idempotency, activation pitfalls, and resulting files.

You are setting up a Python project on a fresh Linux machine and want one command that prepares an isolated environment for it.

Write a short Bash script (or review one you are given) that does the following:

  • Creates a virtual environment in a directory chosen by the user, defaulting to .venv.
  • Lets the caller override which Python interpreter is used.
  • Upgrades pip inside the environment.
  • Installs the packages listed in requirements.txt, but only when that file exists.
  • Can be run several times without breaking anything.

Then answer the following:

  1. Walk through your script line by line. What does each command do, and why is it there?
  2. Why might a script be a better way of doing this than typing commands by hand, following a README, or using another tool? What are its limits?
  3. Suppose you make the script executable and run it from the project root. What files and directories should appear, and what will and will not change in your current terminal session?

Please be precise about the shebang line, exit-on-error behavior, file permission bits, and what source really does when used inside a script.

Hints

Hint 1

A script runs in a child process. Think about which changes to environment variables survive after that child exits, and how that affects activating a virtual environment.

Hint 2

You do not need to activate an environment to use it: the interpreter inside the environment's `bin` directory already knows where its own packages live.

Hint 3

For idempotency, decide what condition proves that the environment is usable (an existing directory is not enough), and consider what happens on a second run.

Hint 4

Consider strict-mode options such as `set -euo pipefail`, and note where `-e` does not take effect, such as inside `if` conditions.