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