launcher.py 5.9 KB

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