1#!/usr/bin/env bash
2#
3# Tool for running scripts with several versions of Python by the use of pyenv (versions must be installed before in
4# the docker image)
5#
6# Examples:
7# ./multirun_with_pyenv.sh ./exec.sh                 # Run ./exec.h with ALL installed versions of Python
8# ./multirun_with_pyenv.sh ./exec.sh arg1 arg2       # Run ./exec.h with arguments (and ALL installed versions of Python)
9# ./multirun_with_pyenv.sh -p 2.7.15 ./exec.sh       # Run ./exec.h with Python 2.7.15 (-p must be the first argument)
10# ./multirun_with_pyenv.sh -p 3.4.8,2.7.15 ./exec.sh # Run ./exec.h with Python 3.4.8 and 2.7.15 (versions must be
11#                                               # separated by coma and be without a space)
12
13PY_VERSIONS=""
14
15{ source /opt/pyenv/activate; } || { echo 'Pyenv activation has failed!' ; exit 1; }
16
17if [ "$1" = "-p" ]; then
18    if [ "$#" -ge 2 ]; then
19        IFS=',' read -a PY_VERSIONS <<< "$2"
20        shift #remove -p
21        shift #remove argument after -p
22    else
23        echo 'No value (Python version) is given for argument -p!'
24        exit 1
25    fi
26else
27    PY_VERSIONS=$(pyenv versions --bare)
28fi
29
30if [ "$#" -lt 1 ]; then
31    echo 'No executable was passed to the runner!'
32    exit 1
33fi
34
35for ver in ${PY_VERSIONS[@]}
36do
37    echo 'Switching to Python' $ver
38    $(pyenv global $ver) || exit 1
39    echo 'Running' $@
40    $@ || {
41               echo 'Run failed! Switching back to the system version of the Python interpreter.';
42               pyenv global system;
43               exit 1;
44          }
45done
46
47echo 'Switching back to the system version of Python'
48{ pyenv global system; } || { echo 'Restoring the system version of the Python interpreter has failed!' ; exit 1; }
49