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

后端 未结 21 1751
刺人心
刺人心 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 probably makes sense to emphasize one thing that the most have missed, which may prevent immediate understanding. When you type python in terminal you don't normally provide a full path. Instead, the executable is up looked in PATH environment variable. In turn, when you want to execute a Python program directly, /path/to/app.py, one must tell the shell what interpreter to use (via the hashbang, what the other contributors are explaining above).

    Hashbang expects full path to an interpreter. Thus to run your Python program directly you have to provide full path to Python binary which varies significantly, especially considering a use of virtualenv. To address portability the trick with /usr/bin/env is used. The latter is originally intended to alter environment in-place and run a command in it. When no alteration is provided it runs the command in current environment, which effectively results in the same PATH lookup which does the trick.

    Source from unix stackexchange

提交回复
热议问题