Last active
July 31, 2019 12:27
-
-
Save joaocarmo/e5828264069e8e3dddcbba207639745a to your computer and use it in GitHub Desktop.
Python wrapper to select the best interpreter available in the system
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
################################################################################ | |
# Python Wrapper | |
# ------------------------------------------------------------------------------ | |
# Author: Joao Carmo | |
# License: MIT | |
# ------------------------------------------------------------------------------ | |
# This wrapper script will test each available Python interpreter in the system | |
# to find the one which has the most critical modules installed and then execute | |
# the Python code | |
################################################################################ | |
# Settings | |
pythons=('python' 'python2' 'python3') # Pythons list, accepts absolute paths | |
modules=('ssl') # Python modules list to test | |
py_script='my_script.py' # Python code to execute if valid | |
# Debug function for verbose execution | |
function debug_print { | |
if [ "$PY_DEBUG" = "true" ]; then | |
echo "$1" | |
fi | |
} | |
# Main loop | |
for py in ${pythons[@]}; do | |
debug_print "testing for $py" | |
py_exec=`which $py` | |
exit_code=$? | |
if [ $exit_code -eq 0 ]; then | |
debug_print "$py exists in $py_exec" | |
if [ -f $py_exec ]; then | |
debug_print "$py_exec is a file" | |
if [ -x $py_exec ]; then | |
debug_print "$py_exec is executable" | |
should_exec=0 | |
for mod in ${modules[@]}; do | |
test=`$py_exec -c "import $mod" >/dev/null 2>&1` | |
test_exit_code=$? | |
if [ $test_exit_code -eq 0 ]; then | |
debug_print "$py_exec has '$mod' support" | |
else | |
debug_print "$py_exec has no '$mod' support" | |
should_exec=$(($should_exec + 1)) | |
fi | |
done | |
if [ $should_exec -eq 0 ]; then | |
exec $py_exec "`python -c "import os;print(os.path.dirname(os.path.realpath('$0')))"`/$py_script" "$@" | |
fi | |
fi | |
fi | |
fi | |
done | |
# If no valid interpreter is found | |
echo "ERROR: No appropriate 'python' interpreter found" >&2 | |
exit 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment