4 ms·
uv has a feature where you can put a magic comment at the top of a script and it will pull all the dependencies into its central store when you do “uv run …”. A
by easton 1y ago
uv has a feature where you can put a magic comment at the top of a script and it will pull all the dependencies into its central store when you do “uv run …”. And then it makes a special venv too I think? That part’s cloudier.
https://docs.astral.sh/uv/guides/scripts/ https://docs.astral.sh/uv/guides/scripts/
Makes it a snap to have a one file python script without having to explicitly pip install requests or whatever into a venv.
- wonger_ 1y agoExample usage for those who haven't seen it yet: #!/usr/bin/env -S uv run --script # # /// script # requires-python = ">=3.12" # dependencies = ["httpx"] # /// import httpx print(httpx.get("https://example.com"))
- dotancohen 1y agoThat is amazing! I might use this instead of bash for some scripts. I could imagine a Python wrapper script that parses the Python for import statements, then prepends these comments and passes it off to uv. Basically automating the process.
- Elucalidavah 1y ago> dependencies = ["httpx"] I heavily recommend writing a known working version in there, i.e. `"httpx~=0.27.2"`, which, in the best case, would allow fixes and security patches (e.g. when httpx 0.27.3 releases), and, in the worst case, would let you change to `~=` to `==` in case httpx manages to break the backwards compatibility with a patch release. And, of course, always use `if __name__ == "__main__":`, so that you can e.g. run an import check and doctests and stuff in it.
- dotancohen 1y agoImport checks and doctests you can run before any script code anyway, and exit() if needed. The advantage of `if __name__ == "__main__":`, is that you can import the script as module on other code, as in that case __name__ will not be __main__.