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