Pular para o conteúdo

JupyterLab Cheatsheet

JupyterLab Cheatsheet

Installation

PlatformCommand
Ubuntu/Debian (pip)sudo apt-get update && sudo apt-get install python3 python3-pip
pip3 install jupyterlab
Ubuntu/Debian (conda)conda install -c conda-forge jupyterlab
macOS (Homebrew)brew install python3
pip3 install jupyterlab
macOS (conda)brew install --cask anaconda
conda install -c conda-forge jupyterlab
Windows (pip)pip install jupyterlab
Windows (Anaconda)Install Anaconda, then: conda install -c conda-forge jupyterlab
Dockerdocker pull jupyter/datascience-notebook
docker run -p 8888:8888 jupyter/datascience-notebook
Upgradepip install --upgrade jupyterlab
Verify Installationjupyter lab --version

Basic Commands

CommandDescription
jupyter labStart JupyterLab server (opens browser automatically)
jupyter lab --port=8889Start JupyterLab on specific port
jupyter lab --no-browserStart without opening browser
jupyter lab --notebook-dir=/path/to/dirStart with specific working directory
jupyter lab listList all running JupyterLab servers
jupyter lab stop 8888Stop JupyterLab server on port 8888
jupyter lab --versionDisplay JupyterLab version
jupyter --pathsShow all Jupyter paths (config, data, runtime)
jupyter lab --generate-configGenerate default configuration file
jupyter lab passwordSet password for JupyterLab server
jupyter lab cleanClean up JupyterLab installation
jupyter kernelspec listList all available kernels
jupyter labextension listList all installed extensions
jupyter trust notebook.ipynbTrust a notebook (allow JavaScript)
jupyter lab --helpDisplay help and all available options

Kernel Management

CommandDescription
jupyter kernelspec listList all installed kernels
python -m ipykernel install --user --name myenvInstall Python kernel from environment
python -m ipykernel install --user --name myenv --display-name "Python (myenv)"Install kernel with custom display name
jupyter kernelspec uninstall myenvRemove a kernel
R -e "install.packages('IRkernel'); IRkernel::installspec()"Install R kernel
julia -e 'using Pkg; Pkg.add("IJulia")'Install Julia kernel
conda install -c conda-forge ipykernelInstall kernel support in conda environment
jupyter kernelspec remove kernel-nameRemove kernel specification

Notebook Conversion (nbconvert)

CommandDescription
jupyter nbconvert --to html notebook.ipynbConvert notebook to HTML
jupyter nbconvert --to pdf notebook.ipynbConvert notebook to PDF
jupyter nbconvert --to python notebook.ipynbConvert notebook to Python script
jupyter nbconvert --to markdown notebook.ipynbConvert notebook to Markdown
jupyter nbconvert --to slides notebook.ipynbConvert notebook to reveal.js slides
jupyter nbconvert --to notebook --execute notebook.ipynbExecute notebook and save output
jupyter nbconvert --execute --to html notebook.ipynbExecute and convert to HTML
jupyter nbconvert --clear-output notebook.ipynbClear all cell outputs
jupyter nbconvert --to html *.ipynbBatch convert all notebooks in directory
jupyter nbconvert --to pdf --execute notebook.ipynbExecute notebook and export to PDF

Extension Management

CommandDescription
jupyter labextension listList all installed extensions
jupyter labextension install @jupyterlab/tocInstall table of contents extension
jupyter labextension uninstall @jupyterlab/tocUninstall an extension
jupyter labextension update @jupyterlab/tocUpdate specific extension
jupyter labextension disable @jupyterlab/tocDisable extension without uninstalling
jupyter labextension enable @jupyterlab/tocEnable previously disabled extension
jupyter lab buildRebuild JupyterLab (required after extension changes)
jupyter labextension check-updatesCheck for extension updates
jupyter labextension develop . --overwriteLink extension for development

Advanced Server Configuration

CommandDescription
jupyter lab --ip=0.0.0.0Allow connections from any IP address
jupyter lab --ip=0.0.0.0 --no-browserStart server for remote access
jupyter lab --ServerApp.token='mytoken'Set custom authentication token
jupyter lab --ServerApp.allow_origin='*'Allow requests from any origin (CORS)
jupyter lab --ServerApp.allow_remote_access=TrueEnable remote access explicitly
jupyter lab --ServerApp.iopub_data_rate_limit=1000000000Increase data rate limit for large outputs
jupyter lab --ServerApp.max_body_size=524288000Increase max upload size (500MB)
jupyter lab --debugStart in debug mode with verbose logging
jupyter lab --dev-mode --watchStart in development mode with auto-rebuild
jupyter lab --show-configDisplay current configuration
jupyter lab --ServerApp.base_url='/jupyter'Set custom base URL (for reverse proxy)
jupyter lab --ServerApp.allow_root=TrueAllow running as root user (not recommended)

Workspace Management

CommandDescription
jupyter lab workspaces export > workspace.jsonExport current workspace layout
jupyter lab workspaces import workspace.jsonImport workspace layout
jupyter lab workspaces listList all saved workspaces
jupyter lab workspaces delete workspace-nameDelete a workspace

Configuration

Main Configuration File

Location: ~/.jupyter/jupyter_lab_config.py (Linux/macOS) or %USERPROFILE%\.jupyter\jupyter_lab_config.py (Windows)

Generate default configuration:

jupyter lab --generate-config

Common Configuration Options

# ~/.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

User Settings Directory

Location: ~/.jupyter/lab/user-settings/ (Linux/macOS) or %APPDATA%\jupyter\lab\user-settings\ (Windows)

Example theme settings (@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'))"

Then add to 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 (Command Mode)

ShortcutAction
EnterEnter edit mode
Shift + EnterRun cell and select below
Ctrl + EnterRun selected cells
Alt + EnterRun cell and insert below
AInsert cell above
BInsert cell below
DDDelete selected cell
ZUndo cell deletion
MChange cell to Markdown
YChange cell to Code
Shift + MMerge selected cells
Ctrl + SSave notebook
Shift + LToggle line numbers
00Restart kernel

Best Practices

  • Use Virtual Environments: Always work within isolated environments (conda or venv) to manage dependencies and avoid conflicts between projects.

  • Regular Kernel Restarts: Restart kernels periodically during long sessions to clear memory and ensure reproducibility. Use “Restart Kernel and Run All Cells” to verify notebook execution order.

  • Version Control Integration: Store notebooks in Git but use .gitignore to exclude checkpoint files (.ipynb_checkpoints/). Consider using nbstripout to remove output before committing.

  • Secure Remote Access: When exposing JupyterLab remotely, always use strong passwords or tokens, enable HTTPS with SSL certificates, and consider using SSH tunneling or VPN for additional security.

  • Resource Management: Configure kernel culling for idle kernels to free up memory, especially on shared servers. Set appropriate timeout values based on typical workflow duration.

  • Modular Code Organization: Keep notebooks focused on specific analyses. Extract reusable functions into separate .py modules and import them, rather than duplicating code across notebooks.

  • Documentation Habits: Use Markdown cells liberally to document your thought process, methodology, and findings. Include cell execution order dependencies and expected runtime for long-running cells.

  • Extension Discipline: Only install necessary extensions to avoid bloat and potential conflicts. Regularly update extensions and rebuild JupyterLab after updates.

Troubleshooting

IssueSolution
”Port 8888 is already in use”Use different port: jupyter lab --port=8889 or stop existing server: jupyter lab stop 8888
Cannot connect to kernelRestart kernel from Kernel menu, or restart JupyterLab server. Check jupyter kernelspec list for valid kernels.
”IOPub data rate exceeded”Increase limit: jupyter lab --ServerApp.iopub_data_rate_limit=1000000000 or add to config file.
Extensions not loadingRebuild JupyterLab: jupyter lab build. Check compatibility with jupyter labextension list.
Notebook won’t saveCheck file permissions, disk space, and that server has write access. Look for .ipynb_checkpoints directory issues.
ModuleNotFoundError in notebookEnsure kernel is using correct environment. Reinstall ipykernel in target environment: python -m ipykernel install --user --name envname
High memory usageEnable kernel culling in config, restart unused kernels, or use %reset magic command to clear variables.
Slow notebook loadingClear output of large notebooks: jupyter nbconvert --clear-output notebook.ipynb. Reduce cell output size.
Token/password not workingRegenerate token: jupyter lab password. Check ~/.jupyter/jupyter_server_config.json for conflicts.
”403 Forbidden” errorsDisable XSRF check temporarily: jupyter lab --ServerApp.disable_check_xsrf=True (not recommended for production).
Extension installation failsUpdate Node.js: conda install nodejs or use system package manager. Clear npm cache: npm cache clean --force.
Kernel dies immediatelyCheck kernel logs: jupyter --runtime-dir to find log location. May indicate missing dependencies or memory issues.

Useful Magic Commands (In Notebooks)

Magic CommandDescription
%lsmagicList all available magic commands
%time statementTime execution of single statement
%%timeTime execution of entire cell
%timeit statementTime repeated execution for average
%matplotlib inlineDisplay plots inline in notebook
%load file.pyLoad external Python file into cell
%run script.pyExecute external Python script
%pwdPrint current working directory
%cd /pathChange working directory
%envList environment variables
%pip install packageInstall package in current kernel
%conda install packageInstall package via conda
%%bashExecute cell as bash script
%debugActivate interactive debugger