spawn.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. from __future__ import absolute_import
  11. import io
  12. import os
  13. import pickle
  14. import sys
  15. import runpy
  16. import types
  17. import warnings
  18. from . import get_start_method, set_start_method
  19. from . import process
  20. from . import util
  21. __all__ = ['_main', 'freeze_support', 'set_executable', 'get_executable',
  22. 'get_preparation_data', 'get_command_line', 'import_main_path']
  23. W_OLD_DJANGO_LAYOUT = """\
  24. Will add directory %r to path! This is necessary to accommodate \
  25. pre-Django 1.4 layouts using setup_environ.
  26. You can skip this warning by adding a DJANGO_SETTINGS_MODULE=settings \
  27. environment variable.
  28. """
  29. #
  30. # _python_exe is the assumed path to the python executable.
  31. # People embedding Python want to modify it.
  32. #
  33. if sys.platform != 'win32':
  34. WINEXE = False
  35. WINSERVICE = False
  36. else:
  37. WINEXE = (sys.platform == 'win32' and getattr(sys, 'frozen', False))
  38. WINSERVICE = sys.executable.lower().endswith("pythonservice.exe")
  39. if WINSERVICE:
  40. _python_exe = os.path.join(sys.exec_prefix, 'python.exe')
  41. else:
  42. _python_exe = sys.executable
  43. def _module_parent_dir(mod):
  44. dir, filename = os.path.split(_module_dir(mod))
  45. if dir == os.curdir or not dir:
  46. dir = os.getcwd()
  47. return dir
  48. def _module_dir(mod):
  49. if '__init__.py' in mod.__file__:
  50. return os.path.dirname(mod.__file__)
  51. return mod.__file__
  52. def _Django_old_layout_hack__save():
  53. if 'DJANGO_PROJECT_DIR' not in os.environ:
  54. try:
  55. settings_name = os.environ['DJANGO_SETTINGS_MODULE']
  56. except KeyError:
  57. return # not using Django.
  58. conf_settings = sys.modules.get('django.conf.settings')
  59. configured = conf_settings and conf_settings.configured
  60. try:
  61. project_name, _ = settings_name.split('.', 1)
  62. except ValueError:
  63. return # not modified by setup_environ
  64. project = __import__(project_name)
  65. try:
  66. project_dir = os.path.normpath(_module_parent_dir(project))
  67. except AttributeError:
  68. return # dynamically generated module (no __file__)
  69. if configured:
  70. warnings.warn(UserWarning(
  71. W_OLD_DJANGO_LAYOUT % os.path.realpath(project_dir)
  72. ))
  73. os.environ['DJANGO_PROJECT_DIR'] = project_dir
  74. def _Django_old_layout_hack__load():
  75. try:
  76. sys.path.append(os.environ['DJANGO_PROJECT_DIR'])
  77. except KeyError:
  78. pass
  79. def set_executable(exe):
  80. global _python_exe
  81. _python_exe = exe
  82. def get_executable():
  83. return _python_exe
  84. #
  85. #
  86. #
  87. def is_forking(argv):
  88. '''
  89. Return whether commandline indicates we are forking
  90. '''
  91. if len(argv) >= 2 and argv[1] == '--billiard-fork':
  92. return True
  93. else:
  94. return False
  95. def freeze_support():
  96. '''
  97. Run code for process object if this in not the main process
  98. '''
  99. if is_forking(sys.argv):
  100. kwds = {}
  101. for arg in sys.argv[2:]:
  102. name, value = arg.split('=')
  103. if value == 'None':
  104. kwds[name] = None
  105. else:
  106. kwds[name] = int(value)
  107. spawn_main(**kwds)
  108. sys.exit()
  109. def get_command_line(**kwds):
  110. '''
  111. Returns prefix of command line used for spawning a child process
  112. '''
  113. if getattr(sys, 'frozen', False):
  114. return ([sys.executable, '--billiard-fork'] +
  115. ['%s=%r' % item for item in kwds.items()])
  116. else:
  117. prog = 'from billiard.spawn import spawn_main; spawn_main(%s)'
  118. prog %= ', '.join('%s=%r' % item for item in kwds.items())
  119. opts = util._args_from_interpreter_flags()
  120. return [_python_exe] + opts + ['-c', prog, '--billiard-fork']
  121. def spawn_main(pipe_handle, parent_pid=None, tracker_fd=None):
  122. '''
  123. Run code specified by data received over pipe
  124. '''
  125. assert is_forking(sys.argv)
  126. if sys.platform == 'win32':
  127. import msvcrt
  128. from .reduction import steal_handle
  129. new_handle = steal_handle(parent_pid, pipe_handle)
  130. fd = msvcrt.open_osfhandle(new_handle, os.O_RDONLY)
  131. else:
  132. from . import semaphore_tracker
  133. semaphore_tracker._semaphore_tracker._fd = tracker_fd
  134. fd = pipe_handle
  135. exitcode = _main(fd)
  136. sys.exit(exitcode)
  137. def _setup_logging_in_child_hack():
  138. # Huge hack to make logging before Process.run work.
  139. try:
  140. os.environ["MP_MAIN_FILE"] = sys.modules["__main__"].__file__
  141. except KeyError:
  142. pass
  143. except AttributeError:
  144. pass
  145. loglevel = os.environ.get("_MP_FORK_LOGLEVEL_")
  146. logfile = os.environ.get("_MP_FORK_LOGFILE_") or None
  147. format = os.environ.get("_MP_FORK_LOGFORMAT_")
  148. if loglevel:
  149. from . import util
  150. import logging
  151. logger = util.get_logger()
  152. logger.setLevel(int(loglevel))
  153. if not logger.handlers:
  154. logger._rudimentary_setup = True
  155. logfile = logfile or sys.__stderr__
  156. if hasattr(logfile, "write"):
  157. handler = logging.StreamHandler(logfile)
  158. else:
  159. handler = logging.FileHandler(logfile)
  160. formatter = logging.Formatter(
  161. format or util.DEFAULT_LOGGING_FORMAT,
  162. )
  163. handler.setFormatter(formatter)
  164. logger.addHandler(handler)
  165. def _main(fd):
  166. _Django_old_layout_hack__load()
  167. with io.open(fd, 'rb', closefd=True) as from_parent:
  168. process.current_process()._inheriting = True
  169. try:
  170. preparation_data = pickle.load(from_parent)
  171. prepare(preparation_data)
  172. _setup_logging_in_child_hack()
  173. self = pickle.load(from_parent)
  174. finally:
  175. del process.current_process()._inheriting
  176. return self._bootstrap()
  177. def _check_not_importing_main():
  178. if getattr(process.current_process(), '_inheriting', False):
  179. raise RuntimeError('''
  180. An attempt has been made to start a new process before the
  181. current process has finished its bootstrapping phase.
  182. This probably means that you are not using fork to start your
  183. child processes and you have forgotten to use the proper idiom
  184. in the main module:
  185. if __name__ == '__main__':
  186. freeze_support()
  187. ...
  188. The "freeze_support()" line can be omitted if the program
  189. is not going to be frozen to produce an executable.''')
  190. def get_preparation_data(name):
  191. '''
  192. Return info about parent needed by child to unpickle process object
  193. '''
  194. _check_not_importing_main()
  195. d = dict(
  196. log_to_stderr=util._log_to_stderr,
  197. authkey=process.current_process().authkey,
  198. )
  199. if util._logger is not None:
  200. d['log_level'] = util._logger.getEffectiveLevel()
  201. sys_path = sys.path[:]
  202. try:
  203. i = sys_path.index('')
  204. except ValueError:
  205. pass
  206. else:
  207. sys_path[i] = process.ORIGINAL_DIR
  208. d.update(
  209. name=name,
  210. sys_path=sys_path,
  211. sys_argv=sys.argv,
  212. orig_dir=process.ORIGINAL_DIR,
  213. dir=os.getcwd(),
  214. start_method=get_start_method(),
  215. )
  216. # Figure out whether to initialise main in the subprocess as a module
  217. # or through direct execution (or to leave it alone entirely)
  218. main_module = sys.modules['__main__']
  219. try:
  220. main_mod_name = main_module.__spec__.name
  221. except AttributeError:
  222. main_mod_name = main_module.__name__
  223. if main_mod_name is not None:
  224. d['init_main_from_name'] = main_mod_name
  225. elif sys.platform != 'win32' or (not WINEXE and not WINSERVICE):
  226. main_path = getattr(main_module, '__file__', None)
  227. if main_path is not None:
  228. if (not os.path.isabs(main_path) and
  229. process.ORIGINAL_DIR is not None):
  230. main_path = os.path.join(process.ORIGINAL_DIR, main_path)
  231. d['init_main_from_path'] = os.path.normpath(main_path)
  232. return d
  233. #
  234. # Prepare current process
  235. #
  236. old_main_modules = []
  237. def prepare(data):
  238. '''
  239. Try to get current process ready to unpickle process object
  240. '''
  241. if 'name' in data:
  242. process.current_process().name = data['name']
  243. if 'authkey' in data:
  244. process.current_process().authkey = data['authkey']
  245. if 'log_to_stderr' in data and data['log_to_stderr']:
  246. util.log_to_stderr()
  247. if 'log_level' in data:
  248. util.get_logger().setLevel(data['log_level'])
  249. if 'sys_path' in data:
  250. sys.path = data['sys_path']
  251. if 'sys_argv' in data:
  252. sys.argv = data['sys_argv']
  253. if 'dir' in data:
  254. os.chdir(data['dir'])
  255. if 'orig_dir' in data:
  256. process.ORIGINAL_DIR = data['orig_dir']
  257. if 'start_method' in data:
  258. set_start_method(data['start_method'])
  259. if 'init_main_from_name' in data:
  260. _fixup_main_from_name(data['init_main_from_name'])
  261. elif 'init_main_from_path' in data:
  262. _fixup_main_from_path(data['init_main_from_path'])
  263. # Multiprocessing module helpers to fix up the main module in
  264. # spawned subprocesses
  265. def _fixup_main_from_name(mod_name):
  266. # __main__.py files for packages, directories, zip archives, etc, run
  267. # their "main only" code unconditionally, so we don't even try to
  268. # populate anything in __main__, nor do we make any changes to
  269. # __main__ attributes
  270. current_main = sys.modules['__main__']
  271. if mod_name == "__main__" or mod_name.endswith(".__main__"):
  272. return
  273. # If this process was forked, __main__ may already be populated
  274. if getattr(current_main.__spec__, "name", None) == mod_name:
  275. return
  276. # Otherwise, __main__ may contain some non-main code where we need to
  277. # support unpickling it properly. We rerun it as __mp_main__ and make
  278. # the normal __main__ an alias to that
  279. old_main_modules.append(current_main)
  280. main_module = types.ModuleType("__mp_main__")
  281. main_content = runpy.run_module(mod_name,
  282. run_name="__mp_main__",
  283. alter_sys=True)
  284. main_module.__dict__.update(main_content)
  285. sys.modules['__main__'] = sys.modules['__mp_main__'] = main_module
  286. def _fixup_main_from_path(main_path):
  287. # If this process was forked, __main__ may already be populated
  288. current_main = sys.modules['__main__']
  289. # Unfortunately, the main ipython launch script historically had no
  290. # "if __name__ == '__main__'" guard, so we work around that
  291. # by treating it like a __main__.py file
  292. # See https://github.com/ipython/ipython/issues/4698
  293. main_name = os.path.splitext(os.path.basename(main_path))[0]
  294. if main_name == 'ipython':
  295. return
  296. # Otherwise, if __file__ already has the setting we expect,
  297. # there's nothing more to do
  298. if getattr(current_main, '__file__', None) == main_path:
  299. return
  300. # If the parent process has sent a path through rather than a module
  301. # name we assume it is an executable script that may contain
  302. # non-main code that needs to be executed
  303. old_main_modules.append(current_main)
  304. main_module = types.ModuleType("__mp_main__")
  305. main_content = runpy.run_path(main_path,
  306. run_name="__mp_main__")
  307. main_module.__dict__.update(main_content)
  308. sys.modules['__main__'] = sys.modules['__mp_main__'] = main_module
  309. def import_main_path(main_path):
  310. '''
  311. Set sys.modules['__main__'] to module at main_path
  312. '''
  313. _fixup_main_from_path(main_path)