Why do people write #!/usr/bin/env python on the first line of a Python script?

后端 未结 21 1730
刺人心
刺人心 2020-11-21 06:16

It seems to me like the files run the same without that line.

21条回答
  •  感情败类
    2020-11-21 06:52

    It just specifies what interpreter you want to use. To understand this, create a file through terminal by doing touch test.py, then type into that file the following:

    #!/usr/bin/env python3
    print "test"
    

    and do chmod +x test.py to make your script executable. After this when you do ./test.py you should get an error saying:

      File "./test.py", line 2
        print "test"
                   ^
    SyntaxError: Missing parentheses in call to 'print'
    

    because python3 doesn't supprt the print operator.

    Now go ahead and change the first line of your code to:

    #!/usr/bin/env python2
    

    and it'll work, printing test to stdout, because python2 supports the print operator. So, now you've learned how to switch between script interpreters.

提交回复
热议问题