Skip to content

Instantly share code, notes, and snippets.

@chuyqa
Created April 7, 2024 05:21
Show Gist options
  • Save chuyqa/f2498f36daa05c76dec990a1e0076a9d to your computer and use it in GitHub Desktop.
Save chuyqa/f2498f36daa05c76dec990a1e0076a9d to your computer and use it in GitHub Desktop.
import json
import IPython
class NotebookInfo:
def __init__(self):
self.ip = IPython.get_ipython()
self._notebook_path = None
self._notebook_content = None
@property
def nbmeta(self):
if not self.ip:
return json.dumps({"error": "IPython kernel not available."})
if not self._notebook_path:
self._notebook_path = self._get_notebook_path()
if not self._notebook_content:
self._notebook_content = self._read_notebook()
self._execution_count = self.ip.execution_count
cell_index = self._get_cell_index_by_execution_count(self._execution_count)
notebook_details = {
"cell": cell_index+1,
"name": self._notebook_path,
"cell_execution_number": self._execution_count
}
return json.dumps(notebook_details)
def _get_notebook_path(self):
connection_file_path = self.ip.config['IPKernelApp']['connection_file']
try:
with open(connection_file_path) as f:
connection_info = json.load(f)
return connection_info.get('jupyter_session', 'Unknown')
except Exception:
return "Unknown"
def _read_notebook(self):
"""Read and cache the notebook content."""
try:
with open(self._notebook_path, 'r', encoding='utf-8') as file:
return json.load(file)
except Exception as e:
print(f"Error reading the notebook file: {e}")
return None
def _get_cell_index_by_execution_count(self, execution_count):
"""Try to find the cell index for a given execution count."""
self._notebook_content = self._read_notebook()
if not self._notebook_content:
return None
for index, cell in enumerate(self._notebook_content.get('cells', [])):
if cell.get('cell_type') == 'code' and cell.get('execution_count') == execution_count:
return index # Return the 0-based index of the cell
return None
notebook_info = NotebookInfo()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment