spawn.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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. new_handle = reduction.steal_handle(parent_pid, pipe_handle)
  84. fd = msvcrt.open_osfhandle(new_handle, os.O_RDONLY)
  85. else:
  86. from . import semaphore_tracker
  87. semaphore_tracker._semaphore_tracker._fd = tracker_fd
  88. fd = pipe_handle
  89. exitcode = _main(fd)
  90. sys.exit(exitcode)
  91. def _main(fd):
  92. with os.fdopen(fd, 'rb', closefd=True) as from_parent:
  93. process.current_process()._inheriting = True
  94. try:
  95. preparation_data = reduction.pickle.load(from_parent)
  96. prepare(preparation_data)
  97. self = reduction.pickle.load(from_parent)
  98. finally:
  99. del process.current_process()._inheriting
  100. return self._bootstrap()
  101. def _check_not_importing_main():
  102. if getattr(process.current_process(), '_inheriting', False):
  103. raise RuntimeError('''
  104. An attempt has been made to start a new process before the
  105. current process has finished its bootstrapping phase.
  106. This probably means that you are not using fork to start your
  107. child processes and you have forgotten to use the proper idiom
  108. in the main module:
  109. if __name__ == '__main__':
  110. freeze_support()
  111. ...
  112. The "freeze_support()" line can be omitted if the program
  113. is not going to be frozen to produce an executable.''')
  114. def get_preparation_data(name):
  115. '''
  116. Return info about parent needed by child to unpickle process object
  117. '''
  118. _check_not_importing_main()
  119. d = dict(
  120. log_to_stderr=util._log_to_stderr,
  121. authkey=process.current_process().authkey,
  122. )
  123. if util._logger is not None:
  124. d['log_level'] = util._logger.getEffectiveLevel()
  125. sys_path=sys.path.copy()
  126. try:
  127. i = sys_path.index('')
  128. except ValueError:
  129. pass
  130. else:
  131. sys_path[i] = process.ORIGINAL_DIR
  132. d.update(
  133. name=name,
  134. sys_path=sys_path,
  135. sys_argv=sys.argv,
  136. orig_dir=process.ORIGINAL_DIR,
  137. dir=os.getcwd(),
  138. start_method=get_start_method(),
  139. )
  140. # Figure out whether to initialise main in the subprocess as a module
  141. # or through direct execution (or to leave it alone entirely)
  142. main_module = sys.modules['__main__']
  143. main_mod_name = getattr(main_module.__spec__, "name", None)
  144. if main_mod_name is not None:
  145. d['init_main_from_name'] = main_mod_name
  146. elif sys.platform != 'win32' or (not WINEXE and not WINSERVICE):
  147. main_path = getattr(main_module, '__file__', None)
  148. if main_path is not None:
  149. if (not os.path.isabs(main_path) and
  150. process.ORIGINAL_DIR is not None):
  151. main_path = os.path.join(process.ORIGINAL_DIR, main_path)
  152. d['init_main_from_path'] = os.path.normpath(main_path)
  153. return d
  154. #
  155. # Prepare current process
  156. #
  157. old_main_modules = []
  158. def prepare(data):
  159. '''
  160. Try to get current process ready to unpickle process object
  161. '''
  162. if 'name' in data:
  163. process.current_process().name = data['name']
  164. if 'authkey' in data:
  165. process.current_process().authkey = data['authkey']
  166. if 'log_to_stderr' in data and data['log_to_stderr']:
  167. util.log_to_stderr()
  168. if 'log_level' in data:
  169. util.get_logger().setLevel(data['log_level'])
  170. if 'sys_path' in data:
  171. sys.path = data['sys_path']
  172. if 'sys_argv' in data:
  173. sys.argv = data['sys_argv']
  174. if 'dir' in data:
  175. os.chdir(data['dir'])
  176. if 'orig_dir' in data:
  177. process.ORIGINAL_DIR = data['orig_dir']
  178. if 'start_method' in data:
  179. set_start_method(data['start_method'], force=True)
  180. if 'init_main_from_name' in data:
  181. _fixup_main_from_name(data['init_main_from_name'])
  182. elif 'init_main_from_path' in data:
  183. _fixup_main_from_path(data['init_main_from_path'])
  184. # Multiprocessing module helpers to fix up the main module in
  185. # spawned subprocesses
  186. def _fixup_main_from_name(mod_name):
  187. # __main__.py files for packages, directories, zip archives, etc, run
  188. # their "main only" code unconditionally, so we don't even try to
  189. # populate anything in __main__, nor do we make any changes to
  190. # __main__ attributes
  191. current_main = sys.modules['__main__']
  192. if mod_name == "__main__" or mod_name.endswith(".__main__"):
  193. return
  194. # If this process was forked, __main__ may already be populated
  195. if getattr(current_main.__spec__, "name", None) == mod_name:
  196. return
  197. # Otherwise, __main__ may contain some non-main code where we need to
  198. # support unpickling it properly. We rerun it as __mp_main__ and make
  199. # the normal __main__ an alias to that
  200. old_main_modules.append(current_main)
  201. main_module = types.ModuleType("__mp_main__")
  202. main_content = runpy.run_module(mod_name,
  203. run_name="__mp_main__",
  204. alter_sys=True)
  205. main_module.__dict__.update(main_content)
  206. sys.modules['__main__'] = sys.modules['__mp_main__'] = main_module
  207. def _fixup_main_from_path(main_path):
  208. # If this process was forked, __main__ may already be populated
  209. current_main = sys.modules['__main__']
  210. # Unfortunately, the main ipython launch script historically had no
  211. # "if __name__ == '__main__'" guard, so we work around that
  212. # by treating it like a __main__.py file
  213. # See https://github.com/ipython/ipython/issues/4698
  214. main_name = os.path.splitext(os.path.basename(main_path))[0]
  215. if main_name == 'ipython':
  216. return
  217. # Otherwise, if __file__ already has the setting we expect,
  218. # there's nothing more to do
  219. if getattr(current_main, '__file__', None) == main_path:
  220. return
  221. # If the parent process has sent a path through rather than a module
  222. # name we assume it is an executable script that may contain
  223. # non-main code that needs to be executed
  224. old_main_modules.append(current_main)
  225. main_module = types.ModuleType("__mp_main__")
  226. main_content = runpy.run_path(main_path,
  227. run_name="__mp_main__")
  228. main_module.__dict__.update(main_content)
  229. sys.modules['__main__'] = sys.modules['__mp_main__'] = main_module
  230. def import_main_path(main_path):
  231. '''
  232. Set sys.modules['__main__'] to module at main_path
  233. '''
  234. _fixup_main_from_path(main_path)