8

Why running a python file doesn't require the x permission when running it like this:

python script.py

But it does when it's being run as:

./script.py
Forge
  • 6,538
  • 6
  • 44
  • 64

3 Answers3

10

Because what you are running with python script.py is the python program; then, it loads and runs the script that you specified in parameters, that is script.py (basically a text file). The script file doesn't need to be an executable because what is executed here is the python interpreter (the python binary itself, that should obviously have the x permission).

With .\script.py, you try to run directly your script (still the same text file) as a program. When you do that, you want it to be parsed with the interpreter that you specified in the first line of your script code, the "shebang", e.g. #!/usr/bin/env python. If it's not set with the x permission, the OS doesn't try to "execute" your file (though it might try to open it with the default program, where applicable), so, it will not care about the shebang.

cedbeu
  • 1,919
  • 14
  • 24
  • 1
    To learn more about how this works, look for unix shebangs https://en.wikipedia.org/wiki/Shebang_%28Unix%29 – xvan Mar 08 '16 at 11:18
4

The file itself it interpreted (read) rather than actually executed in your first example. The python application is what needs execute rights.

In the second example the file itself is being executed, so needs those rights in order to proceed.

Pep_8_Guardiola
  • 5,002
  • 1
  • 24
  • 35
3

When we run a script as python script.py we actually invoke the python interpreter which is generally located at /usr/bin/python (The output of which python will tell you where exactly).

The interpreter in turn reads the scripts and executes its code. It is the interpreter that has the execute permission.

When a script is executed as ./script.py then the script is executed directly and hence the script requires execute permission. The interpreter used is specified by shebang line.

When the kernel finds that the first two bytes are #! then it uses the rest of the line as interpreter and passes the file as argument. Note that to do this the file needs to have execute permission. In the former case we are indirectly doing what the kernel would do had we executed the script as ./script.py

In short for executing by method1 the interpreter needs only read permission but for later it needs to execute it directly

Ricardo Saporta
  • 54,400
  • 17
  • 144
  • 178
Sharad
  • 1,867
  • 14
  • 33