68

I'm usually using the following shebang declaration in my Python scripts:

#!/usr/bin/python

Recently, I've came across this shebang declaration:

#!/usr/bin/env python

In the script documentation, it was noted that using this form is "more portable".

What does this declaration mean? How come there's a space in the middle of the path? Does it actually contribute to protability?

Adam Matan
  • 128,757
  • 147
  • 397
  • 562
  • 6
    possible duplicate of [What's the difference between these two python shebangs](http://stackoverflow.com/questions/5709616/whats-the-difference-between-these-two-python-shebangs) – unutbu Jul 25 '13 at 01:08
  • possible duplicate of [Why do people write #!/usr/bin/env python on the first line of a Python script?](http://stackoverflow.com/questions/2429511/why-do-people-write-usr-bin-env-python-on-the-first-line-of-a-python-script) – nbro Jul 05 '15 at 02:22
  • Possible duplicate of [Should I put #! (shebang) in Python scripts, and what form should it take?](http://stackoverflow.com/questions/6908143/should-i-put-shebang-in-python-scripts-and-what-form-should-it-take) – Tor Klingberg Oct 08 '15 at 14:55

1 Answers1

90
#!/usr/bin/env python

is more portable because in general the program /usr/bin/env can be used to "activate" the desired command without full path.

Otherwise, you would have to specify the full path of the Python interpreter, which can vary.

So no matter if the Python interpreter was in /usr/bin/python or in /usr/local/bin/python or in your home directory, using #!/usr/bin/env python will work.

jh314
  • 27,144
  • 16
  • 62
  • 82
  • Great, thanks. Do you know does env work? does it run a full filesystem search, or relies on some path file? – Adam Matan Jul 25 '13 at 00:50
  • 5
    @AdamMatan env uses the `PATH` variable in the environment by looking at each directory in it for a binary of the given name (python, in this case). If it finds it, it executes the program. This decouples the finding of the program from the execution, and since `env` is available on many systems in the standard location of `/usr/bin`, it is more portable. Better standardization leads to better portability. – Colonel Panic Jul 25 '13 at 01:43
  • 7
    If your script is Python 3 only and your target system might have a Python 2 executable in PATH then I recommend `#!/usr/bin/env python3` instead. – dadaist Apr 01 '20 at 08:11