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