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'
export PYTHONNOUSERSITE='true'
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 test.py
#!/Users/smaret/.nix-profile/bin/python
print("hello world")

However it seems that the shebang does not launch Python:

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

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

This looks like the same thing described in this issue:

https://github.com/NixOS/nixpkgs/issues/11133

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 test.py
#!/usr/bin/env /Users/smaret/.nix-profile/bin/python
print("hello world")
% ./test.py 
hello world

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

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

$ cat test.py 
#!/home/user/python
print("hello world")

$ ./test.py 
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 - Nix Reference Manual