4

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?

6
  • Wait, Ubuntu 22.04 removed python3? I'm still on 20.04 myself. I checked the dependencies online and it still seems to be there: ubuntu-desktop -> software-properties-gtk -> python3 -> python3-minimal: /usr/bin/python3; and ubuntu-server -> software-properties-common -> python3. Commented Nov 7, 2022 at 18:42
  • 2
    sudo apt install python-is-python3 Commented Nov 7, 2022 at 18:46
  • For true portability use a virtualenv through pyenv. Then your system does pyenv activate my_python3.x.y_env and just runs the script with a normal shebang. Using a virtualenv and pyenv removes all dependencies on the system python and problems with package dependencies. Commented Nov 7, 2022 at 18:51
  • The installation process will replace any shebang containing the word python with whatever is used to actually install your script. #!python would suffice. You as the author of the code shouldn't worry about where the user keeps the version of Python they'll use to execute it. Commented Nov 7, 2022 at 19:10
  • Easier to symlink python3 -> python in /usr/bin or the like than to muck around tons of shebangs, IMHO. Commented Nov 7, 2022 at 21:20

1 Answer 1

3

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).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.