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

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

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

21条回答
  •  遇见更好的自我
    2020-11-21 06:56

    In order to run the python script, we need to tell the shell three things:

    1. That the file is a script
    2. Which interpreter we want to execute the script
    3. The path of said interpreter

    The shebang #! accomplishes (1.). The shebang begins with a # because the # character is a comment marker in many scripting languages. The contents of the shebang line are therefore automatically ignored by the interpreter.

    The env command accomplishes (2.) and (3.). To quote "grawity,"

    A common use of the env command is to launch interpreters, by making use of the fact that env will search $PATH for the command it is told to launch. Since the shebang line requires an absolute path to be specified, and since the location of various interpreters (perl, bash, python) may vary a lot, it is common to use:

    #!/usr/bin/env perl  instead of trying to guess whether it is /bin/perl, /usr/bin/perl, /usr/local/bin/perl, /usr/local/pkg/perl, /fileserver/usr/bin/perl, or /home/MrDaniel/usr/bin/perl on the user's system...

    On the other hand, env is almost always in /usr/bin/env. (Except in cases when it isn't; some systems might use /bin/env, but that's a fairly rare occassion and only happens on non-Linux systems.)

提交回复
热议问题