Skip to content

Use docstring instead of variable definition #1

Description

@ewenmcneill

Inspired by a comment on the original version, it looks like we can use a docstring instead of a variable definition to hide the shell script. And by using : as suggested as the "placeholder" command in the shell script it is fairly readable.

From a quick test, it looks like this might work with a Bourne shell / Python2 / Python3, but needs some more testing. Test further, and if it works, then update the example.

The bonus of using a docstring to hide the data is that we can then use from __future__ ... in the Python code section.

""":" # Shell script, Python doc string; find Python interpreter

# Try the usual locations
for INTERPRETER in python3 python2 python; do
    PYTHON=$(command -v "${INTERPRETER}" 2>/dev/null)
    if [ -n "${PYTHON}" ]; then
       echo "Found Python in ${PYTHON}" >&2
       exec "${PYTHON}" "$0" "$@"
    fi
done

# Maybe we have Ansible or some other Python system program
# whose homework we can copy?
#
for PROGRAM in ansible; do
    PROGPATH=$(which "${PROGRAM}" 2>/dev/null)
    if [ -n "${PROGPATH}" -a -r "${PROGPATH}" ]; then
        PYTHON=$(head -1 $(command -v ansible) | sed 's/^#!//; s/^  *//; s/\/usr\/bin\/env //; s/ .*$//;')
        if [ -n "${PYTHON}" ]; then
           echo "Found Python in ${PYTHON}" >&2
           exec "${PYTHON}" "$0" "$@"
        fi
    fi
done

# Or we have some random OS default location
for PYTHON in /usr/libexec/platform-python; do
    if [ -x "${PYTHON}" ]; then
       echo "Found Python in ${PYTHON}" >&2
       exec "${PYTHON}" "$0" "$@"
    fi
done

echo "Sorry, I have no idea where Python is.  Is it even installed?!" >&2
exit 254
":""" # End of shell script, start of shared code

from __future__ import print_function
print("Hello World!")

Activity

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

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions