“python myscript” ignores “#!/usr/bin/env pythonX” where pythonX doesn't exist

余生颓废 提交于 2019-12-04 05:55:17

问题


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.


回答1:


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.




回答2:


The shebang is only processed when you do test.py, running the file directly instead of running python with test.py as an argument. When you do python test.py, Python completely ignores the shebang line.



来源:https://stackoverflow.com/questions/38401850/python-myscript-ignores-usr-bin-env-pythonx-where-pythonx-doesnt-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!