popen_spawn_win32.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. import os
  2. import msvcrt
  3. import signal
  4. import sys
  5. import _winapi
  6. from .context import reduction, get_spawning_popen, set_spawning_popen
  7. from . import spawn
  8. from . import util
  9. __all__ = ['Popen']
  10. #
  11. #
  12. #
  13. TERMINATE = 0x10000
  14. WINEXE = (sys.platform == 'win32' and getattr(sys, 'frozen', False))
  15. WINSERVICE = sys.executable.lower().endswith("pythonservice.exe")
  16. def _path_eq(p1, p2):
  17. return p1 == p2 or os.path.normcase(p1) == os.path.normcase(p2)
  18. WINENV = not _path_eq(sys.executable, sys._base_executable)
  19. def _close_handles(*handles):
  20. for handle in handles:
  21. _winapi.CloseHandle(handle)
  22. #
  23. # We define a Popen class similar to the one from subprocess, but
  24. # whose constructor takes a process object as its argument.
  25. #
  26. class Popen(object):
  27. '''
  28. Start a subprocess to run the code of a process object
  29. '''
  30. method = 'spawn'
  31. def __init__(self, process_obj):
  32. prep_data = spawn.get_preparation_data(process_obj._name)
  33. # read end of pipe will be duplicated by the child process
  34. # -- see spawn_main() in spawn.py.
  35. #
  36. # bpo-33929: Previously, the read end of pipe was "stolen" by the child
  37. # process, but it leaked a handle if the child process had been
  38. # terminated before it could steal the handle from the parent process.
  39. rhandle, whandle = _winapi.CreatePipe(None, 0)
  40. wfd = msvcrt.open_osfhandle(whandle, 0)
  41. cmd = spawn.get_command_line(parent_pid=os.getpid(),
  42. pipe_handle=rhandle)
  43. python_exe = spawn.get_executable()
  44. # bpo-35797: When running in a venv, we bypass the redirect
  45. # executor and launch our base Python.
  46. if WINENV and _path_eq(python_exe, sys.executable):
  47. cmd[0] = python_exe = sys._base_executable
  48. env = os.environ.copy()
  49. env["__PYVENV_LAUNCHER__"] = sys.executable
  50. else:
  51. env = None
  52. cmd = ' '.join('"%s"' % x for x in cmd)
  53. with open(wfd, 'wb', closefd=True) as to_child:
  54. # start process
  55. try:
  56. hp, ht, pid, tid = _winapi.CreateProcess(
  57. python_exe, cmd,
  58. None, None, False, 0, env, None, None)
  59. _winapi.CloseHandle(ht)
  60. except:
  61. _winapi.CloseHandle(rhandle)
  62. raise
  63. # set attributes of self
  64. self.pid = pid
  65. self.returncode = None
  66. self._handle = hp
  67. self.sentinel = int(hp)
  68. self.finalizer = util.Finalize(self, _close_handles,
  69. (self.sentinel, int(rhandle)))
  70. # send information to child
  71. set_spawning_popen(self)
  72. try:
  73. reduction.dump(prep_data, to_child)
  74. reduction.dump(process_obj, to_child)
  75. finally:
  76. set_spawning_popen(None)
  77. def duplicate_for_child(self, handle):
  78. assert self is get_spawning_popen()
  79. return reduction.duplicate(handle, self.sentinel)
  80. def wait(self, timeout=None):
  81. if self.returncode is None:
  82. if timeout is None:
  83. msecs = _winapi.INFINITE
  84. else:
  85. msecs = max(0, int(timeout * 1000 + 0.5))
  86. res = _winapi.WaitForSingleObject(int(self._handle), msecs)
  87. if res == _winapi.WAIT_OBJECT_0:
  88. code = _winapi.GetExitCodeProcess(self._handle)
  89. if code == TERMINATE:
  90. code = -signal.SIGTERM
  91. self.returncode = code
  92. return self.returncode
  93. def poll(self):
  94. return self.wait(timeout=0)
  95. def terminate(self):
  96. if self.returncode is None:
  97. try:
  98. _winapi.TerminateProcess(int(self._handle), TERMINATE)
  99. except OSError:
  100. if self.wait(timeout=1.0) is None:
  101. raise
  102. kill = terminate
  103. def close(self):
  104. self.finalizer()