python脚本中的头注释

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaobao5214/article/details/82705913

python脚本开头一般有这么两行:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

 它是用来干嘛的?貌似没有它对脚本功能也没啥影响。它是用来指定用什么解释器运行脚本以及解释器所在的位置还有文件编码。以test.py为例,脚本内容如下:

def test():
        print 'hello, world'


if __name__ == "__main__":
        test()


运行脚本:
python test.py
输出:
hello, world

换一种方法运行:
./test.py
会提示出错,文件无可执行权限:
-bash: ./test.py: Permission denied

将文件设为可执行:
chmod +x test.py
继续运行:
./test.py
提示:
./test.py: line 1: syntax error near unexpected token `('
./test.py: line 1: `def test():'
那是因为系统默认该脚本是shell脚本,把它当shell语句执行,当然失败了。

在前面加上
#!/usr/bin/python
申明这是个python脚本,要用python解释器来运行:
./test.py
输出:
hello, world

猜你喜欢

转载自blog.csdn.net/xiaobao5214/article/details/82705913