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

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

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

21条回答
  •  一生所求
    2020-11-21 06:51

    Expanding a bit on the other answers, here's a little example of how your command line scripts can get into trouble by incautious use of /usr/bin/env shebang lines:

    $ /usr/local/bin/python -V
    Python 2.6.4
    $ /usr/bin/python -V
    Python 2.5.1
    $ cat my_script.py 
    #!/usr/bin/env python
    import json
    print "hello, json"
    $ PATH=/usr/local/bin:/usr/bin
    $ ./my_script.py 
    hello, json
    $ PATH=/usr/bin:/usr/local/bin
    $ ./my_script.py 
    Traceback (most recent call last):
      File "./my_script.py", line 2, in 
        import json
    ImportError: No module named json
    

    The json module doesn't exist in Python 2.5.

    One way to guard against that kind of problem is to use the versioned python command names that are typically installed with most Pythons:

    $ cat my_script.py 
    #!/usr/bin/env python2.6
    import json
    print "hello, json"
    

    If you just need to distinguish between Python 2.x and Python 3.x, recent releases of Python 3 also provide a python3 name:

    $ cat my_script.py 
    #!/usr/bin/env python3
    import json
    print("hello, json")
    

提交回复
热议问题