Skip to content

Instantly share code, notes, and snippets.

@malex984
Last active August 25, 2020 11:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malex984/df0fc88ac516f7f30fc793e42e07958a to your computer and use it in GitHub Desktop.
Save malex984/df0fc88ac516f7f30fc793e42e07958a to your computer and use it in GitHub Desktop.
run a simple HTTP server using python 2 or 3 via command line using bash script
#!/bin/bash
### purpose: run simple HTTP server in both Python2 and Python3
### note: set PYTHON and ARGS environment variables for control the behaviour
export PORT=${PORT:-8000} # open http://localhost:8000/
export ARGS=${ARGS:-${PORT}}
export PYTHON=${PYTHON:-python}
echo "Running HTTP Server via [${PYTHON}]: "
${PYTHON} -VV -V --version || exit $?
echo "Command line arguments: [${ARGS}]..."
export PYTHON_MAJOR_VERSION=`${PYTHON} -c "import sys; print(sys.version_info.major)"`
if [[ "${PYTHON_MAJOR_VERSION}" == "2" ]]; then
# in Python 2
export HTTP_SERVER_MODULE="SimpleHTTPServer"
elif [[ "${PYTHON_MAJOR_VERSION}" == "3" ]]; then
# in Python 3
export HTTP_SERVER_MODULE="http.server"
else
echo "Sorry: version of [$PYTHON] is not supported!"
exit 1
fi
echo "Press Ctrl+C to exit."
exec ${PYTHON} -m ${HTTP_SERVER_MODULE:-ERROR_UNKNOWN_MODULE} ${ARGS}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment