danielfrg / s3contents

Jupyter Notebooks in S3 - Jupyter Contents Manager implementation
Apache License 2.0
248 stars 88 forks source link

How to get the correct path from within the notebook #123

Closed ItamarShDev closed 3 years ago

ItamarShDev commented 3 years ago

I have S3 libraries shared to Jupyter Lab using HybridContentsManager plugin.

I have the following tree: projects/

If I run

import os
os.path.abspath(os.getcwd())

From the notebook that saved in S3, I will always get /home/jovyan

Is there any way to get the full s3 path of the notebook from the notebook?

ItamarShDev commented 3 years ago

I wind up with

import requests
import ipykernel
import re
from notebook.notebookapp import list_running_servers
import os
TOKEN = os.environ['JUPYTERHUB_API_TOKEN']
base_url = next(list_running_servers())['url']
r = requests.get(
    url=base_url + 'api/sessions',
    headers={'Authorization': 'token {}'.format(TOKEN),})
r.raise_for_status()
response = r.json()
kernel_id = re.search('kernel-(.*).json', ipykernel.connect.get_connection_file()).group(1)
notebook_path = {r['kernel']['id']: r['notebook']['path'] for r in response}[kernel_id]
os.environ['current_notebook']=notebook_path
os.environ['current_notebook']