Last active
October 2, 2024 19:00
-
-
Save algal/a490024ad088de1b857531c83abef0a0 to your computer and use it in GitHub Desktop.
Python script to open a notebook in your local browser, no matter where the server or notebook is
This file contains 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
#!/usr/bin/env python3 | |
import os, os.path, sys, urllib.parse, base64, subprocess | |
def on_iterm2(): return 'ITERM_SESSION_ID' in os.environ or os.environ.get('LC_TERMINAL','') == 'iTerm2' | |
def on_macOS(): return sys.platform == 'darwin' | |
def on_remote_host(): return 'SSH_CLIENT' in os.environ or 'SSH_TTY' in os.environ | |
def openurl(url): | |
"Opens a URL with `open` on macOS or with iTerm2 control codes if needed" | |
if on_macOS(): | |
subprocess.run(["open",url]) | |
elif on_iterm2(): | |
b64_encoded_url=base64.b64encode(url.encode()).decode().rstrip('\n') | |
print(f"\033]1337;OpenURL=:{b64_encoded_url}\007") | |
else: | |
print("Can open URLs only when I'm run on macOS or through iTerm2") | |
exit(1) | |
def openjup(path): | |
""" | |
Open dir or nb in Jupyter server on the macOS browser. | |
Works even if the file and server are on linux. | |
Requires iTerm2. | |
""" | |
running_remotely = on_remote_host() | |
if running_remotely: | |
jup_root_url="http://box.local.:9999/nbclassic/notebooks" | |
jup_root_dir=os.path.expanduser("~/gits") | |
else: | |
jup_root_url="http://arrow.local.:9999/nbclassic/notebooks" | |
jup_root_dir=os.path.expanduser("~/workspace/answerai") | |
relpath = os.path.relpath(path, start=jup_root_dir) | |
quote_encoded = urllib.parse.quote(relpath) | |
jup_url=f"{jup_root_url}/{quote_encoded}" | |
openurl(jup_url) | |
openjup(sys.argv[1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment