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