2

In many python scripts do I read the shebang directive #!/usr/bin/env python I understand it tells which interpreter to use, like in a bash script: #!/bin/bash , but I fail to understand how the python interpreter is specified. If I simply run

$ /usr/bin/env 

I get a list of variable path such as SHELL=/bin/bash or JAVA_HOME==/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home.

The thing is there is no information about python when running this command. So I would like to better understand what does /usr/bin/env do exactly, and in which way #!/usr/bin/env python tells where my current python interpreter is.

3
  • Have you tried the man page yet? Commented Dec 17, 2015 at 11:04
  • The man page of what? man /usr/bin/env ? There is no entry. Commented Dec 17, 2015 at 11:08
  • That's because /usr/bin/env isn't a man page. man 1 env Commented Dec 17, 2015 at 11:09

1 Answer 1

5

Try running /usr/bin/env python and see what happens.

When given an argument, env runs the executable it finds.

BTW I also use it with bash scripts: /usr/bin/env bash because distros don't agree on its location (/bin/bash vs /usr/bin/bash)

See also: https://unix.stackexchange.com/questions/29608/why-is-it-better-to-use-usr-bin-env-name-instead-of-path-to-name-as-my

EDIT- extra explanations:

When given an argument, e.g. python, env behaves exactly as any shell would do when trying to find an executable: look at the PATH environment variable, split it at :, and for each directory, try to find an executable named python. The first matching executable is launched.

Typical content of the PATH variable: /bin:/usr/bin:/usr/local/bin

Sign up to request clarification or add additional context in comments.

4 Comments

yes running /usr/bin/env python runs the python interpreter. The thing is by running /usr/bin/env I get a list of path variables. I don't know why there are variables, and why the location of python interpreter is not among them.
/usr/bin/env shows your environment variables currently active in your shell. When pass python as an argument, it looks in your PATH and if there is an executable called python in an of the directories then it runs it.
Why is env useful or needed? The shell already does the job of using my PATH for finding the python executable .
@kristianp when specifying an interpreter on the first line of a script using the #! syntax, you have to pass a full path to an executable as the first thing that comes after the #!. The OS/kernel does not search PATH. So you cannot just write python in this case. You could write /usr/bin/python but this path will vary across systems, and I guess the idea is that /usr/bin/env is consistently present at that location.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.