For scripts that are only expected to be run in an activated virtual environment, shebang lines can be written as #!/usr/bin/env python, as this instructs the script to respect the active virtual environment.
Could we clarify the following?
env
is a system binary in/usr/bin
available in most Linux distros that searches$PATH
for strings containing the provided argument and returns the first instance it finds. In the above syntax,env
will search for the first instance ofpython
in$PATH
and return it.The shebang #! /usr/bin/env python works equally well in Linux when a script is to be run from within an activated virtual environment or when a default python installation is to be used and it is uncertain whether the
python
interpreter exists in/bin
,/usr/bin
,/usr/local/bin
, or another custom path.Since
python
may be an alias forpython2
orpython3
(typically, it is an alias forpython2
), the developer may choose to be specific and use the shebang#!/usr/bin/env python3
where desired. The Windows py launcher also accepts this shebang and searches the application directory, current directory, system directories, andPATH
for “python.exe”. However, note that using python3 instead of python will not work as expected because it will instead use the preferred version of python 3.x that's installed and not look through directories.