Question: I have a pip requirements file that changes during development.

Can `pip` be made to **uninstall** packages that do not appear in the requirements file as well as installing those that do appear? Is there a standard method?

This would allow the pip requirements file to be the canonical list of packages - an 'if and only if' approach.

**Update**: I suggested it as a new feature at <https://github.com/pypa/pip/issues/716>

Answer: 
This should uninstall anything not in requirements.txt:

```
pip freeze | grep -v -f requirements.txt - | grep -v '^#' | xargs pip uninstall -y

```

Although this won't work quite right with packages installed with `-e`, i.e. from a git repository or similar. To skip those, just filter out packages starting with the `-e` flag:

```
pip freeze | grep -v -f requirements.txt - | grep -v '^#' | grep -v '^-e ' | xargs pip uninstall -y

```

Then, obviously:

```
pip install -r requirements.txt

```

**Update for 2016:**
You probably don't really want to actually use the above approach, though. [Check out `pip-tools` and `pip-sync`](http://nvie.com/posts/better-package-management/#virtue-2-have-your-envs-reflect-your-specs) which accomplish what you are probably looking to do in a much more robust way.

<https://github.com/nvie/pip-tools>

**Update for May, 2016:**

You can now also use `pip uninstall -r requirements.txt`, however this accomplishes basically the opposite - it uninstalls everything in `requirements.txt`

**Update for May, 2019:**

Check out [pipenv](https://pipenv.pypa.io/en/latest/) or [Poetry](https://python-poetry.org/). A lot has happened in the world of package management that makes this sort of question a bit obsolete. I'm actually still quite happily using pip-tools, though.
This is an old question (but a good one), and things have changed substantially since it was asked.

There's an offhand reference to `pip-sync` in another answer, but deserves its own answer, because it solves precisely the OP's problem.

[pip-sync](https://github.com/jazzband/pip-tools#example-usage-for-pip-sync) takes a `requirements.txt` file as input, and "trues up" your current Python environment so that it matches *exactly* what's in that `requirements.txt`. This includes *removing* any packages that are present in your env but absent from `requirements.txt`.

Example: Suppose we want our env to contain (only) 3 libraries: `libA`, `libB`, and `libC`, like so:

```
> cat requirements.txt
libA==1.0
libB==1.1
libC==1.2

```

But our env currently contains `libC` and `libD`:

```
> pip freeze
libC==1.2
libD==1.3

```

Running pip-sync will result in this, which was our desired final state:

```
> pip-sync requirements.txt
> pip freeze
libA==1.0
libB==1.1
libC==1.2

```