Skip to content

ipython

Class info

Classes

Name Children Inherits
BaseIPythonWidget
prettyqt.ipython.baseipythonwidget
Convenience class for a live IPython console widget running out-of-process.
InProcessIPythonWidget
prettyqt.ipython.inprocessipythonwidget
Convenience class for a live IPython console widget.
    OutOfProcessIPythonWidget
    prettyqt.ipython.outofprocessipythonwidget
    Convenience class for a live IPython console widget running out-of-process.

      🛈 DocStrings

      BaseIPythonWidget

      Bases: RichJupyterWidget, WidgetMixin

      Convenience class for a live IPython console widget running out-of-process.

      Source code in prettyqt/ipython/baseipythonwidget.py
      class BaseIPythonWidget(RichJupyterWidget, widgets.WidgetMixin):
          """Convenience class for a live IPython console widget running out-of-process."""
      
          code_executed = core.Signal(str)
      
          def __init__(self, *args, **kwargs):
              kwargs.setdefault("gui_completion", "droplist")
              kwargs.setdefault("kind", "rich")
              kwargs.setdefault("paging", "vsplit")
              super().__init__(*args, **kwargs)
              self.banner = "IPython Console"
              self.font_size = 6
              # self.gui_completion = "droplist"
              widgets.Application.call_on_exit(self.shutdown)
              # self.exit_requested.connect(self.shutdown)
      
              widgets.Application.styleHints().colorSchemeChanged.connect(
                  self.adjust_style_to_palette
              )
              self.adjust_style_to_palette()
      
          @classmethod
          def setup_example(cls):
              return None
      
          def set_completion_mode(self, mode: CompletionmodeStr):
              self._set_completion_widget(mode)
      
          def get_completion_mode(self) -> CompletionmodeStr:
              return self.gui_completion  # type: ignore
      
          @property
          def texteditor(self) -> widgets.QPlainTextEdit:  # to shut up linters
              return self._control  # type: ignore
      
          def adjust_style_to_palette(self):
              """Adjust coloring of the terminal to current palette."""
              pal = widgets.Application.get_palette()
              style = "linux" if pal.is_dark() else "lightbg"
              self.set_default_style(style)
      
          def shutdown(self):
              """Stop IPython and cleanup."""
              return NotImplemented
      
          def buffer(self) -> str:
              """Get current code block."""
              return self.input_buffer
      
          def set_buffer(self, code: str) -> None:
              """Set code string to Jupyter QtConsole buffer."""
              self.input_buffer = ""
              if not isinstance(code, str):
                  msg = f"Cannot set {type(code)}."
                  raise ValueError(msg)  # noqa: TRY004
              cursor = self.texteditor.textCursor()
              lines = code.split("\n")
              for line in lines[:-1]:
                  cursor.insertText(line + "\n")
                  self._insert_continuation_prompt(cursor)  # insert "...:"
              cursor.insertText(lines[-1])
      
          def insert_text(self, text: str) -> None:
              cursor = self.texteditor.textCursor()
              cursor.insertText(text)
      
          def set_temp_text(self, text: str) -> None:
              cursor = self.texteditor.textCursor()
              cursor.removeSelectedText()
              pos = cursor.position()
              cursor.insertText(text)
              cursor.setPosition(pos)
              cursor.setPosition(pos + len(text), gui.TextCursor.MoveMode.KeepAnchor)
              self.texteditor.setTextCursor(cursor)
      
          def get_selected_text(self) -> str:
              """Return the selected text."""
              cursor = self.texteditor.textCursor()
              return cursor.selection().toPlainText()
      
          def clear(self):
              """Clear the terminal."""
              self.texteditor.clear()
      
          def print_text(self, text: str, before_prompt: bool = False):
              """Print some plain text to the console."""
              self._append_plain_text(text, before_prompt=before_prompt)
      
          def execute(
              self,
              source: str | None = None,
              hidden: bool = False,
              interactive: bool = False,
          ):
              """Execute a command in the frame of the console widget."""
              if source is None:
                  source = self.input_buffer
              super().execute(source=source, hidden=hidden, interactive=interactive)
              self.code_executed.emit(source)
      
          completion_mode = core.Property(
              str,
              get_completion_mode,
              set_completion_mode,
              doc="Completion mode for the widget",
          )
      

      adjust_style_to_palette()

      Adjust coloring of the terminal to current palette.

      Source code in prettyqt/ipython/baseipythonwidget.py
      def adjust_style_to_palette(self):
          """Adjust coloring of the terminal to current palette."""
          pal = widgets.Application.get_palette()
          style = "linux" if pal.is_dark() else "lightbg"
          self.set_default_style(style)
      

      buffer() -> str

      Get current code block.

      Source code in prettyqt/ipython/baseipythonwidget.py
      def buffer(self) -> str:
          """Get current code block."""
          return self.input_buffer
      

      clear()

      Clear the terminal.

      Source code in prettyqt/ipython/baseipythonwidget.py
      def clear(self):
          """Clear the terminal."""
          self.texteditor.clear()
      

      execute(source: str | None = None, hidden: bool = False, interactive: bool = False)

      Execute a command in the frame of the console widget.

      Source code in prettyqt/ipython/baseipythonwidget.py
      def execute(
          self,
          source: str | None = None,
          hidden: bool = False,
          interactive: bool = False,
      ):
          """Execute a command in the frame of the console widget."""
          if source is None:
              source = self.input_buffer
          super().execute(source=source, hidden=hidden, interactive=interactive)
          self.code_executed.emit(source)
      

      get_selected_text() -> str

      Return the selected text.

      Source code in prettyqt/ipython/baseipythonwidget.py
      def get_selected_text(self) -> str:
          """Return the selected text."""
          cursor = self.texteditor.textCursor()
          return cursor.selection().toPlainText()
      

      print_text(text: str, before_prompt: bool = False)

      Print some plain text to the console.

      Source code in prettyqt/ipython/baseipythonwidget.py
      def print_text(self, text: str, before_prompt: bool = False):
          """Print some plain text to the console."""
          self._append_plain_text(text, before_prompt=before_prompt)
      

      set_buffer(code: str) -> None

      Set code string to Jupyter QtConsole buffer.

      Source code in prettyqt/ipython/baseipythonwidget.py
      def set_buffer(self, code: str) -> None:
          """Set code string to Jupyter QtConsole buffer."""
          self.input_buffer = ""
          if not isinstance(code, str):
              msg = f"Cannot set {type(code)}."
              raise ValueError(msg)  # noqa: TRY004
          cursor = self.texteditor.textCursor()
          lines = code.split("\n")
          for line in lines[:-1]:
              cursor.insertText(line + "\n")
              self._insert_continuation_prompt(cursor)  # insert "...:"
          cursor.insertText(lines[-1])
      

      shutdown()

      Stop IPython and cleanup.

      Source code in prettyqt/ipython/baseipythonwidget.py
      def shutdown(self):
          """Stop IPython and cleanup."""
          return NotImplemented
      

      InProcessIPythonWidget

      Bases: BaseIPythonWidget

      Convenience class for a live IPython console widget.

      Source code in prettyqt/ipython/inprocessipythonwidget.py
      class InProcessIPythonWidget(ipython.BaseIPythonWidget):
          """Convenience class for a live IPython console widget."""
      
          evaluated = core.Signal(object)
      
          def __init__(self, *args, **kwargs):
              super().__init__(*args, **kwargs)
              self.kernel_manager = QtInProcessKernelManager()
              self.kernel_manager.start_kernel(show_banner=False)
      
              self.kernel_manager.kernel.log.setLevel(logging.CRITICAL)
              self.kernel_manager.kernel.gui = "qt"
              if importlib.util.find_spec("matplotlib"):
                  self.kernel_manager.kernel.shell.enable_matplotlib(gui="inline")
              self.kernel_client = self.kernel_manager.client()
              self.kernel_client.start_channels()
      
          def shutdown(self):
              logger.info("shutting down IPython kernel...")
              assert self.kernel_manager
              assert self.kernel_client
              self.kernel_client.stop_channels()
              self.kernel_manager.shutdown_kernel()
              logger.info("shutdown successful.")
      
          def push_vars(self, var_dict):
              """Send python objects to IPYthon namespace.
      
              Given a dictionary containing name / value pairs, push those variables
              to the IPython console widget.
              """
              assert self.kernel_manager
              self.kernel_manager.kernel.shell.push(var_dict)
              for key in var_dict:
                  self._append_plain_text(f'\nadded "{key}" object to namespace\n', True)
      
          def eval(self, obj_name):
              """Pull object with name *obj_name from namespace."""
              assert self.kernel_manager
              try:
                  data = self.kernel_manager.kernel.shell.ev(obj_name)
              except NameError:
                  logger.exception("Exception when evaluating %s", obj_name)
                  return None
              self._append_plain_text(f'\nread "{obj_name}" object to namespace\n', True)
              self.evaluated.emit(data)
              return data
      

      eval(obj_name)

      Pull object with name *obj_name from namespace.

      Source code in prettyqt/ipython/inprocessipythonwidget.py
      def eval(self, obj_name):
          """Pull object with name *obj_name from namespace."""
          assert self.kernel_manager
          try:
              data = self.kernel_manager.kernel.shell.ev(obj_name)
          except NameError:
              logger.exception("Exception when evaluating %s", obj_name)
              return None
          self._append_plain_text(f'\nread "{obj_name}" object to namespace\n', True)
          self.evaluated.emit(data)
          return data
      

      push_vars(var_dict)

      Send python objects to IPYthon namespace.

      Given a dictionary containing name / value pairs, push those variables to the IPython console widget.

      Source code in prettyqt/ipython/inprocessipythonwidget.py
      def push_vars(self, var_dict):
          """Send python objects to IPYthon namespace.
      
          Given a dictionary containing name / value pairs, push those variables
          to the IPython console widget.
          """
          assert self.kernel_manager
          self.kernel_manager.kernel.shell.push(var_dict)
          for key in var_dict:
              self._append_plain_text(f'\nadded "{key}" object to namespace\n', True)
      

      OutOfProcessIPythonWidget

      Bases: BaseIPythonWidget

      Convenience class for a live IPython console widget running out-of-process.

      Source code in prettyqt/ipython/outofprocessipythonwidget.py
      class OutOfProcessIPythonWidget(ipython.BaseIPythonWidget):
          """Convenience class for a live IPython console widget running out-of-process."""
      
          def __init__(self, *args, **kwargs):
              super().__init__(*args, **kwargs)
              temp_path = core.Dir.get_temp_path()
              self.connection_file = temp_path / f"connection-{os.getpid()}.json"
              self.p = multiprocessing.Process(target=run_server, args=(self.connection_file,))
              self.p.daemon = True
              self.p.start()
              logger.info("waiting for connection file creation....")
              for _ in range(500):
                  if self.connection_file.exists() and self.connection_file.stat().st_size > 0:
                      break
                  widgets.Application.sleep(0.1)
              else:
                  raise FileNotFoundError(self.connection_file)
              logger.info("Connection file found. Opening channels.")
              kernel_client = QtKernelClient(connection_file=os.fspath(self.connection_file))
              kernel_client.load_connection_file()  # can throw FileNotFoundError
              kernel_client.start_channels()
              self.kernel_client = kernel_client
      
          def shutdown(self):
              """Stop IPython server process and clean up."""
              logger.info("shutting down IPython MP kernel")
              assert self.kernel_client, "Kernel client not initialized"
              self.kernel_client.stop_channels()
              self.kernel_client.shutdown()
              self.p.terminate()
              self.connection_file.unlink(missing_ok=True)
              logger.info("shutdown successful.")
      

      shutdown()

      Stop IPython server process and clean up.

      Source code in prettyqt/ipython/outofprocessipythonwidget.py
      def shutdown(self):
          """Stop IPython server process and clean up."""
          logger.info("shutting down IPython MP kernel")
          assert self.kernel_client, "Kernel client not initialized"
          self.kernel_client.stop_channels()
          self.kernel_client.shutdown()
          self.p.terminate()
          self.connection_file.unlink(missing_ok=True)
          logger.info("shutdown successful.")