73

I used to use the shebang

#!/usr/bin/env python

When is it better to use

#!/usr/bin/python

What is the exact difference between them?

smci
  • 32,567
  • 20
  • 113
  • 146
Ken
  • 3,922
  • 9
  • 39
  • 40
  • Did you try `man env` to see what the `env` app does? – S.Lott Apr 18 '11 at 22:51
  • 7
    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) – dnozay Oct 10 '13 at 18:54
  • 1
    @S.Lott I assumed `env` was a directory, not an executable. – ArtOfWarfare May 18 '17 at 20:35
  • 1
    Possible duplicate of [Should I put #! (shebang) in Python scripts, and what form should it take?](https://stackoverflow.com/questions/6908143/should-i-put-shebang-in-python-scripts-and-what-form-should-it-take) – codeaviator Sep 22 '17 at 02:04

1 Answers1

95

#!/usr/bin/python is hardcoded to always run /usr/bin/python, while #!/usr/bin/env python will run whichever python would be default in your current environment (it will take in account for example $PATH, you can check which python interpreter will be used with which python).

The second way ( #!/usr/bin/env python ) is preferred , as it's not dependent on particular installation. It will work for example with virtualenv setups or systems where there is no /usr/bin/python, but only e.g. /usr/local/bin/python.

manojlds
  • 290,304
  • 63
  • 469
  • 417
vartec
  • 131,205
  • 36
  • 218
  • 244
  • 5
    This. See [Why do people write #!/usr/bin/env python on the first line of a Python script?](http://stackoverflow.com/q/2429511/668807) and [this message on the Python mailing list](http://mail.python.org/pipermail/tutor/2007-June/054828.html). – Blair Apr 18 '11 at 22:35
  • 1
    Indirection via `env` also works when `/usr/bin/python` exists, but isn't an actual executable (e.g. it may be a launch script) – ncoghlan Apr 19 '11 at 06:20
  • 2
    does that imply that it is better to use `#!/usr/bin/env perl` will be more versatile than the usual shebang `#!/bin/perl`? It seems to me that people usually use `#!/bin/perl` in perl, but `#!/usr/bin/env python` for python. Why? – Ken Apr 20 '11 at 01:26
  • 1
    @Ken, no principled reason, just accidents of history. – dubiousjim Apr 19 '12 at 15:23
  • 1
    @Ken: AFAIK, there isn't popular equivalent of virtualenv for Perl. – vartec Apr 19 '12 at 15:26