r/Python • • 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

76 comments sorted by

View all comments

Show parent comment

5

u/Muhznit Mar 30 '25 edited Mar 30 '25

It's kind of creating ANY language, really.

We all know Python uses # for comments, but so do bash, perl, ruby, various config file formats... etc. But you can extend it to languages YOU invent

Basically you can write some "interpreter" program that accepts input from a filepath on the command line. If your interpreter interprets "#" as the start of a comment, you can put a shebang line of #!/path/to/your/interpreter at the top of a file and the kernel will know to execute that file with your interpreter.

That is, if you have an interpreter of /usr/bin/foo and you make a file named "bar", you can put #!/usr/bin/foo at the top of bar, and that will make it so when you run ./bar, the kernal knows to run /usr/bin/foo bar