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