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