launcher.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. """Utilities for launching kernels"""
  2. # Copyright (c) Jupyter Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. import os
  5. import sys
  6. import warnings
  7. from subprocess import PIPE, Popen
  8. from typing import Any
  9. from traitlets.log import get_logger
  10. def launch_kernel(
  11. cmd: list[str],
  12. stdin: int | None = None,
  13. stdout: int | None = None,
  14. stderr: int | None = None,
  15. env: dict[str, str] | None = None,
  16. independent: bool = False,
  17. cwd: str | None = None,
  18. **kw: Any,
  19. ) -> Popen:
  20. """Launches a localhost kernel, binding to the specified ports.
  21. Parameters
  22. ----------
  23. cmd : Popen list,
  24. A string of Python code that imports and executes a kernel entry point.
  25. stdin, stdout, stderr : optional (default None)
  26. Standards streams, as defined in subprocess.Popen.
  27. env: dict, optional
  28. Environment variables passed to the kernel
  29. independent : bool, optional (default False)
  30. If set, the kernel process is guaranteed to survive if this process
  31. dies. If not set, an effort is made to ensure that the kernel is killed
  32. when this process dies. Note that in this case it is still good practice
  33. to kill kernels manually before exiting.
  34. cwd : path, optional
  35. The working dir of the kernel process (default: cwd of this process).
  36. **kw: optional
  37. Additional arguments for Popen
  38. Returns
  39. -------
  40. Popen instance for the kernel subprocess
  41. """
  42. # Popen will fail (sometimes with a deadlock) if stdin, stdout, and stderr
  43. # are invalid. Unfortunately, there is in general no way to detect whether
  44. # they are valid. The following two blocks redirect them to (temporary)
  45. # pipes in certain important cases.
  46. # If this process has been backgrounded, our stdin is invalid. Since there
  47. # is no compelling reason for the kernel to inherit our stdin anyway, we'll
  48. # place this one safe and always redirect.
  49. redirect_in = True
  50. _stdin = PIPE if stdin is None else stdin
  51. # If this process in running on pythonw, we know that stdin, stdout, and
  52. # stderr are all invalid.
  53. redirect_out = sys.executable.endswith("pythonw.exe")
  54. _stdout: Any
  55. _stderr: Any
  56. if redirect_out:
  57. blackhole = open(os.devnull, "w") # noqa
  58. _stdout = blackhole if stdout is None else stdout
  59. _stderr = blackhole if stderr is None else stderr
  60. else:
  61. _stdout, _stderr = stdout, stderr
  62. env = env if (env is not None) else os.environ.copy()
  63. kwargs = kw.copy()
  64. main_args = {
  65. "stdin": _stdin,
  66. "stdout": _stdout,
  67. "stderr": _stderr,
  68. "cwd": cwd,
  69. "env": env,
  70. }
  71. kwargs.update(main_args)
  72. # Spawn a kernel.
  73. if sys.platform == "win32":
  74. if cwd:
  75. kwargs["cwd"] = cwd
  76. from .win_interrupt import create_interrupt_event
  77. # Create a Win32 event for interrupting the kernel
  78. # and store it in an environment variable.
  79. interrupt_event = create_interrupt_event()
  80. env["JPY_INTERRUPT_EVENT"] = str(interrupt_event)
  81. # deprecated old env name:
  82. env["IPY_INTERRUPT_EVENT"] = env["JPY_INTERRUPT_EVENT"]
  83. try:
  84. from _winapi import (
  85. CREATE_NEW_PROCESS_GROUP,
  86. DUPLICATE_SAME_ACCESS,
  87. DuplicateHandle,
  88. GetCurrentProcess,
  89. )
  90. except: # noqa
  91. from _subprocess import (
  92. CREATE_NEW_PROCESS_GROUP,
  93. DUPLICATE_SAME_ACCESS,
  94. DuplicateHandle,
  95. GetCurrentProcess,
  96. )
  97. # create a handle on the parent to be inherited
  98. if independent:
  99. kwargs["creationflags"] = CREATE_NEW_PROCESS_GROUP
  100. else:
  101. pid = GetCurrentProcess()
  102. handle = DuplicateHandle(
  103. pid,
  104. pid,
  105. pid,
  106. 0,
  107. True,
  108. DUPLICATE_SAME_ACCESS, # Inheritable by new processes.
  109. )
  110. env["JPY_PARENT_PID"] = str(int(handle))
  111. # Prevent creating new console window on pythonw
  112. if redirect_out:
  113. kwargs["creationflags"] = (
  114. kwargs.setdefault("creationflags", 0) | 0x08000000
  115. ) # CREATE_NO_WINDOW
  116. # Avoid closing the above parent and interrupt handles.
  117. # close_fds is True by default on Python >=3.7
  118. # or when no stream is captured on Python <3.7
  119. # (we always capture stdin, so this is already False by default on <3.7)
  120. kwargs["close_fds"] = False
  121. else:
  122. # Create a new session.
  123. # This makes it easier to interrupt the kernel,
  124. # because we want to interrupt the whole process group.
  125. # We don't use setpgrp, which is known to cause problems for kernels starting
  126. # certain interactive subprocesses, such as bash -i.
  127. kwargs["start_new_session"] = True
  128. if not independent:
  129. env["JPY_PARENT_PID"] = str(os.getpid())
  130. try:
  131. # Allow to use ~/ in the command or its arguments
  132. cmd = [os.path.expanduser(s) for s in cmd]
  133. proc = Popen(cmd, **kwargs) # noqa
  134. except Exception as ex:
  135. try:
  136. msg = "Failed to run command:\n{}\n PATH={!r}\n with kwargs:\n{!r}\n"
  137. # exclude environment variables,
  138. # which may contain access tokens and the like.
  139. without_env = {key: value for key, value in kwargs.items() if key != "env"}
  140. msg = msg.format(cmd, env.get("PATH", os.defpath), without_env)
  141. get_logger().error(msg)
  142. except Exception as ex2: # Don't let a formatting/logger issue lead to the wrong exception
  143. warnings.warn(f"Failed to run command: '{cmd}' due to exception: {ex}", stacklevel=2)
  144. warnings.warn(
  145. f"The following exception occurred handling the previous failure: {ex2}",
  146. stacklevel=2,
  147. )
  148. raise ex
  149. if sys.platform == "win32":
  150. # Attach the interrupt event to the Popen object so it can be used later.
  151. proc.win32_interrupt_event = interrupt_event
  152. # Clean up pipes created to work around Popen bug.
  153. if redirect_in and stdin is None:
  154. assert proc.stdin is not None
  155. proc.stdin.close()
  156. return proc
  157. __all__ = [
  158. "launch_kernel",
  159. ]