connect.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. """Connection file-related utilities for the kernel"""
  2. # Copyright (c) IPython Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. from __future__ import annotations
  5. import json
  6. import sys
  7. from subprocess import PIPE, Popen
  8. from typing import TYPE_CHECKING, Any
  9. import jupyter_client
  10. from jupyter_client import write_connection_file
  11. if TYPE_CHECKING:
  12. from ipykernel.kernelapp import IPKernelApp
  13. def get_connection_file(app: IPKernelApp | None = None) -> str:
  14. """Return the path to the connection file of an app
  15. Parameters
  16. ----------
  17. app : IPKernelApp instance [optional]
  18. If unspecified, the currently running app will be used
  19. """
  20. from traitlets.utils import filefind
  21. if app is None:
  22. from ipykernel.kernelapp import IPKernelApp
  23. if not IPKernelApp.initialized():
  24. msg = "app not specified, and not in a running Kernel"
  25. raise RuntimeError(msg)
  26. app = IPKernelApp.instance()
  27. return filefind(app.connection_file, [".", app.connection_dir])
  28. def _find_connection_file(connection_file):
  29. """Return the absolute path for a connection file
  30. - If nothing specified, return current Kernel's connection file
  31. - Otherwise, call jupyter_client.find_connection_file
  32. """
  33. if connection_file is None:
  34. # get connection file from current kernel
  35. return get_connection_file()
  36. return jupyter_client.find_connection_file(connection_file)
  37. def get_connection_info(
  38. connection_file: str | None = None, unpack: bool = False
  39. ) -> str | dict[str, Any]:
  40. """Return the connection information for the current Kernel.
  41. Parameters
  42. ----------
  43. connection_file : str [optional]
  44. The connection file to be used. Can be given by absolute path, or
  45. IPython will search in the security directory.
  46. If run from IPython,
  47. If unspecified, the connection file for the currently running
  48. IPython Kernel will be used, which is only allowed from inside a kernel.
  49. unpack : bool [default: False]
  50. if True, return the unpacked dict, otherwise just the string contents
  51. of the file.
  52. Returns
  53. -------
  54. The connection dictionary of the current kernel, as string or dict,
  55. depending on `unpack`.
  56. """
  57. cf = _find_connection_file(connection_file)
  58. with open(cf) as f:
  59. info_str = f.read()
  60. if unpack:
  61. info = json.loads(info_str)
  62. # ensure key is bytes:
  63. info["key"] = info.get("key", "").encode()
  64. return info # type:ignore[no-any-return]
  65. return info_str
  66. def connect_qtconsole(
  67. connection_file: str | None = None, argv: list[str] | None = None
  68. ) -> Popen[Any]:
  69. """Connect a qtconsole to the current kernel.
  70. This is useful for connecting a second qtconsole to a kernel, or to a
  71. local notebook.
  72. Parameters
  73. ----------
  74. connection_file : str [optional]
  75. The connection file to be used. Can be given by absolute path, or
  76. IPython will search in the security directory.
  77. If run from IPython,
  78. If unspecified, the connection file for the currently running
  79. IPython Kernel will be used, which is only allowed from inside a kernel.
  80. argv : list [optional]
  81. Any extra args to be passed to the console.
  82. Returns
  83. -------
  84. :class:`subprocess.Popen` instance running the qtconsole frontend
  85. """
  86. argv = [] if argv is None else argv
  87. cf = _find_connection_file(connection_file)
  88. cmd = ";".join(["from qtconsole import qtconsoleapp", "qtconsoleapp.main()"])
  89. kwargs: dict[str, Any] = {}
  90. # Launch the Qt console in a separate session & process group, so
  91. # interrupting the kernel doesn't kill it.
  92. kwargs["start_new_session"] = True
  93. return Popen(
  94. [sys.executable, "-c", cmd, "--existing", cf, *argv],
  95. stdout=PIPE,
  96. stderr=PIPE,
  97. close_fds=(sys.platform != "win32"),
  98. **kwargs,
  99. )
  100. __all__ = [
  101. "connect_qtconsole",
  102. "get_connection_file",
  103. "get_connection_info",
  104. "write_connection_file",
  105. ]