spawn.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. #
  2. # Code used to start processes when using the spawn or forkserver
  3. # start methods.
  4. #
  5. # multiprocessing/spawn.py
  6. #
  7. # Copyright (c) 2006-2008, R Oudkerk
  8. # Licensed to PSF under a Contributor Agreement.
  9. #
  10. import os
  11. import sys
  12. import runpy
  13. import types
  14. from . import get_start_method, set_start_method
  15. from . import process
  16. from .context import reduction
  17. from . import util
  18. __all__ = ['_main', 'freeze_support', 'set_executable', 'get_executable',
  19. 'get_preparation_data', 'get_command_line', 'import_main_path']
  20. #
  21. # _python_exe is the assumed path to the python executable.
  22. # People embedding Python want to modify it.
  23. #
  24. if sys.platform != 'win32':
  25. WINEXE = False
  26. WINSERVICE = False
  27. else:
  28. WINEXE = getattr(sys, 'frozen', False)
  29. WINSERVICE = sys.executable and sys.executable.lower().endswith("pythonservice.exe")
  30. def set_executable(exe):
  31. global _python_exe
  32. if exe is None:
  33. _python_exe = exe
  34. elif sys.platform == 'win32':
  35. _python_exe = os.fsdecode(exe)
  36. else:
  37. _python_exe = os.fsencode(exe)
  38. def get_executable():
  39. return _python_exe
  40. if WINSERVICE:
  41. set_executable(os.path.join(sys.exec_prefix, 'python.exe'))
  42. else:
  43. set_executable(sys.executable)
  44. #
  45. #
  46. #
  47. def is_forking(argv):
  48. '''
  49. Return whether commandline indicates we are forking
  50. '''
  51. if len(argv) >= 2 and argv[1] == '--multiprocessing-fork':
  52. return True
  53. else:
  54. return False
  55. def freeze_support():
  56. '''
  57. Run code for process object if this in not the main process
  58. '''
  59. if is_forking(sys.argv):
  60. kwds = {}
  61. for arg in sys.argv[2:]:
  62. name, value = arg.split('=')
  63. if value == 'None':
  64. kwds[name] = None
  65. else:
  66. kwds[name] = int(value)
  67. spawn_main(**kwds)
  68. sys.exit()
  69. def get_command_line(**kwds):
  70. '''
  71. Returns prefix of command line used for spawning a child process
  72. '''
  73. if False and getattr(sys, 'frozen', False):
  74. return ([sys.executable, '--multiprocessing-fork'] +
  75. ['%s=%r' % item for item in kwds.items()])
  76. else:
  77. prog = 'from multiprocessing.spawn import spawn_main; spawn_main(%s)'
  78. prog %= ', '.join('%s=%r' % item for item in kwds.items())
  79. opts = util._args_from_interpreter_flags()
  80. exe = get_executable()
  81. return [exe] + opts + ['-c', prog, '--multiprocessing-fork']
  82. def spawn_main(pipe_handle, parent_pid=None, tracker_fd=None):
  83. '''
  84. Run code specified by data received over pipe
  85. '''
  86. assert is_forking(sys.argv), "Not forking"
  87. if sys.platform == 'win32':
  88. import msvcrt
  89. import _winapi
  90. if parent_pid is not None:
  91. source_process = _winapi.OpenProcess(
  92. _winapi.SYNCHRONIZE | _winapi.PROCESS_DUP_HANDLE,
  93. False, parent_pid)
  94. else:
  95. source_process = None
  96. new_handle = reduction.duplicate(pipe_handle,
  97. source_process=source_process)
  98. fd = msvcrt.open_osfhandle(new_handle, os.O_RDONLY)
  99. parent_sentinel = source_process
  100. else:
  101. from . import resource_tracker
  102. resource_tracker._resource_tracker._fd = tracker_fd
  103. fd = pipe_handle
  104. parent_sentinel = os.dup(pipe_handle)
  105. exitcode = _main(fd, parent_sentinel)
  106. sys.exit(exitcode)
  107. def _main(fd, parent_sentinel):
  108. with os.fdopen(fd, 'rb', closefd=True) as from_parent:
  109. process.current_process()._inheriting = True
  110. try:
  111. preparation_data = reduction.pickle.load(from_parent)
  112. prepare(preparation_data)
  113. self = reduction.pickle.load(from_parent)
  114. finally:
  115. del process.current_process()._inheriting
  116. return self._bootstrap(parent_sentinel)
  117. def _check_not_importing_main():
  118. if getattr(process.current_process(), '_inheriting', False):
  119. raise RuntimeError('''
  120. An attempt has been made to start a new process before the
  121. current process has finished its bootstrapping phase.
  122. This probably means that you are not using fork to start your
  123. child processes and you have forgotten to use the proper idiom
  124. in the main module:
  125. if __name__ == '__main__':
  126. freeze_support()
  127. ...
  128. The "freeze_support()" line can be omitted if the program
  129. is not going to be frozen to produce an executable.
  130. To fix this issue, refer to the "Safe importing of main module"
  131. section in https://docs.python.org/3/library/multiprocessing.html
  132. ''')
  133. def get_preparation_data(name):
  134. '''
  135. Return info about parent needed by child to unpickle process object
  136. '''
  137. _check_not_importing_main()
  138. d = dict(
  139. log_to_stderr=util._log_to_stderr,
  140. authkey=process.current_process().authkey,
  141. )
  142. if util._logger is not None:
  143. d['log_level'] = util._logger.getEffectiveLevel()
  144. sys_path=sys.path.copy()
  145. try:
  146. i = sys_path.index('')
  147. except ValueError:
  148. pass
  149. else:
  150. sys_path[i] = process.ORIGINAL_DIR
  151. d.update(
  152. name=name,
  153. sys_path=sys_path,
  154. sys_argv=sys.argv,
  155. orig_dir=process.ORIGINAL_DIR,
  156. dir=os.getcwd(),
  157. start_method=get_start_method(),
  158. )
  159. # Figure out whether to initialise main in the subprocess as a module
  160. # or through direct execution (or to leave it alone entirely)
  161. main_module = sys.modules['__main__']
  162. main_mod_name = getattr(main_module.__spec__, "name", None)
  163. if main_mod_name is not None:
  164. d['init_main_from_name'] = main_mod_name
  165. elif sys.platform != 'win32' or (not WINEXE and not WINSERVICE):
  166. main_path = getattr(main_module, '__file__', None)
  167. if main_path is not None:
  168. if (not os.path.isabs(main_path) and
  169. process.ORIGINAL_DIR is not None):
  170. main_path = os.path.join(process.ORIGINAL_DIR, main_path)
  171. d['init_main_from_path'] = os.path.normpath(main_path)
  172. return d
  173. #
  174. # Prepare current process
  175. #
  176. old_main_modules = []
  177. def prepare(data):
  178. '''
  179. Try to get current process ready to unpickle process object
  180. '''
  181. if 'name' in data:
  182. process.current_process().name = data['name']
  183. if 'authkey' in data:
  184. process.current_process().authkey = data['authkey']
  185. if 'log_to_stderr' in data and data['log_to_stderr']:
  186. util.log_to_stderr()
  187. if 'log_level' in data:
  188. util.get_logger().setLevel(data['log_level'])
  189. if 'sys_path' in data:
  190. sys.path = data['sys_path']
  191. if 'sys_argv' in data:
  192. sys.argv = data['sys_argv']
  193. if 'dir' in data:
  194. os.chdir(data['dir'])
  195. if 'orig_dir' in data:
  196. process.ORIGINAL_DIR = data['orig_dir']
  197. if 'start_method' in data:
  198. set_start_method(data['start_method'], force=True)
  199. if 'init_main_from_name' in data:
  200. _fixup_main_from_name(data['init_main_from_name'])
  201. elif 'init_main_from_path' in data:
  202. _fixup_main_from_path(data['init_main_from_path'])
  203. # Multiprocessing module helpers to fix up the main module in
  204. # spawned subprocesses
  205. def _fixup_main_from_name(mod_name):
  206. # __main__.py files for packages, directories, zip archives, etc, run
  207. # their "main only" code unconditionally, so we don't even try to
  208. # populate anything in __main__, nor do we make any changes to
  209. # __main__ attributes
  210. current_main = sys.modules['__main__']
  211. if mod_name == "__main__" or mod_name.endswith(".__main__"):
  212. return
  213. # If this process was forked, __main__ may already be populated
  214. if getattr(current_main.__spec__, "name", None) == mod_name:
  215. return
  216. # Otherwise, __main__ may contain some non-main code where we need to
  217. # support unpickling it properly. We rerun it as __mp_main__ and make
  218. # the normal __main__ an alias to that
  219. old_main_modules.append(current_main)
  220. main_module = types.ModuleType("__mp_main__")
  221. main_content = runpy.run_module(mod_name,
  222. run_name="__mp_main__",
  223. alter_sys=True)
  224. main_module.__dict__.update(main_content)
  225. sys.modules['__main__'] = sys.modules['__mp_main__'] = main_module
  226. def _fixup_main_from_path(main_path):
  227. # If this process was forked, __main__ may already be populated
  228. current_main = sys.modules['__main__']
  229. # Unfortunately, the main ipython launch script historically had no
  230. # "if __name__ == '__main__'" guard, so we work around that
  231. # by treating it like a __main__.py file
  232. # See https://github.com/ipython/ipython/issues/4698
  233. main_name = os.path.splitext(os.path.basename(main_path))[0]
  234. if main_name == 'ipython':
  235. return
  236. # Otherwise, if __file__ already has the setting we expect,
  237. # there's nothing more to do
  238. if getattr(current_main, '__file__', None) == main_path:
  239. return
  240. # If the parent process has sent a path through rather than a module
  241. # name we assume it is an executable script that may contain
  242. # non-main code that needs to be executed
  243. old_main_modules.append(current_main)
  244. main_module = types.ModuleType("__mp_main__")
  245. main_content = runpy.run_path(main_path,
  246. run_name="__mp_main__")
  247. main_module.__dict__.update(main_content)
  248. sys.modules['__main__'] = sys.modules['__mp_main__'] = main_module
  249. def import_main_path(main_path):
  250. '''
  251. Set sys.modules['__main__'] to module at main_path
  252. '''
  253. _fixup_main_from_path(main_path)