Saltar a contenido

JupyterLab

_ _

JupyterLab Cheatsheet

Instalación

Platform Command
Ubuntu/Debian (pip) INLINE_CODE_10 HTML_TAG_141 INLINE_CODE_11
Ubuntu/Debian (conda) INLINE_CODE_12
macOS (Homebrew) INLINE_CODE_13 HTML_TAG_142 INLINE_CODE_14
macOS (conda) INLINE_CODE_15 HTML_TAG_143 INLINE_CODE_16
Windows (pip) INLINE_CODE_17
Windows (Anaconda) Install Anaconda, then: INLINE_CODE_18
Docker INLINE_CODE_19 HTML_TAG_144 INLINE_CODE_20
Upgrade INLINE_CODE_21
Verify Installation INLINE_CODE_22

Comandos básicos

Command Description
INLINE_CODE_23 Start JupyterLab server (opens browser automatically)
INLINE_CODE_24 Start JupyterLab on specific port
INLINE_CODE_25 Start without opening browser
INLINE_CODE_26 Start with specific working directory
INLINE_CODE_27 List all running JupyterLab servers
INLINE_CODE_28 Stop JupyterLab server on port 8888
INLINE_CODE_29 Display JupyterLab version
INLINE_CODE_30 Show all Jupyter paths (config, data, runtime)
INLINE_CODE_31 Generate default configuration file
INLINE_CODE_32 Set password for JupyterLab server
INLINE_CODE_33 Clean up JupyterLab installation
INLINE_CODE_34 List all available kernels
INLINE_CODE_35 List all installed extensions
INLINE_CODE_36 Trust a notebook (allow JavaScript)
INLINE_CODE_37 Display help and all available options

Kernel Management

Command Description
INLINE_CODE_38 List all installed kernels
INLINE_CODE_39 Install Python kernel from environment
INLINE_CODE_40 Install kernel with custom display name
INLINE_CODE_41 Remove a kernel
INLINE_CODE_42 Install R kernel
INLINE_CODE_43 Install Julia kernel
INLINE_CODE_44 Install kernel support in conda environment
INLINE_CODE_45 Remove kernel specification

Notebook Conversion (nbconvert)

Command Description
INLINE_CODE_46 Convert notebook to HTML
INLINE_CODE_47 Convert notebook to PDF
INLINE_CODE_48 Convert notebook to Python script
INLINE_CODE_49 Convert notebook to Markdown
INLINE_CODE_50 Convert notebook to reveal.js slides
INLINE_CODE_51 Execute notebook and save output
INLINE_CODE_52 Execute and convert to HTML
INLINE_CODE_53 Clear all cell outputs
INLINE_CODE_54 Batch convert all notebooks in directory
INLINE_CODE_55 Execute notebook and export to PDF

Extension Management

Command Description
INLINE_CODE_56 List all installed extensions
INLINE_CODE_57 Install table of contents extension
INLINE_CODE_58 Uninstall an extension
INLINE_CODE_59 Update specific extension
INLINE_CODE_60 Disable extension without uninstalling
INLINE_CODE_61 Enable previously disabled extension
INLINE_CODE_62 Rebuild JupyterLab (required after extension changes)
INLINE_CODE_63 Check for extension updates
INLINE_CODE_64 Link extension for development

Configuración avanzada del servidor

Command Description
INLINE_CODE_65 Allow connections from any IP address
INLINE_CODE_66 Start server for remote access
INLINE_CODE_67 Set custom authentication token
INLINE_CODE_68 Allow requests from any origin (CORS)
INLINE_CODE_69 Enable remote access explicitly
INLINE_CODE_70 Increase data rate limit for large outputs
INLINE_CODE_71 Increase max upload size (500MB)
INLINE_CODE_72 Start in debug mode with verbose logging
INLINE_CODE_73 Start in development mode with auto-rebuild
INLINE_CODE_74 Display current configuration
INLINE_CODE_75 Set custom base URL (for reverse proxy)
INLINE_CODE_76 Allow running as root user (not recommended)

Workspace Management

Command Description
INLINE_CODE_77 Export current workspace layout
INLINE_CODE_78 Import workspace layout
INLINE_CODE_79 List all saved workspaces
INLINE_CODE_80 Delete a workspace

Configuración

Configuración principal Archivo

Ubicación: ~/.jupyter/jupyter_lab_config.py_ (Linux/macOS) o %USERPROFILE%\.jupyter\jupyter_lab_config.py (Windows)

Generar configuración predeterminada:

jupyter lab --generate-config

Opciones de configuración común

# ~/.jupyter/jupyter_lab_config.py

c = get_config()

# Server settings
c.ServerApp.ip = '0.0.0.0'                    # Listen on all interfaces
c.ServerApp.port = 8888                       # Default port
c.ServerApp.open_browser = False              # Don't open browser automatically
c.ServerApp.token = 'your-secret-token'       # Authentication token
c.ServerApp.allow_remote_access = True        # Enable remote access
c.ServerApp.allow_origin = '*'                # Allow CORS from any origin
c.ServerApp.allow_root = False                # Prevent running as root

# Directory settings
c.ServerApp.root_dir = '/path/to/notebooks'   # Default working directory
c.ServerApp.preferred_dir = '/path/to/start'  # Preferred starting directory

# Resource limits
c.ServerApp.iopub_data_rate_limit = 10000000  # Data rate limit (bytes/sec)
c.ServerApp.iopub_msg_rate_limit = 1000       # Message rate limit
c.ServerApp.rate_limit_window = 3.0           # Rate limit window (seconds)

# Kernel management
c.MappingKernelManager.default_kernel_name = 'python3'
c.MappingKernelManager.cull_idle_timeout = 3600     # Kill idle kernels after 1 hour
c.MappingKernelManager.cull_interval = 300          # Check for idle kernels every 5 min
c.MappingKernelManager.cull_connected = False       # Don't cull connected kernels

# File management
c.ContentsManager.hide_globs = [
    '__pycache__', '*.pyc', '*.pyo', '.DS_Store', '*.so', '*.dylib'
]
c.FileContentsManager.delete_to_trash = True        # Use trash instead of permanent delete

# Security
c.ServerApp.disable_check_xsrf = False              # Enable XSRF protection
c.ServerApp.tornado_settings = {
    'headers': {
        'Content-Security-Policy': "frame-ancestors 'self'"
    }
}

# Logging
c.ServerApp.log_level = 'INFO'                      # Logging level

Directorio de Configuraciones de Usuarios

Ubicación: ~/.jupyter/lab/user-settings/ (Linux/macOS) o %APPDATA%\jupyter\lab\user-settings\ (Windows)

Ajustes de tema de ejemplo (@jupyterlab/apputils-extension/themes.jupyterlab-settings):

{
    "theme": "JupyterLab Dark",
    "theme-scrollbars": true
}

Password Protection

# Set password interactively
jupyter lab password

# Or generate hash programmatically
python -c "from jupyter_server.auth import passwd; print(passwd('your-password'))"

A continuación, añadir a config:

c.ServerApp.password = 'sha1:...'  # Hashed password

Common Use Cases

Use Case 1: Remote Server Setup

# Generate config file
jupyter lab --generate-config

# Set password
jupyter lab password

# Edit config file (~/.jupyter/jupyter_lab_config.py)
# Set: c.ServerApp.ip = '0.0.0.0'
#      c.ServerApp.open_browser = False
#      c.ServerApp.allow_remote_access = True

# Start server
jupyter lab --no-browser --port=8888

# Access from remote: http://your-server-ip:8888

Use Case 2: Creating a Custom Kernel Environment

# Create conda environment
conda create -n myproject python=3.9 pandas numpy matplotlib

# Activate environment
conda activate myproject

# Install ipykernel
conda install ipykernel

# Register kernel with JupyterLab
python -m ipykernel install --user --name myproject --display-name "Python (myproject)"

# Start JupyterLab and select the new kernel
jupyter lab

Use Case 3: Batch Notebook Execution

# Execute single notebook
jupyter nbconvert --to notebook --execute analysis.ipynb --output results.ipynb

# Execute all notebooks in directory
for notebook in *.ipynb; do
    jupyter nbconvert --to notebook --execute "$notebook" --output "executed_${notebook}"
done

# Execute with timeout and error handling
jupyter nbconvert --to notebook --execute notebook.ipynb \
    --ExecutePreprocessor.timeout=600 \
    --ExecutePreprocessor.allow_errors=True

Use Case 4: Docker Deployment with Persistent Storage

# Create directory for notebooks
mkdir -p ~/jupyter-notebooks

# Run JupyterLab in Docker with volume mount
docker run -d \
    -p 8888:8888 \
    -v ~/jupyter-notebooks:/home/jovyan/work \
    -e JUPYTER_ENABLE_LAB=yes \
    --name jupyter \
    jupyter/datascience-notebook

# Get access token
docker logs jupyter 2>&1 | grep "token="

# Stop container
docker stop jupyter

# Restart container
docker start jupyter

Use Case 5: Converting Notebooks to Presentation

# Convert to reveal.js slides
jupyter nbconvert --to slides presentation.ipynb

# Serve slides with built-in server
jupyter nbconvert --to slides presentation.ipynb --post serve

# Convert with custom template
jupyter nbconvert --to slides --template lab presentation.ipynb

# Export as standalone HTML
jupyter nbconvert --to slides presentation.ipynb --output-dir=./slides/

Keyboard Shortcuts (Modo Command)

__TABLE_153_

Buenas prácticas

  • Usar entornos virtuales: Trabajar siempre en entornos aislados (conda o venv) para gestionar dependencias y evitar conflictos entre proyectos.

  • Restablece el núcleo regional: Reinicie los núcleos periódicamente durante largas sesiones para aclarar la memoria y garantizar la reproducibilidad. Utilice "Restart Kernel y Ejecutar todas las celdas" para verificar la orden de ejecución de notebook.

  • ** Integración de Control de Versión**: Guardar cuadernos en Git pero utilizar .gitignore para excluir los archivos de control (.ipynb_checkpoints/_). Considere usar nbstripout para eliminar la salida antes de comprometerse.

  • Acceso remoto seguro: Al exponer a distancia JupyterLab, siempre utilice contraseñas o fichas fuertes, active HTTPS con certificados SSL, y considere el uso de túneles SSH o VPN para mayor seguridad.

  • Resource Management: Configure kernel culling for idle kernels para liberar la memoria, especialmente en servidores compartidos. Establecer valores de tiempo apropiados basados en la duración típica del flujo de trabajo.

Organización de códigos móviles: Mantenga los cuadernos enfocados en análisis específicos. Extraer funciones reutilizables en módulos separados .py y importarlas, en lugar de duplicar código en los cuadernos.

  • Habitos de documentación: Use células de marcado de forma liberal para documentar su proceso de pensamiento, metodología y hallazgos. Incluir dependencias de orden de ejecución celular y tiempo de ejecución esperado para células de larga duración.

  • Disciplina de emergencia: Sólo instalamos las extensiones necesarias para evitar conflictos hinchables y potenciales. Actualizar regularmente extensiones y reconstruir JupyterLab después de actualizaciones.

Troubleshooting

Issue Solution
"Port 8888 is already in use" Use different port: INLINE_CODE_104 or stop existing server: INLINE_CODE_105
Cannot connect to kernel Restart kernel from Kernel menu, or restart JupyterLab server. Check INLINE_CODE_106 for valid kernels.
"IOPub data rate exceeded" Increase limit: INLINE_CODE_107 or add to config file.
Extensions not loading Rebuild JupyterLab: INLINE_CODE_108. Check compatibility with INLINE_CODE_109.
Notebook won't save Check file permissions, disk space, and that server has write access. Look for INLINE_CODE_110 directory issues.
ModuleNotFoundError in notebook Ensure kernel is using correct environment. Reinstall ipykernel in target environment: INLINE_CODE_111
High memory usage Enable kernel culling in config, restart unused kernels, or use INLINE_CODE_112 magic command to clear variables.
Slow notebook loading Clear output of large notebooks: INLINE_CODE_113. Reduce cell output size.
Token/password not working Regenerate token: INLINE_CODE_114. Check INLINE_CODE_115 for conflicts.
"403 Forbidden" errors Disable XSRF check temporarily: INLINE_CODE_116 (not recommended for production).
Extension installation fails Update Node.js: INLINE_CODE_117 or use system package manager. Clear npm cache: INLINE_CODE_118.
Kernel dies immediately Check kernel logs: INLINE_CODE_119 to find log location. May indicate missing dependencies or memory issues.

Mandos mágicos útiles (en Cuadernos)

__TABLE_155_ _ %reset_ ← Limpiar todas las variables del espacio de nombres