我在一些脚本语言中注意到了这一点,但是在这个例子中,我使用的是python。在许多教程中,他们会以#!/usr/bin/python3。我不明白我们为什么要这么做。
操作系统不应该知道它是一个python脚本吗(显然它已经安装了,因为你引用了它)
如果用户使用的操作系统不是基于unix的呢
由于某种原因,该语言被安装在不同的文件夹中
用户版本不一致。特别是当它不是完整的版本号时(比如Python3 vs Python32)
如果有的话,我可以看到这破坏了python脚本,因为上面列出的原因。
#!/usr/bin/python3是shebang行。
shebang行定义解释器的位置。在本例中,python3解释器位于/usr/bin/python3shebang行也可以是bash、ruby、perl或任何其他脚本语言的解释器,例如:#!/bin/bash。
如果没有shebang行,操作系统不会知道它是一个python脚本,即使你在脚本上设置了执行标志(chmod +x script.py)并像./script.py那样运行它。要使脚本在python3中默认运行,可以将其作为python3 script.py调用,或者设置shebang行。
你可以使用#!/usr/bin/env python3用于不同系统之间的可移植性,以防语言解释器安装在不同的位置。
#!/usr/bin/python3是shebang行。
shebang行定义解释器的位置。在本例中,python3解释器位于/usr/bin/python3shebang行也可以是bash、ruby、perl或任何其他脚本语言的解释器,例如:#!/bin/bash。
如果没有shebang行,操作系统不会知道它是一个python脚本,即使你在脚本上设置了执行标志(chmod +x script.py)并像./script.py那样运行它。要使脚本在python3中默认运行,可以将其作为python3 script.py调用,或者设置shebang行。
你可以使用#!/usr/bin/env python3用于不同系统之间的可移植性,以防语言解释器安装在不同的位置。
为了阐明shebang行如何在windows中工作,请参阅3.7 Python文档:
If the first line of a script file starts with #!, it is known as a “shebang” line. Linux and other Unix like operating systems have native support for such lines and they are commonly used on such systems to indicate how a script should be executed.
The Python Launcher for Windows allows the same facilities to be used with Python scripts on Windows
To allow shebang lines in Python scripts to be portable between Unix and Windows, the launcher supports a number of ‘virtual’ commands to specify which interpreter to use. The supported virtual commands are:
/usr/bin/env python
The /usr/bin/env form of shebang line has one further special property. Before looking for installed Python interpreters, this form will search the executable PATH for a Python executable. This corresponds to the behaviour of the Unix env program, which performs a PATH search.
/usr/bin/python
/usr/local/bin/python
python