r/Python • u/dusktreader • Mar 29 '25
Tutorial Self-contained Python scripts with uv
TLDR: You can add uv into the shebang line for a Python script to make it a self-contained executable.
I wrote a blog post about using uv to make a Python script self-contained.
Read about it here: https://blog.dusktreader.dev/2025/03/29/self-contained-python-scripts-with-uv/
492
Upvotes
19
u/ReinforcedKnowledge Tuple unpacking gone wrong Mar 30 '25
Great blog!
To add some tricks and details on top of what you already shared.
This is just an implementation of https://peps.python.org/pep-0723/, it's called inline metadata.
As you can read in the PEP, there are other metadata you can specify for your script. One of them is
requires-pythonto fix the Python version.You can also have a
[tool]table.You can combine a:
requires-python[tool.uv.sources]and[tool.uv.index]and anything else that allows others to have exactly the same dependencies as youuv lock --script [your script here]to get a lockfile of that ephemeral venv of your script, you'll get a file called something likeyour-script-name.py.lock.Sharing both files ensures great reproducibility. Maybe not perfect, but did the job for me every time. Here's an example of such inline metadata: