spawn.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. """distutils.spawn
  2. Provides the 'spawn()' function, a front-end to various platform-
  3. specific functions for launching another program in a sub-process.
  4. Also provides the 'find_executable()' to search the path for a given
  5. executable name.
  6. """
  7. import sys
  8. import os
  9. from distutils.errors import DistutilsPlatformError, DistutilsExecError
  10. from distutils.debug import DEBUG
  11. from distutils import log
  12. def spawn(cmd, search_path=1, verbose=0, dry_run=0):
  13. """Run another program, specified as a command list 'cmd', in a new process.
  14. 'cmd' is just the argument list for the new process, ie.
  15. cmd[0] is the program to run and cmd[1:] are the rest of its arguments.
  16. There is no way to run a program with a name different from that of its
  17. executable.
  18. If 'search_path' is true (the default), the system's executable
  19. search path will be used to find the program; otherwise, cmd[0]
  20. must be the exact path to the executable. If 'dry_run' is true,
  21. the command will not actually be run.
  22. Raise DistutilsExecError if running the program fails in any way; just
  23. return on success.
  24. """
  25. # cmd is documented as a list, but just in case some code passes a tuple
  26. # in, protect our %-formatting code against horrible death
  27. cmd = list(cmd)
  28. if os.name == 'posix':
  29. _spawn_posix(cmd, search_path, dry_run=dry_run)
  30. elif os.name == 'nt':
  31. _spawn_nt(cmd, search_path, dry_run=dry_run)
  32. else:
  33. raise DistutilsPlatformError(
  34. "don't know how to spawn programs on platform '%s'" % os.name)
  35. def _nt_quote_args(args):
  36. """Quote command-line arguments for DOS/Windows conventions.
  37. Just wraps every argument which contains blanks in double quotes, and
  38. returns a new argument list.
  39. """
  40. # XXX this doesn't seem very robust to me -- but if the Windows guys
  41. # say it'll work, I guess I'll have to accept it. (What if an arg
  42. # contains quotes? What other magic characters, other than spaces,
  43. # have to be escaped? Is there an escaping mechanism other than
  44. # quoting?)
  45. for i, arg in enumerate(args):
  46. if ' ' in arg:
  47. args[i] = '"%s"' % arg
  48. return args
  49. def _spawn_nt(cmd, search_path=1, verbose=0, dry_run=0):
  50. executable = cmd[0]
  51. cmd = _nt_quote_args(cmd)
  52. if search_path:
  53. # either we find one or it stays the same
  54. executable = find_executable(executable) or executable
  55. log.info(' '.join([executable] + cmd[1:]))
  56. if not dry_run:
  57. # spawn for NT requires a full path to the .exe
  58. try:
  59. rc = os.spawnv(os.P_WAIT, executable, cmd)
  60. except OSError as exc:
  61. # this seems to happen when the command isn't found
  62. if not DEBUG:
  63. cmd = executable
  64. raise DistutilsExecError(
  65. "command %r failed: %s" % (cmd, exc.args[-1]))
  66. if rc != 0:
  67. # and this reflects the command running but failing
  68. if not DEBUG:
  69. cmd = executable
  70. raise DistutilsExecError(
  71. "command %r failed with exit status %d" % (cmd, rc))
  72. if sys.platform == 'darwin':
  73. from distutils import sysconfig
  74. _cfg_target = None
  75. _cfg_target_split = None
  76. def _spawn_posix(cmd, search_path=1, verbose=0, dry_run=0):
  77. log.info(' '.join(cmd))
  78. if dry_run:
  79. return
  80. executable = cmd[0]
  81. exec_fn = search_path and os.execvp or os.execv
  82. env = None
  83. if sys.platform == 'darwin':
  84. global _cfg_target, _cfg_target_split
  85. if _cfg_target is None:
  86. _cfg_target = sysconfig.get_config_var(
  87. 'MACOSX_DEPLOYMENT_TARGET') or ''
  88. if _cfg_target:
  89. _cfg_target_split = [int(x) for x in _cfg_target.split('.')]
  90. if _cfg_target:
  91. # ensure that the deployment target of build process is not less
  92. # than that used when the interpreter was built. This ensures
  93. # extension modules are built with correct compatibility values
  94. cur_target = os.environ.get('MACOSX_DEPLOYMENT_TARGET', _cfg_target)
  95. if _cfg_target_split > [int(x) for x in cur_target.split('.')]:
  96. my_msg = ('$MACOSX_DEPLOYMENT_TARGET mismatch: '
  97. 'now "%s" but "%s" during configure'
  98. % (cur_target, _cfg_target))
  99. raise DistutilsPlatformError(my_msg)
  100. env = dict(os.environ,
  101. MACOSX_DEPLOYMENT_TARGET=cur_target)
  102. exec_fn = search_path and os.execvpe or os.execve
  103. pid = os.fork()
  104. if pid == 0: # in the child
  105. try:
  106. if env is None:
  107. exec_fn(executable, cmd)
  108. else:
  109. exec_fn(executable, cmd, env)
  110. except OSError as e:
  111. if not DEBUG:
  112. cmd = executable
  113. sys.stderr.write("unable to execute %r: %s\n"
  114. % (cmd, e.strerror))
  115. os._exit(1)
  116. if not DEBUG:
  117. cmd = executable
  118. sys.stderr.write("unable to execute %r for unknown reasons" % cmd)
  119. os._exit(1)
  120. else: # in the parent
  121. # Loop until the child either exits or is terminated by a signal
  122. # (ie. keep waiting if it's merely stopped)
  123. while True:
  124. try:
  125. pid, status = os.waitpid(pid, 0)
  126. except OSError as exc:
  127. if not DEBUG:
  128. cmd = executable
  129. raise DistutilsExecError(
  130. "command %r failed: %s" % (cmd, exc.args[-1]))
  131. if os.WIFSIGNALED(status):
  132. if not DEBUG:
  133. cmd = executable
  134. raise DistutilsExecError(
  135. "command %r terminated by signal %d"
  136. % (cmd, os.WTERMSIG(status)))
  137. elif os.WIFEXITED(status):
  138. exit_status = os.WEXITSTATUS(status)
  139. if exit_status == 0:
  140. return # hey, it succeeded!
  141. else:
  142. if not DEBUG:
  143. cmd = executable
  144. raise DistutilsExecError(
  145. "command %r failed with exit status %d"
  146. % (cmd, exit_status))
  147. elif os.WIFSTOPPED(status):
  148. continue
  149. else:
  150. if not DEBUG:
  151. cmd = executable
  152. raise DistutilsExecError(
  153. "unknown error executing %r: termination status %d"
  154. % (cmd, status))
  155. def find_executable(executable, path=None):
  156. """Tries to find 'executable' in the directories listed in 'path'.
  157. A string listing directories separated by 'os.pathsep'; defaults to
  158. os.environ['PATH']. Returns the complete filename or None if not found.
  159. """
  160. if path is None:
  161. path = os.environ['PATH']
  162. paths = path.split(os.pathsep)
  163. base, ext = os.path.splitext(executable)
  164. if (sys.platform == 'win32') and (ext != '.exe'):
  165. executable = executable + '.exe'
  166. if not os.path.isfile(executable):
  167. for p in paths:
  168. f = os.path.join(p, executable)
  169. if os.path.isfile(f):
  170. # the file exists, we have a shot at spawn working
  171. return f
  172. return None
  173. else:
  174. return executable