Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1 | # subprocess - Subprocesses with accessible I/O streams |
| 2 | # |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 3 | # For more information about this module, see PEP 324. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 4 | # |
Peter Astrand | c26516b | 2005-02-21 08:13:02 +0000 | [diff] [blame] | 5 | # This module should remain compatible with Python 2.2, see PEP 291. |
| 6 | # |
Peter Astrand | 3a708df | 2005-09-23 17:37:29 +0000 | [diff] [blame] | 7 | # Copyright (c) 2003-2005 by Peter Astrand <astrand@lysator.liu.se> |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 8 | # |
Peter Astrand | 69bf13f | 2005-02-14 08:56:32 +0000 | [diff] [blame] | 9 | # Licensed to PSF under a Contributor Agreement. |
Peter Astrand | 3a708df | 2005-09-23 17:37:29 +0000 | [diff] [blame] | 10 | # See http://www.python.org/2.4/license for licensing details. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 11 | |
Raymond Hettinger | 837dd93 | 2004-10-17 16:36:53 +0000 | [diff] [blame] | 12 | r"""subprocess - Subprocesses with accessible I/O streams |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 13 | |
Fredrik Lundh | 15aaacc | 2004-10-17 14:47:05 +0000 | [diff] [blame] | 14 | This module allows you to spawn processes, connect to their |
| 15 | input/output/error pipes, and obtain their return codes. This module |
| 16 | intends to replace several other, older modules and functions, like: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 17 | |
| 18 | os.system |
| 19 | os.spawn* |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 20 | commands.* |
| 21 | |
| 22 | Information about how the subprocess module can be used to replace these |
| 23 | modules and functions can be found below. |
| 24 | |
| 25 | |
| 26 | |
| 27 | Using the subprocess module |
| 28 | =========================== |
| 29 | This module defines one class called Popen: |
| 30 | |
| 31 | class Popen(args, bufsize=0, executable=None, |
| 32 | stdin=None, stdout=None, stderr=None, |
| 33 | preexec_fn=None, close_fds=False, shell=False, |
| 34 | cwd=None, env=None, universal_newlines=False, |
| 35 | startupinfo=None, creationflags=0): |
| 36 | |
| 37 | |
| 38 | Arguments are: |
| 39 | |
| 40 | args should be a string, or a sequence of program arguments. The |
| 41 | program to execute is normally the first item in the args sequence or |
| 42 | string, but can be explicitly set by using the executable argument. |
| 43 | |
| 44 | On UNIX, with shell=False (default): In this case, the Popen class |
| 45 | uses os.execvp() to execute the child program. args should normally |
| 46 | be a sequence. A string will be treated as a sequence with the string |
| 47 | as the only item (the program to execute). |
| 48 | |
| 49 | On UNIX, with shell=True: If args is a string, it specifies the |
| 50 | command string to execute through the shell. If args is a sequence, |
| 51 | the first item specifies the command string, and any additional items |
| 52 | will be treated as additional shell arguments. |
| 53 | |
| 54 | On Windows: the Popen class uses CreateProcess() to execute the child |
| 55 | program, which operates on strings. If args is a sequence, it will be |
| 56 | converted to a string using the list2cmdline method. Please note that |
| 57 | not all MS Windows applications interpret the command line the same |
| 58 | way: The list2cmdline is designed for applications using the same |
| 59 | rules as the MS C runtime. |
| 60 | |
| 61 | bufsize, if given, has the same meaning as the corresponding argument |
| 62 | to the built-in open() function: 0 means unbuffered, 1 means line |
| 63 | buffered, any other positive value means use a buffer of |
| 64 | (approximately) that size. A negative bufsize means to use the system |
| 65 | default, which usually means fully buffered. The default value for |
| 66 | bufsize is 0 (unbuffered). |
| 67 | |
| 68 | stdin, stdout and stderr specify the executed programs' standard |
| 69 | input, standard output and standard error file handles, respectively. |
| 70 | Valid values are PIPE, an existing file descriptor (a positive |
| 71 | integer), an existing file object, and None. PIPE indicates that a |
| 72 | new pipe to the child should be created. With None, no redirection |
| 73 | will occur; the child's file handles will be inherited from the |
| 74 | parent. Additionally, stderr can be STDOUT, which indicates that the |
| 75 | stderr data from the applications should be captured into the same |
| 76 | file handle as for stdout. |
| 77 | |
| 78 | If preexec_fn is set to a callable object, this object will be called |
| 79 | in the child process just before the child is executed. |
| 80 | |
| 81 | If close_fds is true, all file descriptors except 0, 1 and 2 will be |
| 82 | closed before the child process is executed. |
| 83 | |
| 84 | if shell is true, the specified command will be executed through the |
| 85 | shell. |
| 86 | |
| 87 | If cwd is not None, the current directory will be changed to cwd |
| 88 | before the child is executed. |
| 89 | |
| 90 | If env is not None, it defines the environment variables for the new |
| 91 | process. |
| 92 | |
| 93 | If universal_newlines is true, the file objects stdout and stderr are |
| 94 | opened as a text files, but lines may be terminated by any of '\n', |
| 95 | the Unix end-of-line convention, '\r', the Macintosh convention or |
| 96 | '\r\n', the Windows convention. All of these external representations |
| 97 | are seen as '\n' by the Python program. Note: This feature is only |
| 98 | available if Python is built with universal newline support (the |
| 99 | default). Also, the newlines attribute of the file objects stdout, |
| 100 | stdin and stderr are not updated by the communicate() method. |
| 101 | |
| 102 | The startupinfo and creationflags, if given, will be passed to the |
| 103 | underlying CreateProcess() function. They can specify things such as |
| 104 | appearance of the main window and priority for the new process. |
| 105 | (Windows only) |
| 106 | |
| 107 | |
| 108 | This module also defines two shortcut functions: |
| 109 | |
Peter Astrand | 5f5e141 | 2004-12-05 20:15:36 +0000 | [diff] [blame] | 110 | call(*popenargs, **kwargs): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 111 | Run command with arguments. Wait for command to complete, then |
| 112 | return the returncode attribute. |
| 113 | |
| 114 | The arguments are the same as for the Popen constructor. Example: |
| 115 | |
| 116 | retcode = call(["ls", "-l"]) |
| 117 | |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 118 | check_call(*popenargs, **kwargs): |
| 119 | Run command with arguments. Wait for command to complete. If the |
| 120 | exit code was zero then return, otherwise raise |
| 121 | CalledProcessError. The CalledProcessError object will have the |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 122 | return code in the returncode attribute. |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 123 | |
| 124 | The arguments are the same as for the Popen constructor. Example: |
| 125 | |
| 126 | check_call(["ls", "-l"]) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 127 | |
| 128 | Exceptions |
| 129 | ---------- |
| 130 | Exceptions raised in the child process, before the new program has |
| 131 | started to execute, will be re-raised in the parent. Additionally, |
| 132 | the exception object will have one extra attribute called |
| 133 | 'child_traceback', which is a string containing traceback information |
| 134 | from the childs point of view. |
| 135 | |
| 136 | The most common exception raised is OSError. This occurs, for |
| 137 | example, when trying to execute a non-existent file. Applications |
| 138 | should prepare for OSErrors. |
| 139 | |
| 140 | A ValueError will be raised if Popen is called with invalid arguments. |
| 141 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 142 | check_call() will raise CalledProcessError, if the called process |
| 143 | returns a non-zero return code. |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 144 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 145 | |
| 146 | Security |
| 147 | -------- |
| 148 | Unlike some other popen functions, this implementation will never call |
| 149 | /bin/sh implicitly. This means that all characters, including shell |
| 150 | metacharacters, can safely be passed to child processes. |
| 151 | |
| 152 | |
| 153 | Popen objects |
| 154 | ============= |
| 155 | Instances of the Popen class have the following methods: |
| 156 | |
| 157 | poll() |
| 158 | Check if child process has terminated. Returns returncode |
| 159 | attribute. |
| 160 | |
| 161 | wait() |
| 162 | Wait for child process to terminate. Returns returncode attribute. |
| 163 | |
| 164 | communicate(input=None) |
| 165 | Interact with process: Send data to stdin. Read data from stdout |
| 166 | and stderr, until end-of-file is reached. Wait for process to |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 167 | terminate. The optional input argument should be a string to be |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 168 | sent to the child process, or None, if no data should be sent to |
| 169 | the child. |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 170 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 171 | communicate() returns a tuple (stdout, stderr). |
| 172 | |
| 173 | Note: The data read is buffered in memory, so do not use this |
| 174 | method if the data size is large or unlimited. |
| 175 | |
| 176 | The following attributes are also available: |
| 177 | |
| 178 | stdin |
| 179 | If the stdin argument is PIPE, this attribute is a file object |
| 180 | that provides input to the child process. Otherwise, it is None. |
| 181 | |
| 182 | stdout |
| 183 | If the stdout argument is PIPE, this attribute is a file object |
| 184 | that provides output from the child process. Otherwise, it is |
| 185 | None. |
| 186 | |
| 187 | stderr |
| 188 | If the stderr argument is PIPE, this attribute is file object that |
| 189 | provides error output from the child process. Otherwise, it is |
| 190 | None. |
| 191 | |
| 192 | pid |
| 193 | The process ID of the child process. |
| 194 | |
| 195 | returncode |
| 196 | The child return code. A None value indicates that the process |
| 197 | hasn't terminated yet. A negative value -N indicates that the |
| 198 | child was terminated by signal N (UNIX only). |
| 199 | |
| 200 | |
| 201 | Replacing older functions with the subprocess module |
| 202 | ==================================================== |
| 203 | In this section, "a ==> b" means that b can be used as a replacement |
| 204 | for a. |
| 205 | |
| 206 | Note: All functions in this section fail (more or less) silently if |
| 207 | the executed program cannot be found; this module raises an OSError |
| 208 | exception. |
| 209 | |
| 210 | In the following examples, we assume that the subprocess module is |
| 211 | imported with "from subprocess import *". |
| 212 | |
| 213 | |
| 214 | Replacing /bin/sh shell backquote |
| 215 | --------------------------------- |
| 216 | output=`mycmd myarg` |
| 217 | ==> |
| 218 | output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0] |
| 219 | |
| 220 | |
| 221 | Replacing shell pipe line |
| 222 | ------------------------- |
| 223 | output=`dmesg | grep hda` |
| 224 | ==> |
| 225 | p1 = Popen(["dmesg"], stdout=PIPE) |
Peter Astrand | 6fdf3cb | 2004-11-30 18:06:42 +0000 | [diff] [blame] | 226 | p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 227 | output = p2.communicate()[0] |
| 228 | |
| 229 | |
| 230 | Replacing os.system() |
| 231 | --------------------- |
| 232 | sts = os.system("mycmd" + " myarg") |
| 233 | ==> |
| 234 | p = Popen("mycmd" + " myarg", shell=True) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 235 | pid, sts = os.waitpid(p.pid, 0) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 236 | |
| 237 | Note: |
| 238 | |
| 239 | * Calling the program through the shell is usually not required. |
| 240 | |
| 241 | * It's easier to look at the returncode attribute than the |
| 242 | exitstatus. |
| 243 | |
| 244 | A more real-world example would look like this: |
| 245 | |
| 246 | try: |
| 247 | retcode = call("mycmd" + " myarg", shell=True) |
| 248 | if retcode < 0: |
Guido van Rossum | c2f93dc | 2007-05-24 00:50:02 +0000 | [diff] [blame] | 249 | print("Child was terminated by signal", -retcode, file=sys.stderr) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 250 | else: |
Guido van Rossum | c2f93dc | 2007-05-24 00:50:02 +0000 | [diff] [blame] | 251 | print("Child returned", retcode, file=sys.stderr) |
| 252 | except OSError as e: |
| 253 | print("Execution failed:", e, file=sys.stderr) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 254 | |
| 255 | |
| 256 | Replacing os.spawn* |
| 257 | ------------------- |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 258 | P_NOWAIT example: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 259 | |
| 260 | pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") |
| 261 | ==> |
| 262 | pid = Popen(["/bin/mycmd", "myarg"]).pid |
| 263 | |
| 264 | |
| 265 | P_WAIT example: |
| 266 | |
| 267 | retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg") |
| 268 | ==> |
| 269 | retcode = call(["/bin/mycmd", "myarg"]) |
| 270 | |
| 271 | |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 272 | Vector example: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 273 | |
| 274 | os.spawnvp(os.P_NOWAIT, path, args) |
| 275 | ==> |
| 276 | Popen([path] + args[1:]) |
| 277 | |
| 278 | |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 279 | Environment example: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 280 | |
| 281 | os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env) |
| 282 | ==> |
| 283 | Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"}) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 284 | """ |
| 285 | |
| 286 | import sys |
| 287 | mswindows = (sys.platform == "win32") |
| 288 | |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 289 | import io |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 290 | import os |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 291 | import traceback |
Christian Heimes | fdab48e | 2008-01-20 09:06:41 +0000 | [diff] [blame] | 292 | import gc |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 293 | import signal |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 294 | |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 295 | # Exception classes used by this module. |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 296 | class CalledProcessError(Exception): |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 297 | """This exception is raised when a process run by check_call() returns |
| 298 | a non-zero exit status. The exit status will be stored in the |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 299 | returncode attribute.""" |
| 300 | def __init__(self, returncode, cmd): |
| 301 | self.returncode = returncode |
| 302 | self.cmd = cmd |
| 303 | def __str__(self): |
| 304 | return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode) |
| 305 | |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 306 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 307 | if mswindows: |
| 308 | import threading |
| 309 | import msvcrt |
Fredrik Lundh | 3e73a01 | 2004-10-13 18:19:18 +0000 | [diff] [blame] | 310 | if 0: # <-- change this to use pywin32 instead of the _subprocess driver |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 311 | import pywintypes |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 312 | from win32api import GetStdHandle, STD_INPUT_HANDLE, \ |
| 313 | STD_OUTPUT_HANDLE, STD_ERROR_HANDLE |
| 314 | from win32api import GetCurrentProcess, DuplicateHandle, \ |
| 315 | GetModuleFileName, GetVersion |
Peter Astrand | c1d6536 | 2004-11-07 14:30:34 +0000 | [diff] [blame] | 316 | from win32con import DUPLICATE_SAME_ACCESS, SW_HIDE |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 317 | from win32pipe import CreatePipe |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 318 | from win32process import CreateProcess, STARTUPINFO, \ |
| 319 | GetExitCodeProcess, STARTF_USESTDHANDLES, \ |
Peter Astrand | c1d6536 | 2004-11-07 14:30:34 +0000 | [diff] [blame] | 320 | STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 321 | from win32process import TerminateProcess |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 322 | from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0 |
Fredrik Lundh | 3e73a01 | 2004-10-13 18:19:18 +0000 | [diff] [blame] | 323 | else: |
| 324 | from _subprocess import * |
| 325 | class STARTUPINFO: |
| 326 | dwFlags = 0 |
| 327 | hStdInput = None |
| 328 | hStdOutput = None |
| 329 | hStdError = None |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 330 | wShowWindow = 0 |
Fredrik Lundh | 3e73a01 | 2004-10-13 18:19:18 +0000 | [diff] [blame] | 331 | class pywintypes: |
| 332 | error = IOError |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 333 | else: |
| 334 | import select |
| 335 | import errno |
| 336 | import fcntl |
| 337 | import pickle |
| 338 | |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 339 | __all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "CalledProcessError"] |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 340 | |
| 341 | try: |
| 342 | MAXFD = os.sysconf("SC_OPEN_MAX") |
| 343 | except: |
| 344 | MAXFD = 256 |
| 345 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 346 | _active = [] |
| 347 | |
| 348 | def _cleanup(): |
| 349 | for inst in _active[:]: |
Christian Heimes | a37d4c6 | 2007-12-04 23:02:19 +0000 | [diff] [blame] | 350 | res = inst.poll(_deadstate=sys.maxsize) |
Guido van Rossum | b5d47ef | 2006-08-24 02:27:45 +0000 | [diff] [blame] | 351 | if res is not None and res >= 0: |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 352 | try: |
| 353 | _active.remove(inst) |
| 354 | except ValueError: |
| 355 | # This can happen if two threads create a new Popen instance. |
| 356 | # It's harmless that it was already removed, so ignore. |
| 357 | pass |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 358 | |
| 359 | PIPE = -1 |
| 360 | STDOUT = -2 |
| 361 | |
| 362 | |
Peter Astrand | 5f5e141 | 2004-12-05 20:15:36 +0000 | [diff] [blame] | 363 | def call(*popenargs, **kwargs): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 364 | """Run command with arguments. Wait for command to complete, then |
| 365 | return the returncode attribute. |
| 366 | |
| 367 | The arguments are the same as for the Popen constructor. Example: |
| 368 | |
| 369 | retcode = call(["ls", "-l"]) |
| 370 | """ |
Peter Astrand | 5f5e141 | 2004-12-05 20:15:36 +0000 | [diff] [blame] | 371 | return Popen(*popenargs, **kwargs).wait() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 372 | |
| 373 | |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 374 | def check_call(*popenargs, **kwargs): |
| 375 | """Run command with arguments. Wait for command to complete. If |
| 376 | the exit code was zero then return, otherwise raise |
| 377 | CalledProcessError. The CalledProcessError object will have the |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 378 | return code in the returncode attribute. |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 379 | |
| 380 | The arguments are the same as for the Popen constructor. Example: |
| 381 | |
| 382 | check_call(["ls", "-l"]) |
| 383 | """ |
| 384 | retcode = call(*popenargs, **kwargs) |
| 385 | cmd = kwargs.get("args") |
| 386 | if cmd is None: |
| 387 | cmd = popenargs[0] |
| 388 | if retcode: |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 389 | raise CalledProcessError(retcode, cmd) |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 390 | return retcode |
| 391 | |
| 392 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 393 | def list2cmdline(seq): |
| 394 | """ |
| 395 | Translate a sequence of arguments into a command line |
| 396 | string, using the same rules as the MS C runtime: |
| 397 | |
| 398 | 1) Arguments are delimited by white space, which is either a |
| 399 | space or a tab. |
| 400 | |
| 401 | 2) A string surrounded by double quotation marks is |
| 402 | interpreted as a single argument, regardless of white space |
Christian Heimes | fdab48e | 2008-01-20 09:06:41 +0000 | [diff] [blame] | 403 | or pipe characters contained within. A quoted string can be |
| 404 | embedded in an argument. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 405 | |
| 406 | 3) A double quotation mark preceded by a backslash is |
| 407 | interpreted as a literal double quotation mark. |
| 408 | |
| 409 | 4) Backslashes are interpreted literally, unless they |
| 410 | immediately precede a double quotation mark. |
| 411 | |
| 412 | 5) If backslashes immediately precede a double quotation mark, |
| 413 | every pair of backslashes is interpreted as a literal |
| 414 | backslash. If the number of backslashes is odd, the last |
| 415 | backslash escapes the next double quotation mark as |
| 416 | described in rule 3. |
| 417 | """ |
| 418 | |
| 419 | # See |
| 420 | # http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp |
| 421 | result = [] |
| 422 | needquote = False |
| 423 | for arg in seq: |
| 424 | bs_buf = [] |
| 425 | |
| 426 | # Add a space to separate this argument from the others |
| 427 | if result: |
| 428 | result.append(' ') |
| 429 | |
Christian Heimes | fdab48e | 2008-01-20 09:06:41 +0000 | [diff] [blame] | 430 | needquote = (" " in arg) or ("\t" in arg) or ("|" in arg) or not arg |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 431 | if needquote: |
| 432 | result.append('"') |
| 433 | |
| 434 | for c in arg: |
| 435 | if c == '\\': |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 436 | # Don't know if we need to double yet. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 437 | bs_buf.append(c) |
| 438 | elif c == '"': |
Christian Heimes | fdab48e | 2008-01-20 09:06:41 +0000 | [diff] [blame] | 439 | # Double backslashes. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 440 | result.append('\\' * len(bs_buf)*2) |
| 441 | bs_buf = [] |
| 442 | result.append('\\"') |
| 443 | else: |
| 444 | # Normal char |
| 445 | if bs_buf: |
| 446 | result.extend(bs_buf) |
| 447 | bs_buf = [] |
| 448 | result.append(c) |
| 449 | |
Christian Heimes | fdab48e | 2008-01-20 09:06:41 +0000 | [diff] [blame] | 450 | # Add remaining backslashes, if any. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 451 | if bs_buf: |
| 452 | result.extend(bs_buf) |
| 453 | |
| 454 | if needquote: |
Peter Astrand | 7e78ade | 2005-03-03 21:10:23 +0000 | [diff] [blame] | 455 | result.extend(bs_buf) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 456 | result.append('"') |
| 457 | |
| 458 | return ''.join(result) |
| 459 | |
| 460 | |
| 461 | class Popen(object): |
| 462 | def __init__(self, args, bufsize=0, executable=None, |
| 463 | stdin=None, stdout=None, stderr=None, |
| 464 | preexec_fn=None, close_fds=False, shell=False, |
| 465 | cwd=None, env=None, universal_newlines=False, |
| 466 | startupinfo=None, creationflags=0): |
| 467 | """Create new Popen instance.""" |
| 468 | _cleanup() |
| 469 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 470 | self._child_created = False |
Guido van Rossum | 46a05a7 | 2007-06-07 21:56:45 +0000 | [diff] [blame] | 471 | if bufsize is None: |
| 472 | bufsize = 0 # Restore default |
Walter Dörwald | aa97f04 | 2007-05-03 21:05:51 +0000 | [diff] [blame] | 473 | if not isinstance(bufsize, int): |
Peter Astrand | 738131d | 2004-11-30 21:04:45 +0000 | [diff] [blame] | 474 | raise TypeError("bufsize must be an integer") |
| 475 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 476 | if mswindows: |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 477 | if preexec_fn is not None: |
| 478 | raise ValueError("preexec_fn is not supported on Windows " |
| 479 | "platforms") |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 480 | if close_fds and (stdin is not None or stdout is not None or |
| 481 | stderr is not None): |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 482 | raise ValueError("close_fds is not supported on Windows " |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 483 | "platforms if you redirect stdin/stdout/stderr") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 484 | else: |
| 485 | # POSIX |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 486 | if startupinfo is not None: |
| 487 | raise ValueError("startupinfo is only supported on Windows " |
| 488 | "platforms") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 489 | if creationflags != 0: |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 490 | raise ValueError("creationflags is only supported on Windows " |
| 491 | "platforms") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 492 | |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 493 | self.stdin = None |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 494 | self.stdout = None |
| 495 | self.stderr = None |
| 496 | self.pid = None |
| 497 | self.returncode = None |
| 498 | self.universal_newlines = universal_newlines |
| 499 | |
| 500 | # Input and output objects. The general principle is like |
| 501 | # this: |
| 502 | # |
| 503 | # Parent Child |
| 504 | # ------ ----- |
| 505 | # p2cwrite ---stdin---> p2cread |
| 506 | # c2pread <--stdout--- c2pwrite |
| 507 | # errread <--stderr--- errwrite |
| 508 | # |
| 509 | # On POSIX, the child objects are file descriptors. On |
| 510 | # Windows, these are Windows file handles. The parent objects |
| 511 | # are file descriptors on both platforms. The parent objects |
| 512 | # are None when not using PIPEs. The child objects are None |
| 513 | # when not redirecting. |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 514 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 515 | (p2cread, p2cwrite, |
| 516 | c2pread, c2pwrite, |
| 517 | errread, errwrite) = self._get_handles(stdin, stdout, stderr) |
| 518 | |
| 519 | self._execute_child(args, executable, preexec_fn, close_fds, |
| 520 | cwd, env, universal_newlines, |
| 521 | startupinfo, creationflags, shell, |
| 522 | p2cread, p2cwrite, |
| 523 | c2pread, c2pwrite, |
| 524 | errread, errwrite) |
| 525 | |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 526 | # On Windows, you cannot just redirect one or two handles: You |
| 527 | # either have to redirect all three or none. If the subprocess |
| 528 | # user has only redirected one or two handles, we are |
| 529 | # automatically creating PIPEs for the rest. We should close |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 530 | # these after the process is started. See bug #1124861. |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 531 | if mswindows: |
| 532 | if stdin is None and p2cwrite is not None: |
| 533 | os.close(p2cwrite) |
| 534 | p2cwrite = None |
| 535 | if stdout is None and c2pread is not None: |
| 536 | os.close(c2pread) |
| 537 | c2pread = None |
| 538 | if stderr is None and errread is not None: |
| 539 | os.close(errread) |
| 540 | errread = None |
| 541 | |
Guido van Rossum | c2f93dc | 2007-05-24 00:50:02 +0000 | [diff] [blame] | 542 | if bufsize == 0: |
| 543 | bufsize = 1 # Nearly unbuffered (XXX for now) |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 544 | if p2cwrite is not None: |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 545 | self.stdin = io.open(p2cwrite, 'wb', bufsize) |
| 546 | if self.universal_newlines: |
| 547 | self.stdin = io.TextIOWrapper(self.stdin) |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 548 | if c2pread is not None: |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 549 | self.stdout = io.open(c2pread, 'rb', bufsize) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 550 | if universal_newlines: |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 551 | self.stdout = io.TextIOWrapper(self.stdout) |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 552 | if errread is not None: |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 553 | self.stderr = io.open(errread, 'rb', bufsize) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 554 | if universal_newlines: |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 555 | self.stderr = io.TextIOWrapper(self.stderr) |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 556 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 557 | |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 558 | def _translate_newlines(self, data, encoding): |
| 559 | data = data.replace(b"\r\n", b"\n").replace(b"\r", b"\n") |
| 560 | return data.decode(encoding) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 561 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 562 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 563 | def __del__(self, sys=sys): |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 564 | if not self._child_created: |
| 565 | # We didn't get to successfully create a child process. |
| 566 | return |
| 567 | # In case the child hasn't been waited on, check if it's done. |
Christian Heimes | a37d4c6 | 2007-12-04 23:02:19 +0000 | [diff] [blame] | 568 | self.poll(_deadstate=sys.maxsize) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 569 | if self.returncode is None and _active is not None: |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 570 | # Child is still running, keep us alive until we can wait on it. |
| 571 | _active.append(self) |
| 572 | |
| 573 | |
Peter Astrand | 23109f0 | 2005-03-03 20:28:59 +0000 | [diff] [blame] | 574 | def communicate(self, input=None): |
| 575 | """Interact with process: Send data to stdin. Read data from |
| 576 | stdout and stderr, until end-of-file is reached. Wait for |
| 577 | process to terminate. The optional input argument should be a |
| 578 | string to be sent to the child process, or None, if no data |
| 579 | should be sent to the child. |
Tim Peters | eba28be | 2005-03-28 01:08:02 +0000 | [diff] [blame] | 580 | |
Peter Astrand | 23109f0 | 2005-03-03 20:28:59 +0000 | [diff] [blame] | 581 | communicate() returns a tuple (stdout, stderr).""" |
| 582 | |
| 583 | # Optimization: If we are only using one pipe, or no pipe at |
| 584 | # all, using select() or threads is unnecessary. |
| 585 | if [self.stdin, self.stdout, self.stderr].count(None) >= 2: |
Tim Peters | eba28be | 2005-03-28 01:08:02 +0000 | [diff] [blame] | 586 | stdout = None |
| 587 | stderr = None |
Peter Astrand | 23109f0 | 2005-03-03 20:28:59 +0000 | [diff] [blame] | 588 | if self.stdin: |
| 589 | if input: |
| 590 | self.stdin.write(input) |
| 591 | self.stdin.close() |
| 592 | elif self.stdout: |
| 593 | stdout = self.stdout.read() |
| 594 | elif self.stderr: |
| 595 | stderr = self.stderr.read() |
| 596 | self.wait() |
| 597 | return (stdout, stderr) |
Tim Peters | eba28be | 2005-03-28 01:08:02 +0000 | [diff] [blame] | 598 | |
Peter Astrand | 23109f0 | 2005-03-03 20:28:59 +0000 | [diff] [blame] | 599 | return self._communicate(input) |
| 600 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 601 | |
| 602 | if mswindows: |
| 603 | # |
| 604 | # Windows methods |
| 605 | # |
| 606 | def _get_handles(self, stdin, stdout, stderr): |
| 607 | """Construct and return tupel with IO objects: |
| 608 | p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite |
| 609 | """ |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 610 | if stdin is None and stdout is None and stderr is None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 611 | return (None, None, None, None, None, None) |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 612 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 613 | p2cread, p2cwrite = None, None |
| 614 | c2pread, c2pwrite = None, None |
| 615 | errread, errwrite = None, None |
| 616 | |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 617 | if stdin is None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 618 | p2cread = GetStdHandle(STD_INPUT_HANDLE) |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 619 | if p2cread is not None: |
| 620 | pass |
| 621 | elif stdin is None or stdin == PIPE: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 622 | p2cread, p2cwrite = CreatePipe(None, 0) |
| 623 | # Detach and turn into fd |
| 624 | p2cwrite = p2cwrite.Detach() |
| 625 | p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0) |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 626 | elif isinstance(stdin, int): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 627 | p2cread = msvcrt.get_osfhandle(stdin) |
| 628 | else: |
| 629 | # Assuming file-like object |
| 630 | p2cread = msvcrt.get_osfhandle(stdin.fileno()) |
| 631 | p2cread = self._make_inheritable(p2cread) |
| 632 | |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 633 | if stdout is None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 634 | c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE) |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 635 | if c2pwrite is not None: |
| 636 | pass |
| 637 | elif stdout is None or stdout == PIPE: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 638 | c2pread, c2pwrite = CreatePipe(None, 0) |
| 639 | # Detach and turn into fd |
| 640 | c2pread = c2pread.Detach() |
| 641 | c2pread = msvcrt.open_osfhandle(c2pread, 0) |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 642 | elif isinstance(stdout, int): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 643 | c2pwrite = msvcrt.get_osfhandle(stdout) |
| 644 | else: |
| 645 | # Assuming file-like object |
| 646 | c2pwrite = msvcrt.get_osfhandle(stdout.fileno()) |
| 647 | c2pwrite = self._make_inheritable(c2pwrite) |
| 648 | |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 649 | if stderr is None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 650 | errwrite = GetStdHandle(STD_ERROR_HANDLE) |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 651 | if errwrite is not None: |
| 652 | pass |
| 653 | elif stderr is None or stderr == PIPE: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 654 | errread, errwrite = CreatePipe(None, 0) |
| 655 | # Detach and turn into fd |
| 656 | errread = errread.Detach() |
| 657 | errread = msvcrt.open_osfhandle(errread, 0) |
| 658 | elif stderr == STDOUT: |
| 659 | errwrite = c2pwrite |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 660 | elif isinstance(stderr, int): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 661 | errwrite = msvcrt.get_osfhandle(stderr) |
| 662 | else: |
| 663 | # Assuming file-like object |
| 664 | errwrite = msvcrt.get_osfhandle(stderr.fileno()) |
| 665 | errwrite = self._make_inheritable(errwrite) |
| 666 | |
| 667 | return (p2cread, p2cwrite, |
| 668 | c2pread, c2pwrite, |
| 669 | errread, errwrite) |
| 670 | |
| 671 | |
| 672 | def _make_inheritable(self, handle): |
| 673 | """Return a duplicate of handle, which is inheritable""" |
| 674 | return DuplicateHandle(GetCurrentProcess(), handle, |
| 675 | GetCurrentProcess(), 0, 1, |
| 676 | DUPLICATE_SAME_ACCESS) |
| 677 | |
| 678 | |
| 679 | def _find_w9xpopen(self): |
| 680 | """Find and return absolut path to w9xpopen.exe""" |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 681 | w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)), |
| 682 | "w9xpopen.exe") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 683 | if not os.path.exists(w9xpopen): |
| 684 | # Eeek - file-not-found - possibly an embedding |
| 685 | # situation - see if we can locate it in sys.exec_prefix |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 686 | w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix), |
| 687 | "w9xpopen.exe") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 688 | if not os.path.exists(w9xpopen): |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 689 | raise RuntimeError("Cannot locate w9xpopen.exe, which is " |
| 690 | "needed for Popen to work with your " |
| 691 | "shell or platform.") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 692 | return w9xpopen |
| 693 | |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 694 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 695 | def _execute_child(self, args, executable, preexec_fn, close_fds, |
| 696 | cwd, env, universal_newlines, |
| 697 | startupinfo, creationflags, shell, |
| 698 | p2cread, p2cwrite, |
| 699 | c2pread, c2pwrite, |
| 700 | errread, errwrite): |
| 701 | """Execute program (MS Windows version)""" |
| 702 | |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 703 | if not isinstance(args, str): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 704 | args = list2cmdline(args) |
| 705 | |
Peter Astrand | c1d6536 | 2004-11-07 14:30:34 +0000 | [diff] [blame] | 706 | # Process startup details |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 707 | if startupinfo is None: |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 708 | startupinfo = STARTUPINFO() |
| 709 | if None not in (p2cread, c2pwrite, errwrite): |
Peter Astrand | c1d6536 | 2004-11-07 14:30:34 +0000 | [diff] [blame] | 710 | startupinfo.dwFlags |= STARTF_USESTDHANDLES |
| 711 | startupinfo.hStdInput = p2cread |
| 712 | startupinfo.hStdOutput = c2pwrite |
| 713 | startupinfo.hStdError = errwrite |
| 714 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 715 | if shell: |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 716 | startupinfo.dwFlags |= STARTF_USESHOWWINDOW |
| 717 | startupinfo.wShowWindow = SW_HIDE |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 718 | comspec = os.environ.get("COMSPEC", "cmd.exe") |
| 719 | args = comspec + " /c " + args |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 720 | if (GetVersion() >= 0x80000000 or |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 721 | os.path.basename(comspec).lower() == "command.com"): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 722 | # Win9x, or using command.com on NT. We need to |
| 723 | # use the w9xpopen intermediate program. For more |
| 724 | # information, see KB Q150956 |
| 725 | # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp) |
| 726 | w9xpopen = self._find_w9xpopen() |
| 727 | args = '"%s" %s' % (w9xpopen, args) |
| 728 | # Not passing CREATE_NEW_CONSOLE has been known to |
| 729 | # cause random failures on win9x. Specifically a |
| 730 | # dialog: "Your program accessed mem currently in |
| 731 | # use at xxx" and a hopeful warning about the |
| 732 | # stability of your system. Cost is Ctrl+C wont |
| 733 | # kill children. |
| 734 | creationflags |= CREATE_NEW_CONSOLE |
| 735 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 736 | # Start the process |
| 737 | try: |
| 738 | hp, ht, pid, tid = CreateProcess(executable, args, |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 739 | # no special security |
| 740 | None, None, |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 741 | int(not close_fds), |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 742 | creationflags, |
| 743 | env, |
| 744 | cwd, |
| 745 | startupinfo) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 746 | except pywintypes.error as e: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 747 | # Translate pywintypes.error to WindowsError, which is |
| 748 | # a subclass of OSError. FIXME: We should really |
| 749 | # translate errno using _sys_errlist (or simliar), but |
| 750 | # how can this be done from Python? |
| 751 | raise WindowsError(*e.args) |
| 752 | |
| 753 | # Retain the process handle, but close the thread handle |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 754 | self._child_created = True |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 755 | self._handle = hp |
| 756 | self.pid = pid |
| 757 | ht.Close() |
| 758 | |
Andrew M. Kuchling | 51ee66e | 2004-10-12 16:38:42 +0000 | [diff] [blame] | 759 | # Child is launched. Close the parent's copy of those pipe |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 760 | # handles that only the child should have open. You need |
| 761 | # to make sure that no handles to the write end of the |
| 762 | # output pipe are maintained in this process or else the |
| 763 | # pipe will not close when the child process exits and the |
| 764 | # ReadFile will hang. |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 765 | if p2cread is not None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 766 | p2cread.Close() |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 767 | if c2pwrite is not None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 768 | c2pwrite.Close() |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 769 | if errwrite is not None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 770 | errwrite.Close() |
| 771 | |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 772 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 773 | def poll(self, _deadstate=None): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 774 | """Check if child process has terminated. Returns returncode |
| 775 | attribute.""" |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 776 | if self.returncode is None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 777 | if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0: |
| 778 | self.returncode = GetExitCodeProcess(self._handle) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 779 | return self.returncode |
| 780 | |
| 781 | |
| 782 | def wait(self): |
| 783 | """Wait for child process to terminate. Returns returncode |
| 784 | attribute.""" |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 785 | if self.returncode is None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 786 | obj = WaitForSingleObject(self._handle, INFINITE) |
| 787 | self.returncode = GetExitCodeProcess(self._handle) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 788 | return self.returncode |
| 789 | |
| 790 | |
| 791 | def _readerthread(self, fh, buffer): |
| 792 | buffer.append(fh.read()) |
| 793 | |
| 794 | |
Peter Astrand | 23109f0 | 2005-03-03 20:28:59 +0000 | [diff] [blame] | 795 | def _communicate(self, input): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 796 | stdout = None # Return |
| 797 | stderr = None # Return |
| 798 | |
| 799 | if self.stdout: |
| 800 | stdout = [] |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 801 | stdout_thread = threading.Thread(target=self._readerthread, |
| 802 | args=(self.stdout, stdout)) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 803 | stdout_thread.setDaemon(True) |
| 804 | stdout_thread.start() |
| 805 | if self.stderr: |
| 806 | stderr = [] |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 807 | stderr_thread = threading.Thread(target=self._readerthread, |
| 808 | args=(self.stderr, stderr)) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 809 | stderr_thread.setDaemon(True) |
| 810 | stderr_thread.start() |
| 811 | |
| 812 | if self.stdin: |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 813 | if input is not None: |
Guido van Rossum | c12a813 | 2007-10-26 04:29:23 +0000 | [diff] [blame] | 814 | if isinstance(input, str): |
| 815 | input = input.encode() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 816 | self.stdin.write(input) |
| 817 | self.stdin.close() |
| 818 | |
| 819 | if self.stdout: |
| 820 | stdout_thread.join() |
| 821 | if self.stderr: |
| 822 | stderr_thread.join() |
| 823 | |
| 824 | # All data exchanged. Translate lists into strings. |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 825 | if stdout is not None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 826 | stdout = stdout[0] |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 827 | if stderr is not None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 828 | stderr = stderr[0] |
| 829 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 830 | self.wait() |
| 831 | return (stdout, stderr) |
| 832 | |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 833 | def send_signal(self, sig): |
| 834 | """Send a signal to the process |
| 835 | """ |
| 836 | if sig == signal.SIGTERM: |
| 837 | self.terminate() |
| 838 | else: |
| 839 | raise ValueError("Only SIGTERM is supported on Windows") |
| 840 | |
| 841 | def terminate(self): |
| 842 | """Terminates the process |
| 843 | """ |
| 844 | TerminateProcess(self._handle, 1) |
| 845 | |
| 846 | kill = terminate |
| 847 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 848 | else: |
| 849 | # |
| 850 | # POSIX methods |
| 851 | # |
| 852 | def _get_handles(self, stdin, stdout, stderr): |
| 853 | """Construct and return tupel with IO objects: |
| 854 | p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite |
| 855 | """ |
| 856 | p2cread, p2cwrite = None, None |
| 857 | c2pread, c2pwrite = None, None |
| 858 | errread, errwrite = None, None |
| 859 | |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 860 | if stdin is None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 861 | pass |
| 862 | elif stdin == PIPE: |
| 863 | p2cread, p2cwrite = os.pipe() |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 864 | elif isinstance(stdin, int): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 865 | p2cread = stdin |
| 866 | else: |
| 867 | # Assuming file-like object |
| 868 | p2cread = stdin.fileno() |
| 869 | |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 870 | if stdout is None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 871 | pass |
| 872 | elif stdout == PIPE: |
| 873 | c2pread, c2pwrite = os.pipe() |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 874 | elif isinstance(stdout, int): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 875 | c2pwrite = stdout |
| 876 | else: |
| 877 | # Assuming file-like object |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 878 | c2pwrite = stdout.fileno() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 879 | |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 880 | if stderr is None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 881 | pass |
| 882 | elif stderr == PIPE: |
| 883 | errread, errwrite = os.pipe() |
| 884 | elif stderr == STDOUT: |
| 885 | errwrite = c2pwrite |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 886 | elif isinstance(stderr, int): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 887 | errwrite = stderr |
| 888 | else: |
| 889 | # Assuming file-like object |
| 890 | errwrite = stderr.fileno() |
| 891 | |
| 892 | return (p2cread, p2cwrite, |
| 893 | c2pread, c2pwrite, |
| 894 | errread, errwrite) |
| 895 | |
| 896 | |
| 897 | def _set_cloexec_flag(self, fd): |
| 898 | try: |
| 899 | cloexec_flag = fcntl.FD_CLOEXEC |
| 900 | except AttributeError: |
| 901 | cloexec_flag = 1 |
| 902 | |
| 903 | old = fcntl.fcntl(fd, fcntl.F_GETFD) |
| 904 | fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag) |
| 905 | |
| 906 | |
| 907 | def _close_fds(self, but): |
Christian Heimes | fdab48e | 2008-01-20 09:06:41 +0000 | [diff] [blame] | 908 | os.closerange(3, but) |
| 909 | os.closerange(but + 1, MAXFD) |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 910 | |
| 911 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 912 | def _execute_child(self, args, executable, preexec_fn, close_fds, |
| 913 | cwd, env, universal_newlines, |
| 914 | startupinfo, creationflags, shell, |
| 915 | p2cread, p2cwrite, |
| 916 | c2pread, c2pwrite, |
| 917 | errread, errwrite): |
| 918 | """Execute program (POSIX version)""" |
| 919 | |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 920 | if isinstance(args, str): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 921 | args = [args] |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 922 | else: |
| 923 | args = list(args) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 924 | |
| 925 | if shell: |
| 926 | args = ["/bin/sh", "-c"] + args |
| 927 | |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 928 | if executable is None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 929 | executable = args[0] |
| 930 | |
| 931 | # For transferring possible exec failure from child to parent |
| 932 | # The first char specifies the exception type: 0 means |
| 933 | # OSError, 1 means some other error. |
| 934 | errpipe_read, errpipe_write = os.pipe() |
| 935 | self._set_cloexec_flag(errpipe_write) |
| 936 | |
Christian Heimes | fdab48e | 2008-01-20 09:06:41 +0000 | [diff] [blame] | 937 | gc_was_enabled = gc.isenabled() |
| 938 | # Disable gc to avoid bug where gc -> file_dealloc -> |
| 939 | # write to stderr -> hang. http://bugs.python.org/issue1336 |
| 940 | gc.disable() |
| 941 | try: |
| 942 | self.pid = os.fork() |
| 943 | except: |
| 944 | if gc_was_enabled: |
| 945 | gc.enable() |
| 946 | raise |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 947 | self._child_created = True |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 948 | if self.pid == 0: |
| 949 | # Child |
| 950 | try: |
| 951 | # Close parent's pipe ends |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 952 | if p2cwrite is not None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 953 | os.close(p2cwrite) |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 954 | if c2pread is not None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 955 | os.close(c2pread) |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 956 | if errread is not None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 957 | os.close(errread) |
| 958 | os.close(errpipe_read) |
| 959 | |
| 960 | # Dup fds for child |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 961 | if p2cread is not None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 962 | os.dup2(p2cread, 0) |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 963 | if c2pwrite is not None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 964 | os.dup2(c2pwrite, 1) |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 965 | if errwrite is not None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 966 | os.dup2(errwrite, 2) |
| 967 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 968 | # Close pipe fds. Make sure we don't close the same |
| 969 | # fd more than once, or standard fds. |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 970 | if p2cread is not None and p2cread not in (0,): |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 971 | os.close(p2cread) |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 972 | if c2pwrite is not None and c2pwrite not in (p2cread, 1): |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 973 | os.close(c2pwrite) |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 974 | if (errwrite is not None and |
| 975 | errwrite not in (p2cread, c2pwrite, 2)): |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 976 | os.close(errwrite) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 977 | |
| 978 | # Close all other fds, if asked for |
| 979 | if close_fds: |
| 980 | self._close_fds(but=errpipe_write) |
| 981 | |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 982 | if cwd is not None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 983 | os.chdir(cwd) |
| 984 | |
| 985 | if preexec_fn: |
Neal Norwitz | d910855 | 2006-03-17 08:00:19 +0000 | [diff] [blame] | 986 | preexec_fn() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 987 | |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 988 | if env is None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 989 | os.execvp(executable, args) |
| 990 | else: |
| 991 | os.execvpe(executable, args, env) |
| 992 | |
| 993 | except: |
| 994 | exc_type, exc_value, tb = sys.exc_info() |
| 995 | # Save the traceback and attach it to the exception object |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 996 | exc_lines = traceback.format_exception(exc_type, |
| 997 | exc_value, |
| 998 | tb) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 999 | exc_value.child_traceback = ''.join(exc_lines) |
| 1000 | os.write(errpipe_write, pickle.dumps(exc_value)) |
| 1001 | |
| 1002 | # This exitcode won't be reported to applications, so it |
| 1003 | # really doesn't matter what we return. |
| 1004 | os._exit(255) |
| 1005 | |
| 1006 | # Parent |
Christian Heimes | fdab48e | 2008-01-20 09:06:41 +0000 | [diff] [blame] | 1007 | if gc_was_enabled: |
| 1008 | gc.enable() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1009 | os.close(errpipe_write) |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 1010 | if p2cread is not None and p2cwrite is not None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1011 | os.close(p2cread) |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 1012 | if c2pwrite is not None and c2pread is not None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1013 | os.close(c2pwrite) |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 1014 | if errwrite is not None and errread is not None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1015 | os.close(errwrite) |
| 1016 | |
| 1017 | # Wait for exec to fail or succeed; possibly raising exception |
| 1018 | data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB |
| 1019 | os.close(errpipe_read) |
Guido van Rossum | af2362a | 2007-05-15 22:32:02 +0000 | [diff] [blame] | 1020 | if data: |
Peter Astrand | f791d7a | 2005-01-01 09:38:57 +0000 | [diff] [blame] | 1021 | os.waitpid(self.pid, 0) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1022 | child_exception = pickle.loads(data) |
| 1023 | raise child_exception |
| 1024 | |
| 1025 | |
| 1026 | def _handle_exitstatus(self, sts): |
| 1027 | if os.WIFSIGNALED(sts): |
| 1028 | self.returncode = -os.WTERMSIG(sts) |
| 1029 | elif os.WIFEXITED(sts): |
| 1030 | self.returncode = os.WEXITSTATUS(sts) |
| 1031 | else: |
| 1032 | # Should never happen |
| 1033 | raise RuntimeError("Unknown child exit status!") |
| 1034 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1035 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 1036 | def poll(self, _deadstate=None): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1037 | """Check if child process has terminated. Returns returncode |
| 1038 | attribute.""" |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 1039 | if self.returncode is None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1040 | try: |
| 1041 | pid, sts = os.waitpid(self.pid, os.WNOHANG) |
| 1042 | if pid == self.pid: |
| 1043 | self._handle_exitstatus(sts) |
| 1044 | except os.error: |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 1045 | if _deadstate is not None: |
| 1046 | self.returncode = _deadstate |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1047 | return self.returncode |
| 1048 | |
| 1049 | |
| 1050 | def wait(self): |
| 1051 | """Wait for child process to terminate. Returns returncode |
| 1052 | attribute.""" |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 1053 | if self.returncode is None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1054 | pid, sts = os.waitpid(self.pid, 0) |
| 1055 | self._handle_exitstatus(sts) |
| 1056 | return self.returncode |
| 1057 | |
| 1058 | |
Peter Astrand | 23109f0 | 2005-03-03 20:28:59 +0000 | [diff] [blame] | 1059 | def _communicate(self, input): |
Guido van Rossum | bae07c9 | 2007-10-08 02:46:15 +0000 | [diff] [blame] | 1060 | if self.stdin: |
| 1061 | if isinstance(input, str): # Unicode |
| 1062 | input = input.encode("utf-8") # XXX What else? |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 1063 | input = bytes(input) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1064 | read_set = [] |
| 1065 | write_set = [] |
| 1066 | stdout = None # Return |
| 1067 | stderr = None # Return |
| 1068 | |
| 1069 | if self.stdin: |
| 1070 | # Flush stdio buffer. This might block, if the user has |
| 1071 | # been writing to .stdin in an uncontrolled fashion. |
| 1072 | self.stdin.flush() |
| 1073 | if input: |
| 1074 | write_set.append(self.stdin) |
| 1075 | else: |
| 1076 | self.stdin.close() |
| 1077 | if self.stdout: |
| 1078 | read_set.append(self.stdout) |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 1079 | stdout = [] |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1080 | if self.stderr: |
| 1081 | read_set.append(self.stderr) |
| 1082 | stderr = [] |
| 1083 | |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 1084 | input_offset = 0 |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1085 | while read_set or write_set: |
| 1086 | rlist, wlist, xlist = select.select(read_set, write_set, []) |
| 1087 | |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 1088 | # XXX Rewrite these to use non-blocking I/O on the |
| 1089 | # file objects; they are no longer using C stdio! |
| 1090 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1091 | if self.stdin in wlist: |
| 1092 | # When select has indicated that the file is writable, |
| 1093 | # we can write up to PIPE_BUF bytes without risk |
| 1094 | # blocking. POSIX defines PIPE_BUF >= 512 |
Guido van Rossum | bae07c9 | 2007-10-08 02:46:15 +0000 | [diff] [blame] | 1095 | chunk = input[input_offset : input_offset + 512] |
| 1096 | bytes_written = os.write(self.stdin.fileno(), chunk) |
Thomas Wouters | 9fe394c | 2007-02-05 01:24:16 +0000 | [diff] [blame] | 1097 | input_offset += bytes_written |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 1098 | if input_offset >= len(input): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1099 | self.stdin.close() |
| 1100 | write_set.remove(self.stdin) |
| 1101 | |
| 1102 | if self.stdout in rlist: |
| 1103 | data = os.read(self.stdout.fileno(), 1024) |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 1104 | if not data: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1105 | self.stdout.close() |
| 1106 | read_set.remove(self.stdout) |
| 1107 | stdout.append(data) |
| 1108 | |
| 1109 | if self.stderr in rlist: |
| 1110 | data = os.read(self.stderr.fileno(), 1024) |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 1111 | if not data: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1112 | self.stderr.close() |
| 1113 | read_set.remove(self.stderr) |
| 1114 | stderr.append(data) |
| 1115 | |
| 1116 | # All data exchanged. Translate lists into strings. |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 1117 | if stdout is not None: |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 1118 | stdout = b"".join(stdout) |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 1119 | if stderr is not None: |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 1120 | stderr = b"".join(stderr) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1121 | |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 1122 | # Translate newlines, if requested. |
| 1123 | # This also turns bytes into strings. |
Guido van Rossum | c9e363c | 2007-05-15 23:18:55 +0000 | [diff] [blame] | 1124 | if self.universal_newlines: |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 1125 | if stdout is not None: |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 1126 | stdout = self._translate_newlines(stdout, |
| 1127 | self.stdout.encoding) |
Guido van Rossum | fa0054a | 2007-05-24 04:05:35 +0000 | [diff] [blame] | 1128 | if stderr is not None: |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 1129 | stderr = self._translate_newlines(stderr, |
| 1130 | self.stderr.encoding) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1131 | |
| 1132 | self.wait() |
| 1133 | return (stdout, stderr) |
| 1134 | |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 1135 | def send_signal(self, sig): |
| 1136 | """Send a signal to the process |
| 1137 | """ |
| 1138 | os.kill(self.pid, sig) |
| 1139 | |
| 1140 | def terminate(self): |
| 1141 | """Terminate the process with SIGTERM |
| 1142 | """ |
| 1143 | self.send_signal(signal.SIGTERM) |
| 1144 | |
| 1145 | def kill(self): |
| 1146 | """Kill the process with SIGKILL |
| 1147 | """ |
| 1148 | self.send_signal(signal.SIGKILL) |
| 1149 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1150 | |
| 1151 | def _demo_posix(): |
| 1152 | # |
| 1153 | # Example 1: Simple redirection: Get process list |
| 1154 | # |
| 1155 | plist = Popen(["ps"], stdout=PIPE).communicate()[0] |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1156 | print("Process list:") |
| 1157 | print(plist) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1158 | |
| 1159 | # |
| 1160 | # Example 2: Change uid before executing child |
| 1161 | # |
| 1162 | if os.getuid() == 0: |
| 1163 | p = Popen(["id"], preexec_fn=lambda: os.setuid(100)) |
| 1164 | p.wait() |
| 1165 | |
| 1166 | # |
| 1167 | # Example 3: Connecting several subprocesses |
| 1168 | # |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1169 | print("Looking for 'hda'...") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1170 | p1 = Popen(["dmesg"], stdout=PIPE) |
| 1171 | p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1172 | print(repr(p2.communicate()[0])) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1173 | |
| 1174 | # |
| 1175 | # Example 4: Catch execution error |
| 1176 | # |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1177 | print() |
| 1178 | print("Trying a weird file...") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1179 | try: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1180 | print(Popen(["/this/path/does/not/exist"]).communicate()) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 1181 | except OSError as e: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1182 | if e.errno == errno.ENOENT: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1183 | print("The file didn't exist. I thought so...") |
| 1184 | print("Child traceback:") |
| 1185 | print(e.child_traceback) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1186 | else: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1187 | print("Error", e.errno) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1188 | else: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1189 | print("Gosh. No error.", file=sys.stderr) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1190 | |
| 1191 | |
| 1192 | def _demo_windows(): |
| 1193 | # |
| 1194 | # Example 1: Connecting several subprocesses |
| 1195 | # |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1196 | print("Looking for 'PROMPT' in set output...") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1197 | p1 = Popen("set", stdout=PIPE, shell=True) |
| 1198 | p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE) |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1199 | print(repr(p2.communicate()[0])) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1200 | |
| 1201 | # |
| 1202 | # Example 2: Simple execution of program |
| 1203 | # |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1204 | print("Executing calc...") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1205 | p = Popen("calc") |
| 1206 | p.wait() |
| 1207 | |
| 1208 | |
| 1209 | if __name__ == "__main__": |
| 1210 | if mswindows: |
| 1211 | _demo_windows() |
| 1212 | else: |
| 1213 | _demo_posix() |