Skip to content

Instantly share code, notes, and snippets.

@bmamlin
Last active November 2, 2021 03:21
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 bmamlin/715f2aa3dd61031d2daac98e27b85d78 to your computer and use it in GitHub Desktop.
Save bmamlin/715f2aa3dd61031d2daac98e27b85d78 to your computer and use it in GitHub Desktop.
Jupyter Notebook using current folder contents

Jupyter Notebook using current folder contents

Two lil' scripts (notebook-up & notebook-down) leveraging Docker to make it convenient to fire up Jupyter Notebooks attached to the current folder.

Usage

  1. Place notebook-up and notebook-down on your path as executable files (i.e., chmod 755 notebook-up notebook-down)
  2. Use notebook-up to start the notebook and notebook-down (must be run from the same folder) to kill the docker container and clean up

Details

The notebook-up script just tells Docker to fire up a minimal Jupyter Notebook container attached to the current folder with the name "-notebook" and then waits for that container to report it's security token in the container logs so the script can open a browser directly to the notebook ready-to-go for you. If the notebook container is already running, it will just open the browser to the notebook.

The script installs a couple of extra libraries:

  • prodict for dot notation access to dicts
  • pandas for fun with data

Any notebooks saved will be saved to the same folder you were in when you ran notebook-up.

#!/bin/bash
NOTEBOOK_NAME=${PWD##*/}-notebook; NOTEBOOK_NAME=${NOTEBOOK_NAME// /_}
docker rm -f $NOTEBOOK_NAME
#!/bin/bash
NOTEBOOK_NAME=${PWD##*/}-notebook; NOTEBOOK_NAME=${NOTEBOOK_NAME// /_}
notebook_container_id=$(docker ps -q -f name=$NOTEBOOK_NAME)
if [ -z "$notebook_container_id" ]
then
docker run --name $NOTEBOOK_NAME -p 8888:8888 -v "$PWD":/home/jovyan -d jupyter/minimal-notebook
fi
while true
do
# Exit as soon as we find notebook's URL
notebook_url=$(docker logs $NOTEBOOK_NAME 2>&1 | sed -n -e 's/^.*\(http:\/\/127\)/\1/p' | head -n 1)
if [ ! -z "$notebook_url" ]
then
break
fi
# Give notebook a second to start
sleep 1
done
# Install prodict (if not already installed) because we like dot notation for JSON
prodict_installed=$(docker exec $NOTEBOOK_NAME bash -c 'python -c "import prodict" 2&> /dev/null; echo $?')
if [ ! "$prodict_installed" -eq "0" ]; then
docker exec $NOTEBOOK_NAME pip install prodict pandas
fi
# Extract URL with security token from docker logs and open it
open $notebook_url
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment