From e07ae86a14b35c47b5817aea29cf05eed43d92cf Mon Sep 17 00:00:00 2001 From: Matthias Bussonnier Date: Mon, 23 Jan 2023 15:04:56 +0100 Subject: [PATCH] Expose session start file in __file__. Following jupyter-server/jupyter_server#1100, this expose the value of JUPYTER_SESSION_NAME environment variable as `__file__`. In _most_ cases, this should reflect the notebook file that correspond to current kernel. It is not set when the env variable is not set. And it represent the name of file at the time the session was created, it will not reflect renaming of the file. We could support renaming, but that would require the frontend to send the name of the current file; this would be helpful when we have multiple frontends/documents connected to the same kernel, but this would be out of scope for this PR and a longer discussion to have. --- ipykernel/ipkernel.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/ipykernel/ipkernel.py b/ipykernel/ipkernel.py index a4b975a4b..6acc48725 100644 --- a/ipykernel/ipkernel.py +++ b/ipykernel/ipkernel.py @@ -3,6 +3,7 @@ import asyncio import builtins import getpass +import os import signal import sys import threading @@ -126,6 +127,11 @@ def __init__(self, **kwargs): compiler_class=XCachingCompiler, ) self.shell.displayhook.session = self.session + + jupyter_session_name = os.environ.get('JPY_SESSION_NAME') + if jupyter_session_name: + self.shell.user_ns['__file__'] = jupyter_session_name + self.shell.displayhook.pub_socket = self.iopub_socket self.shell.displayhook.topic = self._topic("execute_result") self.shell.display_pub.session = self.session