Portable way to write Python 3 shebang?

465 Views Asked by At

Back when Python3 was there, I used to use:

#!/usr/bin/env python3

But recently, especially with Ubuntu 22.04 or macOS, the python3 executable isn't always available in PATH, instead, I should use python to call python3.

Is there any portable way to write Python3 shebang?

1

There are 1 best solutions below

0
Bastian Venthur On BEST ANSWER

According to the Python docs, using #!/usr/bin/env python3 is still the recommended way -- but they admit that it does not always work:

2.4. Miscellaneous

To easily use Python scripts on Unix, you need to make them executable, e.g. with

chmod +x script

and put an appropriate Shebang line at the top of the script. A good choice is usually

#!/usr/bin/env python3 which searches for the Python interpreter in the whole PATH. However, some Unices may not have the env command, so you may need to hardcode /usr/bin/python3 as the interpreter path.

The alternative is then to hardocode the python binary, i.e. /usr/bin/python3 (or python in your case).