Files
Cuda/python-docker.sh
2022-08-05 14:44:50 +05:30

64 lines
1.6 KiB
Bash

#!/bin/bash
# Filename: /usr/local/bin/python-docker
# Script to run python:latest inside an ephemeral docker container
# pip install python modules if requirements.txt is preset
# do not continue script on errors
set -euo pipefail
# Python version to run from docker hub
X_PYTHON_VERSION="latest"
# Get current user details so we can run python with this user id later
X_UID=$(id -u)
X_USERNAME=$(id -un)
# Set docker container name to basename of current working dir + random string
NAME=$(echo $(basename "${PWD}" ).${RANDOM})
# Create temporary docker ENTRYPOINT shell script
X_TMPDIR="$(mktemp -d)"
ENTRYPOINT="${X_TMPDIR}/entrypoint.sh"
# Remove temp files on exit
trap "{ rm -rf ${X_TMPDIR}; }" EXIT
cat > "${ENTRYPOINT}" <<EOF
#!/bin/bash
# Alternate entrypoint for python docker image
# Run pip as root, then run python as X_USERNAME
# do not continue script on errors
set -euo pipefail
# Optimize pip for docker usage
export ENV PIP_DISABLE_PIP_VERSION_CHECK=1
export ENV PIP_NO_CACHE_DIR=1
# create the current user in the container
useradd -u ${X_UID} -U -s /bin/bash -M ${X_USERNAME}
# pip install modules if requirements.txt is present
[ -f requirements.txt ] && pip install -r requirements.txt
# run python
exec su -c "python $@" ${X_USERNAME}
EOF
chmod 755 ${ENTRYPOINT}
# Run python in docker with all the containers set
docker run -it --rm \
-v /etc/timezone:/etc/timezone:ro \
-v /etc/localtime:/etc/localtime:ro \
-v /data:/data -v /home:/home \
-v ${X_TMPDIR}:${X_TMPDIR} \
-w $(pwd) \
--entrypoint "${ENTRYPOINT}" \
--name ${NAME} \
--net=host \
python:X_PYTHON_VERSION "$@"