Learning Notes #80 β Running Python Scripts as a Standalone Tool with UV
Managing dependencies for small Python scripts has always been a bit of a hassle.
Traditionally, we either install packages globally (not recommended) or create a virtual environment, activate it, and install dependencies manually.
But what if we could run Python scripts like standalone binaries ?
Introducing PEP 723 β Inline Script Metadata
PEP 723 (https://peps.python.org/pep-0723/) introduces a new way to specify dependencies directly within a script, making it easier to execute standalone scripts without dealing with external dependency files.
This is particularly useful for quick automation scripts or one-off tasks.
Consider a script that interacts with an API requiring a specific package,
# /// script # requires-python = ">=3.11" # dependencies = [ # "requests", # ] # /// import requests response = requests.get("https://api.example.com/data") print(response.json())
Here, instead of manually creating a requirements.txt
or setting up a virtual environment, the dependencies are defined inline. When using uv
, it automatically installs the required packages and runs the script just like a binary.
Running the Script as a Third-Party Tool
With uv
, executing the script feels like running a compiled binary,
$ uv run fetch-data.py Reading inline script metadata from: fetch-data.py Installed dependencies in milliseconds
ehind the scenes, uv
creates an isolated environment, ensuring a clean dependency setup without affecting the global Python environment. This allows Python scripts to function as independent tools without any manual dependency management.
Why This Matters
This approach makes Python an even more attractive choice for quick automation tasks, replacing the need for complex setups. It allows scripts to be shared and executed effortlessly, much like compiled executables in other programming environments.
By leveraging uv
, we can streamline our workflow and use Python scripts as powerful, self-contained tools without the usual dependency headaches.