Totally, some practical use of that here as well:
https://dpc.pw/posts/nix-users-you-can-start-using-rust-scri...
There are pip-run, pipx run, etc for Python-specific use-cases.
There's a 256byte limit for #! so this shouldn't work at all.
EDIT: Now I see its badly formatted, Either way, be careful with #! size limits.
Ah. I think two leading spaces fix this? I'll try:
#! /usr/bin/env nix-shell
#! nix-shell -i python3 -p python3Packages.pillow python3Packages.ansicolor
# scale image by 50%
import sys, PIL.Image, ansicolor
path = sys.argv[1]
image = PIL.Image.open(path)
factor = 0.5
image = image.resize((round(image.width \* factor), round(image.height \* factor)))
path = path + ".s50.jpg"
image.save(path)
print(ansicolor.green(f"done {path}"))I use nix-shell, and mostly I love it. But it’s important to be aware that the above means “Go get the latest(*) versions of python, pillow and ansicolor and run this code in an environment where they’re available.” It doesn’t do any version-pinning of your dependencies. That might be what you want, but maybe not: it’s frustrating when a script that worked yesterday won’t work today, or will only work after some big download.
My own rule of thumb is that nix-shell is great for quick one-offs and for sharing environments. For local tools and anything else I’m sharing with my future self, it’s usually better to write a nix expression and install it, which gives me access to Nix’s (excellent) rollback system, and lets me upgrade on my schedule, not upstream’s.
* - ‘Latest’ according to whatever Nix channel checkout currently applies. Which you can change, of course, but the point is it’s external to the script.
You can "pin" Nixpkgs with this style of invocation as well, see https://nixos.wiki/wiki/Nix-shell_shebang#Pinning_nixpkgs. But I agree that if you're writing a shell script (or small Python/Ruby scripts) that you'll be running often, it's better to package it (e.g. with writeShellScriptBin) and install to profile.
I documented how to do it with mise-en-place: https://mise.jdx.dev/tips-and-tricks.html#shebang
I'm pretty sure TFA is “intentional” too. Isn't this the whole point of shebang?
> #! /usr/bin/env nix-shell > #! nix-shell -i python3 -p python3Packages.pillow python3Packages.ansicolor > > # scale image by 50% > import sys, PIL.Image, ansicolor > path = sys.argv[1] > image = PIL.Image.open(path) > factor = 0.5 > image = image.resize((round(image.width * factor), round(image.height * factor))) > path = path + ".s50.jpg" > image.save(path) > print(ansicolor.green(f"done {path}"))
Just `chmod +x` and you have an executable with all dependencies you specify!
[0] https://nixos.wiki/wiki/Nix-shell_shebang