spawn.py 9.2 KB

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