spawn.py 8.4 KB

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