This works really well in my experience, but it does mean you need to have a working internet connection the first time you run the script.
# /// script
# dependencies = [
# "cowsay",
# ]
# ///
import cowsay
cowsay.cow("Hello World")
Then: uv run cowscript.py
It manages a disposable hidden virtual environment automatically, via a very fast symlink-based caching mechanism.You can also add a shebang line so you can execute it directly:
#!/usr/bin/env -S uv run --script
#
# /// script
# dependencies = ["cowsay"]
# ///
import cowsay
cowsay.cow("Hello World")
Then: chmod 755 cowscript
./cowscriptI wish env -S was more portable. It's a newer feature of the coreutils env implementation and isn't supported elsewhere afaik.
If not having a working internet connection is a concern, I would package your script into a shiv zipapp - https://shiv.readthedocs.io/en/latest/