spawn.py 9.1 KB

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