From 845f4fddb8271df8d040cbda9ed327f17310a57a Mon Sep 17 00:00:00 2001 From: Matthias Bussonnier Date: Mon, 7 Mar 2022 15:41:37 +0100 Subject: [PATCH] Capture caller frame of napari.run() when starting the console. Should fix napari/napari#4098 Replaces napari/napari#4140, and see discussion there as well Needs napari/napari#4212 --- napari_console/qt_console.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/napari_console/qt_console.py b/napari_console/qt_console.py index d7acd63..45bef9e 100644 --- a/napari_console/qt_console.py +++ b/napari_console/qt_console.py @@ -13,6 +13,9 @@ from qtpy.QtGui import QColor +from napari.utils.naming import CallerFrame + +from types import FrameType def str_to_rgb(arg): """Convert an rgb string 'rgb(x,y,z)' to a list of ints [x,y,z].""" @@ -55,6 +58,10 @@ def str_to_rgb(arg): asyncio.set_event_loop_policy(WindowsSelectorEventLoopPolicy()) +def _not_napari(n: int, frame: FrameType): + return frame.f_globals.get("__name__", "").startswith("napari") + + class QtConsole(RichJupyterWidget): """Qt view for the console, an integrated iPython terminal in napari. @@ -128,6 +135,7 @@ def __init__(self, viewer: 'napari.viewer.Viewer'): raise ValueError( 'ipython shell not recognized; ' f'got {type(shell)}' ) + self._capture() # Add any user variables user_variables = user_variables or {} self.push(user_variables) @@ -140,6 +148,13 @@ def __init__(self, viewer: 'napari.viewer.Viewer'): # TODO: Try to get console from jupyter to run without a shift click # self.execute_on_complete_input = True + def _capture(self): + """ + Capture variable from first enclosing scope that is not napari + """ + with CallerFrame(_not_napari) as c: + self.push(dict(c.namespace)) + def _update_theme(self, event=None): """Update the napari GUI theme.""" from napari.utils.theme import get_theme, template