1

I'm sure this is well documented somewhere, but I can't find it! I want to make my scripts portable to machines that may not have their Python interpreters in the same location. For that reason, I thought that I could just code the first line as #!python3 rather than with the absolute path to the interpreter, like #!/usr/local/bin/python3.

No doubt most of you understand why this doesn't work, but I have no idea. Although my lab mates aren't complaining about having to recode my scripts to reflect the absolute path to the interpreter on their own machines, this seems like it shouldn't be necessary. I'd be perfectly happy with a response providing a link to the appropriate documentation. Thanks in advance.

Gregory
  • 3,390
  • 7
  • 25
  • 41
  • Related (but not duplicate; my google-fu is failing here; I'm sure I've seen this question on SO before...): http://stackoverflow.com/questions/2429511/why-do-people-write-usr-bin-env-python-on-the-first-line-of-a-python-script – Wooble Jul 26 '12 at 17:11

2 Answers2

3

The path given after #! in the shebang line is an absolute path, so simply python3 does not work. You should use

#!/usr/bin/env python3

to look up python3 in the PATH on a POSIX machine. Of course this will only find the Python interpreter if it is in some directory given in the PATH environment variable.

Sven Marnach
  • 483,142
  • 107
  • 864
  • 776
2

env is a program that handles these sort of things. You should pretty much always use something like #! /usr/bin/env python3 as your shebang line rather than specifying an absolute path.

Julian
  • 3,207
  • 13
  • 25
  • Answer credit went to the first post, but I really appreciate the added information about `env` and knowing that this is a proper way to handle the shebang line. – Gregory Jul 26 '12 at 17:38
  • Seems like by using `#! /usr/bin/env` you're just using one absolute path instead of another as well as adding a dependency to another application. – martineau Jul 26 '12 at 17:45
  • True. This is mitigated by the fact that `/usr/bin/env` is generally found there, at least more often than whatever else you're running, and the fact that it's generally included OOTB in whatever *nix you're going to find. – Julian Jul 26 '12 at 17:46