Last active
January 31, 2025 12:49
-
-
Save stuaxo/f47b29da25f3d655440984ffe6c5da40 to your computer and use it in GitHub Desktop.
Create a Jupyter Kernel for for the current virtualenv.
This file contains hidden or 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
#!/bin/bash | |
# | |
# Creates a Jupyter kernel for a virtual environment. | |
# | |
# Usage: | |
# ./create_kernel.sh [venv_name] | |
# | |
# Arguments: | |
# venv_name Optional. Name of the virtual environment to create kernel for. | |
# If not provided, uses currently activated environment. | |
# | |
# Examples: | |
# 1. Create kernel for current activated environment: | |
# $ source venv/bin/activate | |
# $ ./create_kernel.sh | |
# | |
# 2. Create kernel for specific environment in current directory: | |
# $ ./create_kernel.sh myproject_venv | |
# | |
# 3. Create kernel for environment for ~/.virtualenvs: | |
# $ ./create_kernel.sh data_science_env | |
# | |
# Notes: | |
# - Script will install ipykernel if not already present | |
# - Environments can be in current directory or the virtualenvwrapper directory: ~/.virtualenvs/ | |
# - If Jupyter is open refresh the page to see the new kernel. | |
# Get the name of the virtual environment from the command line or default to the current environment. | |
VENV_NAME="$1" | |
# Check if a virtual environment name was provided | |
if [ -z "$VENV_NAME" ]; then | |
if [ -z "$VIRTUAL_ENV" ]; then | |
echo "No virtual environment is currently activated, and none was specified." | |
exit 1 | |
else | |
VENV_NAME=$(basename "$VIRTUAL_ENV") | |
fi | |
else | |
# Check both the current directory and the .virtualenvs directory for the specified environment | |
if [ -d "$VENV_NAME" ]; then | |
VENV_PATH="$VENV_NAME" | |
elif [ -d "$HOME/.virtualenvs/$VENV_NAME" ]; then | |
VENV_PATH="$HOME/.virtualenvs/$VENV_NAME" | |
else | |
echo "Virtual environment '$VENV_NAME' not found." | |
exit 1 | |
fi | |
source "$VENV_PATH/bin/activate" | |
fi | |
# Install ipykernel if not already installed | |
if ! pip freeze | grep -q ipykernel; then | |
pip install ipykernel | |
fi | |
# Create the Jupyter kernel | |
python -m ipykernel install --user --name="$VENV_NAME" --display-name="Python ($VENV_NAME)" | |
echo "Jupyter kernel for '$VENV_NAME' created successfully." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment