Christopher Tyler

Self-Contained Python Scripts with uv

I saw this from Tucker’s and Dave’s articles. Basically you can create a Python script, include what are the required dependencies and using uv, be able to run the script and get the dependencies all in one go.

To add a dependency to a script you can do the following:

1
> uv add --script your_script.py httpx

This will include httpx as a dependency:

1
2
3
4
5
6
7
8
9
# /// script
# requires-python = ">=3.13"
# dependencies = [
#     "httpx",
# ]
# ///

import argparse
import asyncio

To run this script:

1
> uv run your_script.py

Also if you put the following on the first line in the script:

1
2
#!/usr/bin/env python
...

or

1
2
#!/usr/bin/env -S uv run --script
...

Now the script can be executable (chmod +x your_script.py). Note won’t work in PowerShell but should work in Unix-like systems. However this could work with the py launcher if you do the following:

1
2
#!/usr/bin/env -S uv run --script
...

<< Previous Post

|

Next Post >>

#Uv #Python #Tucker Beck #Dave Johnson