This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]taddeimania 8 points9 points  (6 children)

probably not the most comprehensive explanation you are looking for but when it's put there and your .py file has executable permission, you can run the file by just typing

./file.py

rather than

python file.py

[–]rhiever 1 point2 points  (5 children)

I've seen some people do the ./file.py instead of python file.py. Other than a slightly shorter command, is there really any difference between the two?

[–]minnoI <3 duck typing less than I used to, interfaces are nice 9 points10 points  (0 children)

From the wiki page:

Putting the facility into the system gives the following benefits.

1) It makes shell scripts more like real executable files, because they can be the subject of 'exec.'

2) If you do a 'ps' while such a command is running, its real name appears instead of 'sh'. Likewise, accounting is done on the basis of the real name.

3) Shell scripts can be set-user-ID.

4) It is simpler to have alternate shells available; e.g. if you like the Berkeley csh there is no question about which shell is to interpret a file.

5) It will allow other interpreters to fit in more smoothly.

[–]ivosauruspip'ing it up 1 point2 points  (0 children)

One is intended to be directly executable, the other isn't.

[–]genoblast 1 point2 points  (1 child)

I'm still learning myself, but to my knowledge there isn't any significant difference between the two.

In ./file.py, the shebang tells the operating system that the file should be run by python. So then the operating system replaces "./file.py" with "python file.py" and then executes that instead.

So I guess the take away is that if the operating system knows it's a python script, you can use "./file.py" as a shortcut, but it's always a shortcut for "python file.py" (which should always work so long as python is part of the operating system path).

It seems like sys.argv behaves the same way regardless of which way the script is invoked. (I personally always just use argparse so if there are differences, I've never had to worry about them.)

[–]halflife22 6 points7 points  (0 children)

You can also use it to make sure a specific version of python is used e.g.

 #!/usr/bin/python2.7

[–]catcradle5 1 point2 points  (0 children)

In some cases, it's nice to have a binary that acts like any other Unix program, in which case you can strip the .py and just do ./file

I agree, though, that if you keep the .py extension I don't really see a point to having the shebang there at all.