Python wrapper in shebang

I have setup a Python environnement in nix that contains the several Python modules. The python executable is a wrapper around the python interpreter:

% less /Users/smaret/.nix-profile/bin/python
#! /nix/store/cblfnvb5rmhd2z231mqasn0brzh1hhv4-bash-4.4-p23/bin/bash -e
export PYTHONHOME='/nix/store/avqvqqqsrbrcpja4avvw9sfff2bfwm8c-python-2.7.15-env'
exec "/nix/store/s9mj8zzg7b0zj7s0k4rx3hdsiayr3ckn-python-2.7.15/bin/python" "${extraFlagsArray[@]}" "$@" 

I would like to use this wrapper in a script shebang to make sure that this Python environnement is used when running the script:

% cat
print("hello world")

However it seems that the shebang does not launch Python:

% ./
./ line 2: syntax error near unexpected token `"hello world"'
./ line 2: `print("hello world")'
% /Users/smaret/.nix-profile/bin/python 
hello world

Is there a way to make the wrapper work in a shebang?

This looks like the same thing described in this issue:

1 Like

Indeed, this is the same problem. A workaround (suggested in the issue) is to prefix the wrapper in the sheband with !/usr/bin/env:

% cat
#!/usr/bin/env /Users/smaret/.nix-profile/bin/python
print("hello world")
% ./ 
hello world

Here, a stripped-down version works (on NixOS):

$ cat /home/user/python
exec "/nix/store/2k3108vcfni2ba5asf6yk4iz18v5q7lc-python-2.7.15/bin/python" "${extraFlagsArray[@]}" "$@"

$ cat 
print("hello world")

$ ./ 
hello world

But note that your wrapper may break when you upgrade your packages. I would recommend to create a Nix-package – either for your program or for your wrapper.
You may also be interested in using nix-shell as shebang: Introduction