"python myscript" ignores "#!/usr/bin/env pythonX" where pythonX doesn't exist
Question: **Why doesn't`test.py` throw error `env: python3: No such file or directory`
when Python 3 is not installed?**

My system (Mac OS X) has Python 2.7 installed, but not Python 3:

    
    
    $ /usr/bin/env python -V
    Python 2.7.12
    $ /usr/bin/env python3 -V
    env: python3: No such file or directory
    

File **test.py:**

    
    
    #!/usr/bin/env python3
    import sys
    print sys.executable
    

Executing **test.py:**

    
    
    $ python test.py
    /usr/local/opt/python/bin/python2.7
    

I thought that since Python 3 does not exist on my system, having the shebang
line `#!/usr/bin/env python3` will throw an error and terminate the script.
But `env` actually selected the Python 2.7 interpreter.


Answer: The shebang is interpreted by OS when it tries to execute the script. Whey you
type `python test.py`, the OS executes `python` and `python` executes the
script (and `python` is found based on the current `PATH`) as opposed to being
processed by the OS.

If you make the script executable (`chmod +x test.py`) and then try to execute
it directly (e.g. `./test.py`), the OS will be responsible for running the
script so it will look at the shebang to figure out what program is
responsible to run the script. In this case, it is `/usr/bin/env` which will
look for `python3` and try to use that. Since `python3` isn't there (or not
findable on your `PATH`) you'll see the error.

