Pragmatism in the real world

Using uv as your shebang line

I create a fair few scripts in my ~/bin/ directory to automate tasks. Since discovering uv and inline script metadata, I’ve started using Python far more for these.

As ~/bin is on my path, I want to run the script by calling it directly on the command line. To do this, I use this shebang:

#!/usr/bin/env -S uv run --script

The command line will now run uv run --script and pass the file as the argument. uv ignores the shebang and then runs the rest of the file as a normal Python file.

Once I’ve ensured that that script has executable permissions via chmod a+x {filname}, I’m now good to go with simple command line scripts written in Python that automatically handle their dependencies!

2 thoughts on “Using uv as your shebang line

  1. This is indeed a cool feature. But it actually gets cooler!

    If your Python script has dependencies, you can declare them in a fenced code block in a leading comment and uv will parse and install those in a temp venv before invoking the script!

    For example:

    #!/usr/bin/env -S uv run --script
    # /// script
    # requires-python = ">=3.12"
    # dependencies = [
    # "ffmpeg-normalize",
    # ]
    # ///

    That’s not my example I just copied it from https://treyhunner.com/2024/12/lazy-self-installing-python-scripts-with-uv/ which you should definitely read to learn more.

Thoughts? Leave a reply

Your email address will not be published. Required fields are marked *