Running a `nix-shell` shebang script inside a derivation

I’m trying to run a nix-shell script inside a derivation like this:

postPatch = ''
  ${./python-script.py}
'';

python-script.py:

#!/usr/bin/env nix-shell
#!nix-shell -i python3 -p python3

print("hello world")

But I’m getting a cannot execute: required file not found error, when building the derivation. The script runs just fine outside of the derivation.

What’s the right way to do this?

This wouldn’t work because /usr/bin/env is not available in the sandbox, and even if it (and nix-shell) does, you would need internet access and store access, which isn’t available easily.

Instead, you can omit the shebang and do something like this

postPatch = ''
  ${python3.interpreter} ${./python-script.py}
''

and if you need some python dependencies

postPatch = ''
  ${(python3.withPackages (p: [ p.tomli-w ])).interpreter} ${./python-script.py}
''

You can also just add python3 to nativeBuildInputs and use python3 instead of ${python3.interpreter}