3

What is the difference between these two lines?

#!/usr/bin/python

#!/usr/bin/env python

Hans-Helge
  • 1,764
  • 3
  • 14
  • 21

1 Answers1

1

This has nothing to do per se with Python, more to do with the way shebang lines work.

In many UNIX-like systems, you are required to give absolute path names on the shebang line, such as /usr/bin/python.

But what happens when you move that script to a different machine that has Pyyhon in the /usr/local/bin directory? It won't work, that's what. Or, even if you just want to use a different Python interpreter in $HOME/python/bin for testing purposes, you need to change the shebang line.

env is a way to get around that. Since it's generally always in /usr/bin, you can safely include it in the shebang line as an absolute path.

The env command itself in this case searches the path for python and runs that executable file.

The env command actually can do more than that, it can print the environment (env) or it can modify it temporarily for a specific process (env xyzzy=plugh myprog) but, in this particular case, it's simply giving you the power to run Python out of your path rather than at a fixed location.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • So i.e. it is good practice to write `#!/usr/bin/env python` because I can be sure my script runs on any machine (as long as python is installed)? – Hans-Helge Apr 29 '13 at 01:11
  • @Hans, yes, it's a good idea. Of course there may be situations where you _want_ a specific path, such as where you app ships with its own Python in `/usr/local/paxprog/tools/python/bin` but, generally, you just want to run with whatever Python the user has (and inform them of necessary requirements, such as "you need Python 2.7"). – paxdiablo Apr 29 '13 at 01:18
  • 2
    There's a downside to using #!/usr/bin/env python: It makes your script show up in "top" as "python" instead of the name of the script. If you get 10 different python scripts all running and pegging your CPU, that can be a problem, because you can't tell them apart as easily. – dstromberg Apr 29 '13 at 01:23