popen_spawn_win32.py 4.5 KB

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