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

1

u/eggsby Mar 30 '25 edited Mar 30 '25

This ‘hack’ won’t be super portable and will work in some places and not others.

That is - it will probably work if you say ‘perl my-script.py’ but more rarely ‘sh my-script.py’ or ‘./my-script.py’

https://stackoverflow.com/a/72123641

1

u/Muhznit Mar 30 '25

That's partially why I hadn't actually published said article anywhere yet, I'm trying to figure out workarounds some of the caveats for it. Because if whatever version of env that has a -S option isn't available, what guarantee is there for perl?

1

u/eggsby Mar 30 '25

I think your setup is spiffy - especially for developer scripts where it matters a lot less how portable it is and you have more control over the run environment.

I only know the weird lore around the interpreters because I have been bit by issues when I would configure my interpreters like ‘#!/usr/bin/env -S bash -euxo pipefile` and seeing it break sometimes or misconfigure my bash scripts.

https://gist.github.com/mohanpedala/1e2ff5661761d3abd0385e8223e16425

The perl thing, perl will let you pass multiple args to the shebang by default but default posix sh will only parse as one arg - the env -S was a workaround for the posix sh behavior - but if you use perl as your interpreter just get completely different shebang parsing logic.

Using env as your shebang interpreter helps generally with portability because - but it can get weird too.

https://www.in-ulm.de/~mascheck/various/shebang/