uv for setting up virtual environments


the python world is abuzz with the wonders of uv. I find it quite clunky - I’m starting to look into it for the speed which is indeed awesome but this was incredibly unintuitive.

I had:

python3 -mvenv env
env/bin/pip install --no-cache-dir --upgrade -r requirements.txt

My first try to uv-ize this was

uv venv env
uv pip install --prefix env --no-cache-dir --upgrade -r requirements.txt

This breaks because stuff installed in the venv refers to the system Python interpreter /usr/bin/python3.12 and not the one installed in the venv.

WHY??? Why doesn’t it use env python?

Turns out one should not use --prefix as the docs state

prefer the use of –python to install into an alternate environment, as scripts and other artifacts installed via –prefix will reference the installing interpreter

Now you tell me. OK, how to make uv pip refer to the venv I created in env? uv pip install --python 3.12 --prefix env, right?

WRONG! This still doesn’t properly rewrite the shebang in executables in the virtualenv.

The docs do say uv will work on the environment pointed to by VIRTUAL_ENV if specified, so it turns out the arcane invocation to do what I needed was:

uv venv env --python 3.12
VIRTUAL_ENV=env uv pip install --no-cache-dir --upgrade -r requirements.txt

This works and if one squints a bit, all this info is in the documentation but it’s very undiscoverable and the breadcrumbs will lead you to all sorts of different places. I ended up cobbling the above together by also looking at this blog article from saaspegasus.

Just for kicks, let’s see what an AI would say here.

hi chatgpt. I have these commands to set up a virtual environment and install some dependencies:

python3 -mvenv env env/bin/pip install –no-cache-dir –upgrade -r requirements.txt

How can I use the uv utility to create my virtual environment in the env directory and install dependencies listed in requirements.txt? I want uv equivalents of the above two commands please.

The response: (spoiler: it’s wrong):

the equivalent uv commands for your original commands would be:

uv env create –path env uv pip install –no-cache-dir –upgrade -r requirements.txt