Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python shebang line [duplicate]

i've seen some people write their shebang line with a space after env. Eg.

#!/usr/bin/env python

Is this a typo?

I don't ever use a space. I use

#!/usr/bin/env/python

Can someone please clarify this?

like image 972
PandaSurge Avatar asked Dec 23 '22 07:12

PandaSurge


2 Answers

No it isn't a typo! The one you are using will not work on all os's. E.G. in my Ubuntu Linux implementation 'env' is a program in /usr/bin not a directory so #!/usr/bin/env/python won't work.

like image 89
Paula Thomas Avatar answered Feb 04 '23 21:02

Paula Thomas


Not using a space isn't a typo, but leads to portability issues when executing the same file on different machines. The purpose of the shebang line (#!/usr....) is to indicate what interpreter is to be used when executing the code in the file. According to Wikipedia:

The form of a shebang interpreter directive is as follows:

#!interpreter [optional-arg]

in which interpreter is an absolute path to an executable program. The optional argument is a string representing a single argument.

The example you provided, #!/usr/bin/env python, actually indicates to the shell that the interpreter to be used when executing the file is the first python interpreter that exists in the user's path. The shebang line is written this way to ensure portability:

Shebangs must specify absolute paths (or paths relative to current working directory) to system executables; this can cause problems on systems that have a non-standard file system layout. Even when systems have fairly standard paths, it is quite possible for variants of the same operating system to have different locations for the desired interpreter. Python, for example, might be in /usr/bin/python, /usr/local/bin/python, or even something like /home/username/bin/python if installed by an ordinary user.

Because of this it is sometimes required to edit the shebang line after copying a script from one computer to another because the path that was coded into the script may not apply on a new machine, depending on the consistency in past convention of placement of the interpreter. For this reason and because POSIX does not standardize path names, POSIX does not standardize the feature.

Often, the program /usr/bin/env can be used to circumvent this limitation by introducing a level of indirection. #! is followed by /usr/bin/env, followed by the desired command without full path, as in this example:

#!/usr/bin/env sh

like image 35
cincospenguinos Avatar answered Feb 04 '23 21:02

cincospenguinos