Skip to content

Instantly share code, notes, and snippets.

@throwaway96
Last active February 28, 2024 04:57
Show Gist options
  • Save throwaway96/3b9d1d502b55cb0a6892ffdc60129d6a to your computer and use it in GitHub Desktop.
Save throwaway96/3b9d1d502b55cb0a6892ffdc60129d6a to your computer and use it in GitHub Desktop.
How to make a Python script work with multiple potential interpreter names (polyglot Python/shell script)

The Python interpreter on webOS 1‒6 is python (Python 2.7), while on webOS 7+ it's python3. To make a Python script that can be run on any version of webOS, I added a bit of shell script at the top that figures out the name of the Python interpreter and uses that to re-execute itself:

#!/bin/sh
''''command -v -- python3 >/dev/null && exec python3 -- "$0" "$@" || exec python -- "$0" "$@" # '''

Python ignores this because it just sees a docstring (idea from here), and the shell is no longer running after exec. I'm sure someone else has already done this, but I didn't really know what to search for. (Edit: Found this. It's more thorough, but a lot longer.)

Example (test.py):

#!/bin/sh
''''command -v -- python3 >/dev/null && exec python3 -- "$0" "$@" || exec python -- "$0" "$@" # '''

print("hi")

import sys
print(sys.argv)
$ ./test.py -a -b -c 123 'asdf qwer'
hi
['./test.py', '-a', '-b', '-c', '123', 'asdf qwer']

Of course, the Python code itself has to be compatible with Python 2 and 3.

I've tested this with ash from BusyBox v1.29.3 (webOS 6) and v1.31.1 (webOS 8) as well as Bash 5.2.15.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment