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

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

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

21条回答
  •  别跟我提以往
    2020-11-21 07:08

    If you're running your script in a virtual environment, say venv, then executing which python while working on venv will display the path to the Python interpreter:

    ~/Envs/venv/bin/python

    Note that the name of the virtual environment is embedded in the path to the Python interpreter. Therefore, hardcoding this path in your script will cause two problems:

    • If you upload the script to a repository, you're forcing other users to have the same virtual environment name. This is if they identify the problem first.
    • You won't be able to run the script across multiple virtual environments even if you had all required packages in other virtual environments.

    Therefore, to add to Jonathan's answer, the ideal shebang is #!/usr/bin/env python, not just for portability across OSes but for portability across virtual environments as well!

提交回复
热议问题