"python myscript"忽略“#!/usr/bin/env pythonX" pythonX不存在的地方 [英] "python myscript" ignores "#!/usr/bin/env pythonX" where pythonX doesn't exist
问题描述
为什么未安装Python 3时test.py
不会抛出错误env: python3: No such file or directory
?
Why doesn't test.py
throw error env: python3: No such file or directory
when Python 3 is not installed?
我的系统(Mac OS X)已安装Python 2.7,但未安装Python 3:
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
文件 test.py:
#!/usr/bin/env python3
import sys
print sys.executable
执行 test.py:
$ python test.py
/usr/local/opt/python/bin/python2.7
我认为,由于我的系统上不存在Python 3,因此使用shebang行#!/usr/bin/env python3
会引发错误并终止脚本.但是env
实际上选择了Python 2.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.
推荐答案
操作系统尝试执行脚本时会解释shebang.键入乳清python test.py
,操作系统将执行python
,而python
执行脚本(并且python
是基于当前PATH
找到的),而不是由操作系统处理.
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.
如果使脚本可执行(chmod +x test.py
),然后尝试直接执行(例如./test.py
),则操作系统将负责运行脚本,因此它将查看shebang以确定程序是什么负责运行脚本.在这种情况下,/usr/bin/env
将查找python3
并尝试使用它.由于python3
不存在(或在PATH
上找不到),因此您会看到错误.
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.
这篇关于"python myscript"忽略“#!/usr/bin/env pythonX" pythonX不存在的地方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!