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* |
| 18 | os.popen* |
| 19 | popen2.* |
| 20 | commands.* |
| 21 | |
| 22 | Information about how the subprocess module can be used to replace these |
| 23 | modules and functions can be found below. |
| 24 | |
| 25 | |
| 26 | |
| 27 | Using the subprocess module |
| 28 | =========================== |
| 29 | This module defines one class called Popen: |
| 30 | |
| 31 | class Popen(args, bufsize=0, executable=None, |
| 32 | stdin=None, stdout=None, stderr=None, |
| 33 | preexec_fn=None, close_fds=False, shell=False, |
| 34 | cwd=None, env=None, universal_newlines=False, |
| 35 | startupinfo=None, creationflags=0): |
| 36 | |
| 37 | |
| 38 | Arguments are: |
| 39 | |
| 40 | args should be a string, or a sequence of program arguments. The |
| 41 | program to execute is normally the first item in the args sequence or |
| 42 | string, but can be explicitly set by using the executable argument. |
| 43 | |
| 44 | On UNIX, with shell=False (default): In this case, the Popen class |
| 45 | uses os.execvp() to execute the child program. args should normally |
| 46 | be a sequence. A string will be treated as a sequence with the string |
| 47 | as the only item (the program to execute). |
| 48 | |
| 49 | On UNIX, with shell=True: If args is a string, it specifies the |
| 50 | command string to execute through the shell. If args is a sequence, |
| 51 | the first item specifies the command string, and any additional items |
| 52 | will be treated as additional shell arguments. |
| 53 | |
| 54 | On Windows: the Popen class uses CreateProcess() to execute the child |
| 55 | program, which operates on strings. If args is a sequence, it will be |
| 56 | converted to a string using the list2cmdline method. Please note that |
| 57 | not all MS Windows applications interpret the command line the same |
| 58 | way: The list2cmdline is designed for applications using the same |
| 59 | rules as the MS C runtime. |
| 60 | |
| 61 | bufsize, if given, has the same meaning as the corresponding argument |
| 62 | to the built-in open() function: 0 means unbuffered, 1 means line |
| 63 | buffered, any other positive value means use a buffer of |
| 64 | (approximately) that size. A negative bufsize means to use the system |
| 65 | default, which usually means fully buffered. The default value for |
| 66 | bufsize is 0 (unbuffered). |
| 67 | |
| 68 | stdin, stdout and stderr specify the executed programs' standard |
| 69 | input, standard output and standard error file handles, respectively. |
| 70 | Valid values are PIPE, an existing file descriptor (a positive |
| 71 | integer), an existing file object, and None. PIPE indicates that a |
| 72 | new pipe to the child should be created. With None, no redirection |
| 73 | will occur; the child's file handles will be inherited from the |
| 74 | parent. Additionally, stderr can be STDOUT, which indicates that the |
| 75 | stderr data from the applications should be captured into the same |
| 76 | file handle as for stdout. |
| 77 | |
| 78 | If preexec_fn is set to a callable object, this object will be called |
| 79 | in the child process just before the child is executed. |
| 80 | |
| 81 | If close_fds is true, all file descriptors except 0, 1 and 2 will be |
| 82 | closed before the child process is executed. |
| 83 | |
| 84 | if shell is true, the specified command will be executed through the |
| 85 | shell. |
| 86 | |
| 87 | If cwd is not None, the current directory will be changed to cwd |
| 88 | before the child is executed. |
| 89 | |
| 90 | If env is not None, it defines the environment variables for the new |
| 91 | process. |
| 92 | |
| 93 | If universal_newlines is true, the file objects stdout and stderr are |
| 94 | opened as a text files, but lines may be terminated by any of '\n', |
| 95 | the Unix end-of-line convention, '\r', the Macintosh convention or |
| 96 | '\r\n', the Windows convention. All of these external representations |
| 97 | are seen as '\n' by the Python program. Note: This feature is only |
| 98 | available if Python is built with universal newline support (the |
| 99 | default). Also, the newlines attribute of the file objects stdout, |
| 100 | stdin and stderr are not updated by the communicate() method. |
| 101 | |
| 102 | The startupinfo and creationflags, if given, will be passed to the |
| 103 | underlying CreateProcess() function. They can specify things such as |
| 104 | appearance of the main window and priority for the new process. |
| 105 | (Windows only) |
| 106 | |
| 107 | |
Gregory P. Smith | 97f49f4 | 2008-12-04 20:21:09 +0000 | [diff] [blame] | 108 | This module also defines some shortcut functions: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 109 | |
Peter Astrand | 5f5e141 | 2004-12-05 20:15:36 +0000 | [diff] [blame] | 110 | call(*popenargs, **kwargs): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 111 | Run command with arguments. Wait for command to complete, then |
| 112 | return the returncode attribute. |
| 113 | |
| 114 | The arguments are the same as for the Popen constructor. Example: |
| 115 | |
| 116 | retcode = call(["ls", "-l"]) |
| 117 | |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 118 | check_call(*popenargs, **kwargs): |
| 119 | Run command with arguments. Wait for command to complete. If the |
| 120 | exit code was zero then return, otherwise raise |
| 121 | CalledProcessError. The CalledProcessError object will have the |
Peter Astrand | 7d1d436 | 2006-07-14 14:04:45 +0000 | [diff] [blame] | 122 | return code in the returncode attribute. |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 123 | |
| 124 | The arguments are the same as for the Popen constructor. Example: |
| 125 | |
| 126 | check_call(["ls", "-l"]) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 127 | |
Gregory P. Smith | 2657680 | 2008-12-05 02:27:01 +0000 | [diff] [blame] | 128 | check_output(*popenargs, **kwargs): |
Georg Brandl | 6ab5d08 | 2009-12-20 14:33:20 +0000 | [diff] [blame] | 129 | Run command with arguments and return its output as a byte string. |
Gregory P. Smith | 97f49f4 | 2008-12-04 20:21:09 +0000 | [diff] [blame] | 130 | |
Georg Brandl | 6ab5d08 | 2009-12-20 14:33:20 +0000 | [diff] [blame] | 131 | If the exit code was non-zero it raises a CalledProcessError. The |
| 132 | CalledProcessError object will have the return code in the returncode |
| 133 | attribute and output in the output attribute. |
Gregory P. Smith | 97f49f4 | 2008-12-04 20:21:09 +0000 | [diff] [blame] | 134 | |
Georg Brandl | 6ab5d08 | 2009-12-20 14:33:20 +0000 | [diff] [blame] | 135 | The arguments are the same as for the Popen constructor. Example: |
Gregory P. Smith | 97f49f4 | 2008-12-04 20:21:09 +0000 | [diff] [blame] | 136 | |
Georg Brandl | 02e7dfd | 2009-12-28 08:09:32 +0000 | [diff] [blame] | 137 | output = check_output(["ls", "-l", "/dev/null"]) |
| 138 | |
Gregory P. Smith | 97f49f4 | 2008-12-04 20:21:09 +0000 | [diff] [blame] | 139 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 140 | Exceptions |
| 141 | ---------- |
| 142 | Exceptions raised in the child process, before the new program has |
| 143 | started to execute, will be re-raised in the parent. Additionally, |
| 144 | the exception object will have one extra attribute called |
| 145 | 'child_traceback', which is a string containing traceback information |
Ezio Melotti | f5469cf | 2013-08-17 15:43:51 +0300 | [diff] [blame] | 146 | from the child's point of view. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 147 | |
| 148 | The most common exception raised is OSError. This occurs, for |
| 149 | example, when trying to execute a non-existent file. Applications |
| 150 | should prepare for OSErrors. |
| 151 | |
| 152 | A ValueError will be raised if Popen is called with invalid arguments. |
| 153 | |
Gregory P. Smith | 2657680 | 2008-12-05 02:27:01 +0000 | [diff] [blame] | 154 | check_call() and check_output() will raise CalledProcessError, if the |
Gregory P. Smith | 97f49f4 | 2008-12-04 20:21:09 +0000 | [diff] [blame] | 155 | called process returns a non-zero return code. |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 156 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 157 | |
| 158 | Security |
| 159 | -------- |
| 160 | Unlike some other popen functions, this implementation will never call |
| 161 | /bin/sh implicitly. This means that all characters, including shell |
| 162 | metacharacters, can safely be passed to child processes. |
| 163 | |
| 164 | |
| 165 | Popen objects |
| 166 | ============= |
| 167 | Instances of the Popen class have the following methods: |
| 168 | |
| 169 | poll() |
| 170 | Check if child process has terminated. Returns returncode |
| 171 | attribute. |
| 172 | |
| 173 | wait() |
| 174 | Wait for child process to terminate. Returns returncode attribute. |
| 175 | |
| 176 | communicate(input=None) |
| 177 | Interact with process: Send data to stdin. Read data from stdout |
| 178 | and stderr, until end-of-file is reached. Wait for process to |
Neal Norwitz | a186ee2 | 2006-12-29 03:01:53 +0000 | [diff] [blame] | 179 | terminate. The optional input argument should be a string to be |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 180 | sent to the child process, or None, if no data should be sent to |
| 181 | the child. |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 182 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 183 | communicate() returns a tuple (stdout, stderr). |
| 184 | |
| 185 | Note: The data read is buffered in memory, so do not use this |
| 186 | method if the data size is large or unlimited. |
| 187 | |
| 188 | The following attributes are also available: |
| 189 | |
| 190 | stdin |
| 191 | If the stdin argument is PIPE, this attribute is a file object |
| 192 | that provides input to the child process. Otherwise, it is None. |
| 193 | |
| 194 | stdout |
| 195 | If the stdout argument is PIPE, this attribute is a file object |
| 196 | that provides output from the child process. Otherwise, it is |
| 197 | None. |
| 198 | |
| 199 | stderr |
| 200 | If the stderr argument is PIPE, this attribute is file object that |
| 201 | provides error output from the child process. Otherwise, it is |
| 202 | None. |
| 203 | |
| 204 | pid |
| 205 | The process ID of the child process. |
| 206 | |
| 207 | returncode |
| 208 | The child return code. A None value indicates that the process |
| 209 | hasn't terminated yet. A negative value -N indicates that the |
| 210 | child was terminated by signal N (UNIX only). |
| 211 | |
| 212 | |
| 213 | Replacing older functions with the subprocess module |
| 214 | ==================================================== |
| 215 | In this section, "a ==> b" means that b can be used as a replacement |
| 216 | for a. |
| 217 | |
| 218 | Note: All functions in this section fail (more or less) silently if |
| 219 | the executed program cannot be found; this module raises an OSError |
| 220 | exception. |
| 221 | |
| 222 | In the following examples, we assume that the subprocess module is |
| 223 | imported with "from subprocess import *". |
| 224 | |
| 225 | |
| 226 | Replacing /bin/sh shell backquote |
| 227 | --------------------------------- |
| 228 | output=`mycmd myarg` |
| 229 | ==> |
| 230 | output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0] |
| 231 | |
| 232 | |
| 233 | Replacing shell pipe line |
| 234 | ------------------------- |
| 235 | output=`dmesg | grep hda` |
| 236 | ==> |
| 237 | p1 = Popen(["dmesg"], stdout=PIPE) |
Peter Astrand | 6fdf3cb | 2004-11-30 18:06:42 +0000 | [diff] [blame] | 238 | p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 239 | output = p2.communicate()[0] |
| 240 | |
| 241 | |
| 242 | Replacing os.system() |
| 243 | --------------------- |
| 244 | sts = os.system("mycmd" + " myarg") |
| 245 | ==> |
| 246 | p = Popen("mycmd" + " myarg", shell=True) |
Neal Norwitz | 8440483 | 2006-07-10 00:05:34 +0000 | [diff] [blame] | 247 | pid, sts = os.waitpid(p.pid, 0) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 248 | |
| 249 | Note: |
| 250 | |
| 251 | * Calling the program through the shell is usually not required. |
| 252 | |
| 253 | * It's easier to look at the returncode attribute than the |
| 254 | exitstatus. |
| 255 | |
| 256 | A more real-world example would look like this: |
| 257 | |
| 258 | try: |
| 259 | retcode = call("mycmd" + " myarg", shell=True) |
| 260 | if retcode < 0: |
| 261 | print >>sys.stderr, "Child was terminated by signal", -retcode |
| 262 | else: |
| 263 | print >>sys.stderr, "Child returned", retcode |
| 264 | except OSError, e: |
| 265 | print >>sys.stderr, "Execution failed:", e |
| 266 | |
| 267 | |
| 268 | Replacing os.spawn* |
| 269 | ------------------- |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 270 | P_NOWAIT example: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 271 | |
| 272 | pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") |
| 273 | ==> |
| 274 | pid = Popen(["/bin/mycmd", "myarg"]).pid |
| 275 | |
| 276 | |
| 277 | P_WAIT example: |
| 278 | |
| 279 | retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg") |
| 280 | ==> |
| 281 | retcode = call(["/bin/mycmd", "myarg"]) |
| 282 | |
| 283 | |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 284 | Vector example: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 285 | |
| 286 | os.spawnvp(os.P_NOWAIT, path, args) |
| 287 | ==> |
| 288 | Popen([path] + args[1:]) |
| 289 | |
| 290 | |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 291 | Environment example: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 292 | |
| 293 | os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env) |
| 294 | ==> |
| 295 | Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"}) |
| 296 | |
| 297 | |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 298 | Replacing os.popen* |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 299 | ------------------- |
Philip Jenvey | 8b90204 | 2009-09-29 19:10:15 +0000 | [diff] [blame] | 300 | pipe = os.popen("cmd", mode='r', bufsize) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 301 | ==> |
Philip Jenvey | 8b90204 | 2009-09-29 19:10:15 +0000 | [diff] [blame] | 302 | pipe = Popen("cmd", shell=True, bufsize=bufsize, stdout=PIPE).stdout |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 303 | |
Philip Jenvey | 8b90204 | 2009-09-29 19:10:15 +0000 | [diff] [blame] | 304 | pipe = os.popen("cmd", mode='w', bufsize) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 305 | ==> |
Philip Jenvey | 8b90204 | 2009-09-29 19:10:15 +0000 | [diff] [blame] | 306 | pipe = Popen("cmd", shell=True, bufsize=bufsize, stdin=PIPE).stdin |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 307 | |
| 308 | |
Philip Jenvey | 8b90204 | 2009-09-29 19:10:15 +0000 | [diff] [blame] | 309 | (child_stdin, child_stdout) = os.popen2("cmd", mode, bufsize) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 310 | ==> |
Philip Jenvey | 8b90204 | 2009-09-29 19:10:15 +0000 | [diff] [blame] | 311 | p = Popen("cmd", shell=True, bufsize=bufsize, |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 312 | stdin=PIPE, stdout=PIPE, close_fds=True) |
| 313 | (child_stdin, child_stdout) = (p.stdin, p.stdout) |
| 314 | |
| 315 | |
| 316 | (child_stdin, |
| 317 | child_stdout, |
Philip Jenvey | 8b90204 | 2009-09-29 19:10:15 +0000 | [diff] [blame] | 318 | child_stderr) = os.popen3("cmd", mode, bufsize) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 319 | ==> |
Philip Jenvey | 8b90204 | 2009-09-29 19:10:15 +0000 | [diff] [blame] | 320 | p = Popen("cmd", shell=True, bufsize=bufsize, |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 321 | stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) |
| 322 | (child_stdin, |
| 323 | child_stdout, |
| 324 | child_stderr) = (p.stdin, p.stdout, p.stderr) |
| 325 | |
| 326 | |
Philip Jenvey | 8b90204 | 2009-09-29 19:10:15 +0000 | [diff] [blame] | 327 | (child_stdin, child_stdout_and_stderr) = os.popen4("cmd", mode, |
| 328 | bufsize) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 329 | ==> |
Philip Jenvey | 8b90204 | 2009-09-29 19:10:15 +0000 | [diff] [blame] | 330 | p = Popen("cmd", shell=True, bufsize=bufsize, |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 331 | stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) |
| 332 | (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout) |
| 333 | |
Philip Jenvey | 8b90204 | 2009-09-29 19:10:15 +0000 | [diff] [blame] | 334 | On Unix, os.popen2, os.popen3 and os.popen4 also accept a sequence as |
| 335 | the command to execute, in which case arguments will be passed |
| 336 | directly to the program without shell intervention. This usage can be |
| 337 | replaced as follows: |
| 338 | |
| 339 | (child_stdin, child_stdout) = os.popen2(["/bin/ls", "-l"], mode, |
| 340 | bufsize) |
| 341 | ==> |
| 342 | p = Popen(["/bin/ls", "-l"], bufsize=bufsize, stdin=PIPE, stdout=PIPE) |
| 343 | (child_stdin, child_stdout) = (p.stdin, p.stdout) |
| 344 | |
| 345 | Return code handling translates as follows: |
| 346 | |
| 347 | pipe = os.popen("cmd", 'w') |
| 348 | ... |
| 349 | rc = pipe.close() |
Florent Xicluna | cf741ce | 2010-03-08 10:58:12 +0000 | [diff] [blame] | 350 | if rc is not None and rc % 256: |
Philip Jenvey | 8b90204 | 2009-09-29 19:10:15 +0000 | [diff] [blame] | 351 | print "There were some errors" |
| 352 | ==> |
| 353 | process = Popen("cmd", 'w', shell=True, stdin=PIPE) |
| 354 | ... |
| 355 | process.stdin.close() |
| 356 | if process.wait() != 0: |
| 357 | print "There were some errors" |
| 358 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 359 | |
| 360 | Replacing popen2.* |
| 361 | ------------------ |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 362 | (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode) |
| 363 | ==> |
| 364 | p = Popen(["somestring"], shell=True, bufsize=bufsize |
| 365 | stdin=PIPE, stdout=PIPE, close_fds=True) |
| 366 | (child_stdout, child_stdin) = (p.stdout, p.stdin) |
| 367 | |
Philip Jenvey | 8b90204 | 2009-09-29 19:10:15 +0000 | [diff] [blame] | 368 | On Unix, popen2 also accepts a sequence as the command to execute, in |
| 369 | which case arguments will be passed directly to the program without |
| 370 | shell intervention. This usage can be replaced as follows: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 371 | |
Philip Jenvey | 8b90204 | 2009-09-29 19:10:15 +0000 | [diff] [blame] | 372 | (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, |
| 373 | mode) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 374 | ==> |
| 375 | p = Popen(["mycmd", "myarg"], bufsize=bufsize, |
| 376 | stdin=PIPE, stdout=PIPE, close_fds=True) |
| 377 | (child_stdout, child_stdin) = (p.stdout, p.stdin) |
| 378 | |
Neal Norwitz | aa87fb6 | 2007-05-11 06:23:01 +0000 | [diff] [blame] | 379 | The popen2.Popen3 and popen2.Popen4 basically works as subprocess.Popen, |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 380 | except that: |
| 381 | |
| 382 | * subprocess.Popen raises an exception if the execution fails |
| 383 | * the capturestderr argument is replaced with the stderr argument. |
| 384 | * stdin=PIPE and stdout=PIPE must be specified. |
| 385 | * popen2 closes all filedescriptors by default, but you have to specify |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 386 | close_fds=True with subprocess.Popen. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 387 | """ |
| 388 | |
| 389 | import sys |
| 390 | mswindows = (sys.platform == "win32") |
| 391 | |
| 392 | import os |
Peter Astrand | c26516b | 2005-02-21 08:13:02 +0000 | [diff] [blame] | 393 | import types |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 394 | import traceback |
Gregory P. Smith | 87d4979 | 2008-01-19 20:57:59 +0000 | [diff] [blame] | 395 | import gc |
Christian Heimes | e74c8f2 | 2008-04-19 02:23:57 +0000 | [diff] [blame] | 396 | import signal |
Ross Lagerwall | 104c3f1 | 2011-04-05 15:24:34 +0200 | [diff] [blame] | 397 | import errno |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 398 | |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 399 | # Exception classes used by this module. |
Peter Astrand | 7d1d436 | 2006-07-14 14:04:45 +0000 | [diff] [blame] | 400 | class CalledProcessError(Exception): |
Gregory P. Smith | 97f49f4 | 2008-12-04 20:21:09 +0000 | [diff] [blame] | 401 | """This exception is raised when a process run by check_call() or |
Gregory P. Smith | 2657680 | 2008-12-05 02:27:01 +0000 | [diff] [blame] | 402 | check_output() returns a non-zero exit status. |
Gregory P. Smith | 97f49f4 | 2008-12-04 20:21:09 +0000 | [diff] [blame] | 403 | The exit status will be stored in the returncode attribute; |
Gregory P. Smith | 2657680 | 2008-12-05 02:27:01 +0000 | [diff] [blame] | 404 | check_output() will also store the output in the output attribute. |
Gregory P. Smith | 97f49f4 | 2008-12-04 20:21:09 +0000 | [diff] [blame] | 405 | """ |
| 406 | def __init__(self, returncode, cmd, output=None): |
Peter Astrand | 7d1d436 | 2006-07-14 14:04:45 +0000 | [diff] [blame] | 407 | self.returncode = returncode |
| 408 | self.cmd = cmd |
Gregory P. Smith | 97f49f4 | 2008-12-04 20:21:09 +0000 | [diff] [blame] | 409 | self.output = output |
Peter Astrand | 7d1d436 | 2006-07-14 14:04:45 +0000 | [diff] [blame] | 410 | def __str__(self): |
| 411 | return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode) |
Tim Peters | 73a9ead | 2006-07-18 21:55:15 +0000 | [diff] [blame] | 412 | |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 413 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 414 | if mswindows: |
| 415 | import threading |
| 416 | import msvcrt |
Brian Curtin | a2936cf | 2010-04-24 15:40:11 +0000 | [diff] [blame] | 417 | import _subprocess |
| 418 | class STARTUPINFO: |
| 419 | dwFlags = 0 |
| 420 | hStdInput = None |
| 421 | hStdOutput = None |
| 422 | hStdError = None |
| 423 | wShowWindow = 0 |
| 424 | class pywintypes: |
| 425 | error = IOError |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 426 | else: |
| 427 | import select |
Gregory P. Smith | dd7ca24 | 2009-07-04 01:49:29 +0000 | [diff] [blame] | 428 | _has_poll = hasattr(select, 'poll') |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 429 | import fcntl |
| 430 | import pickle |
| 431 | |
Amaury Forgeot d'Arc | ce32eb7 | 2009-07-09 22:37:22 +0000 | [diff] [blame] | 432 | # When select or poll has indicated that the file is writable, |
| 433 | # we can write up to _PIPE_BUF bytes without risk of blocking. |
| 434 | # POSIX defines PIPE_BUF as >= 512. |
| 435 | _PIPE_BUF = getattr(select, 'PIPE_BUF', 512) |
| 436 | |
| 437 | |
Gregory P. Smith | 97f49f4 | 2008-12-04 20:21:09 +0000 | [diff] [blame] | 438 | __all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", |
Gregory P. Smith | 2657680 | 2008-12-05 02:27:01 +0000 | [diff] [blame] | 439 | "check_output", "CalledProcessError"] |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 440 | |
Brian Curtin | a2936cf | 2010-04-24 15:40:11 +0000 | [diff] [blame] | 441 | if mswindows: |
Brian Curtin | 77b7591 | 2011-04-29 16:21:51 -0500 | [diff] [blame] | 442 | from _subprocess import (CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP, |
| 443 | STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, |
| 444 | STD_ERROR_HANDLE, SW_HIDE, |
| 445 | STARTF_USESTDHANDLES, STARTF_USESHOWWINDOW) |
Brian Curtin | 20de458 | 2011-04-29 16:28:52 -0500 | [diff] [blame] | 446 | |
Brian Curtin | 77b7591 | 2011-04-29 16:21:51 -0500 | [diff] [blame] | 447 | __all__.extend(["CREATE_NEW_CONSOLE", "CREATE_NEW_PROCESS_GROUP", |
| 448 | "STD_INPUT_HANDLE", "STD_OUTPUT_HANDLE", |
| 449 | "STD_ERROR_HANDLE", "SW_HIDE", |
| 450 | "STARTF_USESTDHANDLES", "STARTF_USESHOWWINDOW"]) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 451 | try: |
| 452 | MAXFD = os.sysconf("SC_OPEN_MAX") |
| 453 | except: |
| 454 | MAXFD = 256 |
| 455 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 456 | _active = [] |
| 457 | |
| 458 | def _cleanup(): |
| 459 | for inst in _active[:]: |
Georg Brandl | 02e7dfd | 2009-12-28 08:09:32 +0000 | [diff] [blame] | 460 | res = inst._internal_poll(_deadstate=sys.maxint) |
Charles-François Natali | b02302c | 2011-08-18 17:18:28 +0200 | [diff] [blame] | 461 | if res is not None: |
Martin v. Löwis | 17de8ff | 2006-04-10 15:55:37 +0000 | [diff] [blame] | 462 | try: |
| 463 | _active.remove(inst) |
| 464 | except ValueError: |
| 465 | # This can happen if two threads create a new Popen instance. |
| 466 | # It's harmless that it was already removed, so ignore. |
| 467 | pass |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 468 | |
| 469 | PIPE = -1 |
| 470 | STDOUT = -2 |
| 471 | |
| 472 | |
Gregory P. Smith | cce211f | 2010-03-01 00:05:08 +0000 | [diff] [blame] | 473 | def _eintr_retry_call(func, *args): |
| 474 | while True: |
| 475 | try: |
| 476 | return func(*args) |
Victor Stinner | e790131 | 2011-07-05 14:08:01 +0200 | [diff] [blame] | 477 | except (OSError, IOError) as e: |
Gregory P. Smith | cce211f | 2010-03-01 00:05:08 +0000 | [diff] [blame] | 478 | if e.errno == errno.EINTR: |
| 479 | continue |
| 480 | raise |
| 481 | |
| 482 | |
Kristján Valur Jónsson | 8927e8f | 2013-03-19 15:07:35 -0700 | [diff] [blame] | 483 | # XXX This function is only used by multiprocessing and the test suite, |
| 484 | # but it's here so that it can be imported when Python is compiled without |
| 485 | # threads. |
| 486 | |
| 487 | def _args_from_interpreter_flags(): |
| 488 | """Return a list of command-line arguments reproducing the current |
| 489 | settings in sys.flags and sys.warnoptions.""" |
| 490 | flag_opt_map = { |
| 491 | 'debug': 'd', |
| 492 | # 'inspect': 'i', |
| 493 | # 'interactive': 'i', |
| 494 | 'optimize': 'O', |
| 495 | 'dont_write_bytecode': 'B', |
| 496 | 'no_user_site': 's', |
| 497 | 'no_site': 'S', |
| 498 | 'ignore_environment': 'E', |
| 499 | 'verbose': 'v', |
| 500 | 'bytes_warning': 'b', |
| 501 | 'hash_randomization': 'R', |
| 502 | 'py3k_warning': '3', |
| 503 | } |
| 504 | args = [] |
| 505 | for flag, opt in flag_opt_map.items(): |
| 506 | v = getattr(sys.flags, flag) |
| 507 | if v > 0: |
| 508 | args.append('-' + opt * v) |
| 509 | for opt in sys.warnoptions: |
| 510 | args.append('-W' + opt) |
| 511 | return args |
| 512 | |
| 513 | |
Peter Astrand | 5f5e141 | 2004-12-05 20:15:36 +0000 | [diff] [blame] | 514 | def call(*popenargs, **kwargs): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 515 | """Run command with arguments. Wait for command to complete, then |
| 516 | return the returncode attribute. |
| 517 | |
| 518 | The arguments are the same as for the Popen constructor. Example: |
| 519 | |
| 520 | retcode = call(["ls", "-l"]) |
| 521 | """ |
Peter Astrand | 5f5e141 | 2004-12-05 20:15:36 +0000 | [diff] [blame] | 522 | return Popen(*popenargs, **kwargs).wait() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 523 | |
| 524 | |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 525 | def check_call(*popenargs, **kwargs): |
| 526 | """Run command with arguments. Wait for command to complete. If |
| 527 | the exit code was zero then return, otherwise raise |
| 528 | CalledProcessError. The CalledProcessError object will have the |
Peter Astrand | 7d1d436 | 2006-07-14 14:04:45 +0000 | [diff] [blame] | 529 | return code in the returncode attribute. |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 530 | |
| 531 | The arguments are the same as for the Popen constructor. Example: |
| 532 | |
| 533 | check_call(["ls", "-l"]) |
| 534 | """ |
| 535 | retcode = call(*popenargs, **kwargs) |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 536 | if retcode: |
Gregory P. Smith | 97f49f4 | 2008-12-04 20:21:09 +0000 | [diff] [blame] | 537 | cmd = kwargs.get("args") |
| 538 | if cmd is None: |
| 539 | cmd = popenargs[0] |
Peter Astrand | 7d1d436 | 2006-07-14 14:04:45 +0000 | [diff] [blame] | 540 | raise CalledProcessError(retcode, cmd) |
Gregory P. Smith | 97f49f4 | 2008-12-04 20:21:09 +0000 | [diff] [blame] | 541 | return 0 |
| 542 | |
| 543 | |
Gregory P. Smith | 2657680 | 2008-12-05 02:27:01 +0000 | [diff] [blame] | 544 | def check_output(*popenargs, **kwargs): |
Georg Brandl | 6ab5d08 | 2009-12-20 14:33:20 +0000 | [diff] [blame] | 545 | r"""Run command with arguments and return its output as a byte string. |
Gregory P. Smith | 97f49f4 | 2008-12-04 20:21:09 +0000 | [diff] [blame] | 546 | |
| 547 | If the exit code was non-zero it raises a CalledProcessError. The |
| 548 | CalledProcessError object will have the return code in the returncode |
| 549 | attribute and output in the output attribute. |
| 550 | |
| 551 | The arguments are the same as for the Popen constructor. Example: |
| 552 | |
Gregory P. Smith | 2657680 | 2008-12-05 02:27:01 +0000 | [diff] [blame] | 553 | >>> check_output(["ls", "-l", "/dev/null"]) |
Gregory P. Smith | 97f49f4 | 2008-12-04 20:21:09 +0000 | [diff] [blame] | 554 | 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n' |
| 555 | |
| 556 | The stdout argument is not allowed as it is used internally. |
Georg Brandl | 02e7dfd | 2009-12-28 08:09:32 +0000 | [diff] [blame] | 557 | To capture standard error in the result, use stderr=STDOUT. |
Gregory P. Smith | 97f49f4 | 2008-12-04 20:21:09 +0000 | [diff] [blame] | 558 | |
Gregory P. Smith | 2657680 | 2008-12-05 02:27:01 +0000 | [diff] [blame] | 559 | >>> check_output(["/bin/sh", "-c", |
Georg Brandl | 6ab5d08 | 2009-12-20 14:33:20 +0000 | [diff] [blame] | 560 | ... "ls -l non_existent_file ; exit 0"], |
Georg Brandl | 02e7dfd | 2009-12-28 08:09:32 +0000 | [diff] [blame] | 561 | ... stderr=STDOUT) |
Mark Dickinson | 3e4caeb | 2009-02-21 20:27:01 +0000 | [diff] [blame] | 562 | 'ls: non_existent_file: No such file or directory\n' |
Gregory P. Smith | 97f49f4 | 2008-12-04 20:21:09 +0000 | [diff] [blame] | 563 | """ |
| 564 | if 'stdout' in kwargs: |
| 565 | raise ValueError('stdout argument not allowed, it will be overridden.') |
Amaury Forgeot d'Arc | 5fe420e | 2009-06-18 22:32:50 +0000 | [diff] [blame] | 566 | process = Popen(stdout=PIPE, *popenargs, **kwargs) |
Gregory P. Smith | 97f49f4 | 2008-12-04 20:21:09 +0000 | [diff] [blame] | 567 | output, unused_err = process.communicate() |
| 568 | retcode = process.poll() |
| 569 | if retcode: |
| 570 | cmd = kwargs.get("args") |
| 571 | if cmd is None: |
| 572 | cmd = popenargs[0] |
| 573 | raise CalledProcessError(retcode, cmd, output=output) |
| 574 | return output |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 575 | |
| 576 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 577 | def list2cmdline(seq): |
| 578 | """ |
| 579 | Translate a sequence of arguments into a command line |
| 580 | string, using the same rules as the MS C runtime: |
| 581 | |
| 582 | 1) Arguments are delimited by white space, which is either a |
| 583 | space or a tab. |
| 584 | |
| 585 | 2) A string surrounded by double quotation marks is |
| 586 | interpreted as a single argument, regardless of white space |
Jean-Paul Calderone | b33f0c1 | 2010-06-18 20:00:17 +0000 | [diff] [blame] | 587 | contained within. A quoted string can be embedded in an |
| 588 | argument. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 589 | |
| 590 | 3) A double quotation mark preceded by a backslash is |
| 591 | interpreted as a literal double quotation mark. |
| 592 | |
| 593 | 4) Backslashes are interpreted literally, unless they |
| 594 | immediately precede a double quotation mark. |
| 595 | |
| 596 | 5) If backslashes immediately precede a double quotation mark, |
| 597 | every pair of backslashes is interpreted as a literal |
| 598 | backslash. If the number of backslashes is odd, the last |
| 599 | backslash escapes the next double quotation mark as |
| 600 | described in rule 3. |
| 601 | """ |
| 602 | |
| 603 | # See |
Eric Smith | d19915e | 2009-11-09 15:16:23 +0000 | [diff] [blame] | 604 | # http://msdn.microsoft.com/en-us/library/17w5ykft.aspx |
| 605 | # or search http://msdn.microsoft.com for |
| 606 | # "Parsing C++ Command-Line Arguments" |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 607 | result = [] |
| 608 | needquote = False |
| 609 | for arg in seq: |
| 610 | bs_buf = [] |
| 611 | |
| 612 | # Add a space to separate this argument from the others |
| 613 | if result: |
| 614 | result.append(' ') |
| 615 | |
Jean-Paul Calderone | b33f0c1 | 2010-06-18 20:00:17 +0000 | [diff] [blame] | 616 | needquote = (" " in arg) or ("\t" in arg) or not arg |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 617 | if needquote: |
| 618 | result.append('"') |
| 619 | |
| 620 | for c in arg: |
| 621 | if c == '\\': |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 622 | # Don't know if we need to double yet. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 623 | bs_buf.append(c) |
| 624 | elif c == '"': |
Gregory P. Smith | e047e6d | 2008-01-19 20:49:02 +0000 | [diff] [blame] | 625 | # Double backslashes. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 626 | result.append('\\' * len(bs_buf)*2) |
| 627 | bs_buf = [] |
| 628 | result.append('\\"') |
| 629 | else: |
| 630 | # Normal char |
| 631 | if bs_buf: |
| 632 | result.extend(bs_buf) |
| 633 | bs_buf = [] |
| 634 | result.append(c) |
| 635 | |
Gregory P. Smith | e047e6d | 2008-01-19 20:49:02 +0000 | [diff] [blame] | 636 | # Add remaining backslashes, if any. |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 637 | if bs_buf: |
| 638 | result.extend(bs_buf) |
| 639 | |
| 640 | if needquote: |
Peter Astrand | 7e78ade | 2005-03-03 21:10:23 +0000 | [diff] [blame] | 641 | result.extend(bs_buf) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 642 | result.append('"') |
| 643 | |
| 644 | return ''.join(result) |
| 645 | |
| 646 | |
| 647 | class Popen(object): |
| 648 | def __init__(self, args, bufsize=0, executable=None, |
| 649 | stdin=None, stdout=None, stderr=None, |
| 650 | preexec_fn=None, close_fds=False, shell=False, |
| 651 | cwd=None, env=None, universal_newlines=False, |
| 652 | startupinfo=None, creationflags=0): |
| 653 | """Create new Popen instance.""" |
| 654 | _cleanup() |
| 655 | |
Martin v. Löwis | 17de8ff | 2006-04-10 15:55:37 +0000 | [diff] [blame] | 656 | self._child_created = False |
Peter Astrand | 738131d | 2004-11-30 21:04:45 +0000 | [diff] [blame] | 657 | if not isinstance(bufsize, (int, long)): |
| 658 | raise TypeError("bufsize must be an integer") |
| 659 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 660 | if mswindows: |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 661 | if preexec_fn is not None: |
| 662 | raise ValueError("preexec_fn is not supported on Windows " |
| 663 | "platforms") |
Peter Astrand | 81a191b | 2007-05-26 22:18:20 +0000 | [diff] [blame] | 664 | if close_fds and (stdin is not None or stdout is not None or |
| 665 | stderr is not None): |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 666 | raise ValueError("close_fds is not supported on Windows " |
Peter Astrand | 81a191b | 2007-05-26 22:18:20 +0000 | [diff] [blame] | 667 | "platforms if you redirect stdin/stdout/stderr") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 668 | else: |
| 669 | # POSIX |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 670 | if startupinfo is not None: |
| 671 | raise ValueError("startupinfo is only supported on Windows " |
| 672 | "platforms") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 673 | if creationflags != 0: |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 674 | raise ValueError("creationflags is only supported on Windows " |
| 675 | "platforms") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 676 | |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 677 | self.stdin = None |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 678 | self.stdout = None |
| 679 | self.stderr = None |
| 680 | self.pid = None |
| 681 | self.returncode = None |
| 682 | self.universal_newlines = universal_newlines |
| 683 | |
| 684 | # Input and output objects. The general principle is like |
| 685 | # this: |
| 686 | # |
| 687 | # Parent Child |
| 688 | # ------ ----- |
| 689 | # p2cwrite ---stdin---> p2cread |
| 690 | # c2pread <--stdout--- c2pwrite |
| 691 | # errread <--stderr--- errwrite |
| 692 | # |
| 693 | # On POSIX, the child objects are file descriptors. On |
| 694 | # Windows, these are Windows file handles. The parent objects |
| 695 | # are file descriptors on both platforms. The parent objects |
| 696 | # are None when not using PIPEs. The child objects are None |
| 697 | # when not redirecting. |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 698 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 699 | (p2cread, p2cwrite, |
| 700 | c2pread, c2pwrite, |
| 701 | errread, errwrite) = self._get_handles(stdin, stdout, stderr) |
| 702 | |
Gregory P. Smith | 9d3b6e9 | 2012-11-10 22:49:03 -0800 | [diff] [blame] | 703 | try: |
| 704 | self._execute_child(args, executable, preexec_fn, close_fds, |
| 705 | cwd, env, universal_newlines, |
| 706 | startupinfo, creationflags, shell, |
| 707 | p2cread, p2cwrite, |
| 708 | c2pread, c2pwrite, |
| 709 | errread, errwrite) |
| 710 | except Exception: |
| 711 | # Preserve original exception in case os.close raises. |
| 712 | exc_type, exc_value, exc_trace = sys.exc_info() |
| 713 | |
| 714 | to_close = [] |
| 715 | # Only close the pipes we created. |
| 716 | if stdin == PIPE: |
| 717 | to_close.extend((p2cread, p2cwrite)) |
| 718 | if stdout == PIPE: |
| 719 | to_close.extend((c2pread, c2pwrite)) |
| 720 | if stderr == PIPE: |
| 721 | to_close.extend((errread, errwrite)) |
| 722 | |
| 723 | for fd in to_close: |
| 724 | try: |
| 725 | os.close(fd) |
| 726 | except EnvironmentError: |
| 727 | pass |
| 728 | |
| 729 | raise exc_type, exc_value, exc_trace |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 730 | |
Peter Astrand | 5f9c6ae | 2007-02-06 15:37:50 +0000 | [diff] [blame] | 731 | if mswindows: |
Hirokazu Yamamoto | eacbbdf | 2009-03-03 22:18:14 +0000 | [diff] [blame] | 732 | if p2cwrite is not None: |
| 733 | p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0) |
| 734 | if c2pread is not None: |
| 735 | c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0) |
| 736 | if errread is not None: |
| 737 | errread = msvcrt.open_osfhandle(errread.Detach(), 0) |
Peter Astrand | 5f9c6ae | 2007-02-06 15:37:50 +0000 | [diff] [blame] | 738 | |
Peter Astrand | f540003 | 2007-02-02 19:06:36 +0000 | [diff] [blame] | 739 | if p2cwrite is not None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 740 | self.stdin = os.fdopen(p2cwrite, 'wb', bufsize) |
Peter Astrand | f540003 | 2007-02-02 19:06:36 +0000 | [diff] [blame] | 741 | if c2pread is not None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 742 | if universal_newlines: |
| 743 | self.stdout = os.fdopen(c2pread, 'rU', bufsize) |
| 744 | else: |
| 745 | self.stdout = os.fdopen(c2pread, 'rb', bufsize) |
Peter Astrand | f540003 | 2007-02-02 19:06:36 +0000 | [diff] [blame] | 746 | if errread is not None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 747 | if universal_newlines: |
| 748 | self.stderr = os.fdopen(errread, 'rU', bufsize) |
| 749 | else: |
| 750 | self.stderr = os.fdopen(errread, 'rb', bufsize) |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 751 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 752 | |
| 753 | def _translate_newlines(self, data): |
| 754 | data = data.replace("\r\n", "\n") |
| 755 | data = data.replace("\r", "\n") |
| 756 | return data |
| 757 | |
Martin v. Löwis | 17de8ff | 2006-04-10 15:55:37 +0000 | [diff] [blame] | 758 | |
Brett Cannon | 42a0ba7 | 2010-05-14 00:21:48 +0000 | [diff] [blame] | 759 | def __del__(self, _maxint=sys.maxint, _active=_active): |
Victor Stinner | 776e69b | 2011-06-01 01:03:00 +0200 | [diff] [blame] | 760 | # If __init__ hasn't had a chance to execute (e.g. if it |
| 761 | # was passed an undeclared keyword argument), we don't |
| 762 | # have a _child_created attribute at all. |
| 763 | if not getattr(self, '_child_created', False): |
Martin v. Löwis | 17de8ff | 2006-04-10 15:55:37 +0000 | [diff] [blame] | 764 | # We didn't get to successfully create a child process. |
| 765 | return |
| 766 | # In case the child hasn't been waited on, check if it's done. |
Brett Cannon | 42a0ba7 | 2010-05-14 00:21:48 +0000 | [diff] [blame] | 767 | self._internal_poll(_deadstate=_maxint) |
Georg Brandl | 13cf38c | 2006-07-20 16:28:39 +0000 | [diff] [blame] | 768 | if self.returncode is None and _active is not None: |
Martin v. Löwis | 17de8ff | 2006-04-10 15:55:37 +0000 | [diff] [blame] | 769 | # Child is still running, keep us alive until we can wait on it. |
| 770 | _active.append(self) |
| 771 | |
| 772 | |
Peter Astrand | 23109f0 | 2005-03-03 20:28:59 +0000 | [diff] [blame] | 773 | def communicate(self, input=None): |
| 774 | """Interact with process: Send data to stdin. Read data from |
| 775 | stdout and stderr, until end-of-file is reached. Wait for |
| 776 | process to terminate. The optional input argument should be a |
| 777 | string to be sent to the child process, or None, if no data |
| 778 | should be sent to the child. |
Tim Peters | eba28be | 2005-03-28 01:08:02 +0000 | [diff] [blame] | 779 | |
Peter Astrand | 23109f0 | 2005-03-03 20:28:59 +0000 | [diff] [blame] | 780 | communicate() returns a tuple (stdout, stderr).""" |
| 781 | |
| 782 | # Optimization: If we are only using one pipe, or no pipe at |
| 783 | # all, using select() or threads is unnecessary. |
| 784 | if [self.stdin, self.stdout, self.stderr].count(None) >= 2: |
Tim Peters | eba28be | 2005-03-28 01:08:02 +0000 | [diff] [blame] | 785 | stdout = None |
| 786 | stderr = None |
Peter Astrand | 23109f0 | 2005-03-03 20:28:59 +0000 | [diff] [blame] | 787 | if self.stdin: |
| 788 | if input: |
Ross Lagerwall | 104c3f1 | 2011-04-05 15:24:34 +0200 | [diff] [blame] | 789 | try: |
| 790 | self.stdin.write(input) |
| 791 | except IOError as e: |
| 792 | if e.errno != errno.EPIPE and e.errno != errno.EINVAL: |
| 793 | raise |
Peter Astrand | 23109f0 | 2005-03-03 20:28:59 +0000 | [diff] [blame] | 794 | self.stdin.close() |
| 795 | elif self.stdout: |
Victor Stinner | e790131 | 2011-07-05 14:08:01 +0200 | [diff] [blame] | 796 | stdout = _eintr_retry_call(self.stdout.read) |
Gregory P. Smith | 4036fd4 | 2008-05-26 20:22:14 +0000 | [diff] [blame] | 797 | self.stdout.close() |
Peter Astrand | 23109f0 | 2005-03-03 20:28:59 +0000 | [diff] [blame] | 798 | elif self.stderr: |
Victor Stinner | e790131 | 2011-07-05 14:08:01 +0200 | [diff] [blame] | 799 | stderr = _eintr_retry_call(self.stderr.read) |
Gregory P. Smith | 4036fd4 | 2008-05-26 20:22:14 +0000 | [diff] [blame] | 800 | self.stderr.close() |
Peter Astrand | 23109f0 | 2005-03-03 20:28:59 +0000 | [diff] [blame] | 801 | self.wait() |
| 802 | return (stdout, stderr) |
Tim Peters | eba28be | 2005-03-28 01:08:02 +0000 | [diff] [blame] | 803 | |
Peter Astrand | 23109f0 | 2005-03-03 20:28:59 +0000 | [diff] [blame] | 804 | return self._communicate(input) |
| 805 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 806 | |
Gregory P. Smith | a36f8fe | 2008-08-04 00:13:29 +0000 | [diff] [blame] | 807 | def poll(self): |
| 808 | return self._internal_poll() |
| 809 | |
| 810 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 811 | if mswindows: |
| 812 | # |
| 813 | # Windows methods |
| 814 | # |
| 815 | def _get_handles(self, stdin, stdout, stderr): |
Amaury Forgeot d'Arc | 8318afa | 2009-07-10 16:47:42 +0000 | [diff] [blame] | 816 | """Construct and return tuple with IO objects: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 817 | p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite |
| 818 | """ |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 819 | if stdin is None and stdout is None and stderr is None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 820 | return (None, None, None, None, None, None) |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 821 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 822 | p2cread, p2cwrite = None, None |
| 823 | c2pread, c2pwrite = None, None |
| 824 | errread, errwrite = None, None |
| 825 | |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 826 | if stdin is None: |
Brian Curtin | a2936cf | 2010-04-24 15:40:11 +0000 | [diff] [blame] | 827 | p2cread = _subprocess.GetStdHandle(_subprocess.STD_INPUT_HANDLE) |
Hirokazu Yamamoto | eacbbdf | 2009-03-03 22:18:14 +0000 | [diff] [blame] | 828 | if p2cread is None: |
Brian Curtin | a2936cf | 2010-04-24 15:40:11 +0000 | [diff] [blame] | 829 | p2cread, _ = _subprocess.CreatePipe(None, 0) |
Hirokazu Yamamoto | eacbbdf | 2009-03-03 22:18:14 +0000 | [diff] [blame] | 830 | elif stdin == PIPE: |
Brian Curtin | a2936cf | 2010-04-24 15:40:11 +0000 | [diff] [blame] | 831 | p2cread, p2cwrite = _subprocess.CreatePipe(None, 0) |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 832 | elif isinstance(stdin, int): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 833 | p2cread = msvcrt.get_osfhandle(stdin) |
| 834 | else: |
| 835 | # Assuming file-like object |
| 836 | p2cread = msvcrt.get_osfhandle(stdin.fileno()) |
| 837 | p2cread = self._make_inheritable(p2cread) |
| 838 | |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 839 | if stdout is None: |
Brian Curtin | a2936cf | 2010-04-24 15:40:11 +0000 | [diff] [blame] | 840 | c2pwrite = _subprocess.GetStdHandle(_subprocess.STD_OUTPUT_HANDLE) |
Hirokazu Yamamoto | eacbbdf | 2009-03-03 22:18:14 +0000 | [diff] [blame] | 841 | if c2pwrite is None: |
Brian Curtin | a2936cf | 2010-04-24 15:40:11 +0000 | [diff] [blame] | 842 | _, c2pwrite = _subprocess.CreatePipe(None, 0) |
Hirokazu Yamamoto | eacbbdf | 2009-03-03 22:18:14 +0000 | [diff] [blame] | 843 | elif stdout == PIPE: |
Brian Curtin | a2936cf | 2010-04-24 15:40:11 +0000 | [diff] [blame] | 844 | c2pread, c2pwrite = _subprocess.CreatePipe(None, 0) |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 845 | elif isinstance(stdout, int): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 846 | c2pwrite = msvcrt.get_osfhandle(stdout) |
| 847 | else: |
| 848 | # Assuming file-like object |
| 849 | c2pwrite = msvcrt.get_osfhandle(stdout.fileno()) |
| 850 | c2pwrite = self._make_inheritable(c2pwrite) |
| 851 | |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 852 | if stderr is None: |
Brian Curtin | a2936cf | 2010-04-24 15:40:11 +0000 | [diff] [blame] | 853 | errwrite = _subprocess.GetStdHandle(_subprocess.STD_ERROR_HANDLE) |
Hirokazu Yamamoto | eacbbdf | 2009-03-03 22:18:14 +0000 | [diff] [blame] | 854 | if errwrite is None: |
Brian Curtin | a2936cf | 2010-04-24 15:40:11 +0000 | [diff] [blame] | 855 | _, errwrite = _subprocess.CreatePipe(None, 0) |
Hirokazu Yamamoto | eacbbdf | 2009-03-03 22:18:14 +0000 | [diff] [blame] | 856 | elif stderr == PIPE: |
Brian Curtin | a2936cf | 2010-04-24 15:40:11 +0000 | [diff] [blame] | 857 | errread, errwrite = _subprocess.CreatePipe(None, 0) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 858 | elif stderr == STDOUT: |
| 859 | errwrite = c2pwrite |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 860 | elif isinstance(stderr, int): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 861 | errwrite = msvcrt.get_osfhandle(stderr) |
| 862 | else: |
| 863 | # Assuming file-like object |
| 864 | errwrite = msvcrt.get_osfhandle(stderr.fileno()) |
| 865 | errwrite = self._make_inheritable(errwrite) |
| 866 | |
| 867 | return (p2cread, p2cwrite, |
| 868 | c2pread, c2pwrite, |
| 869 | errread, errwrite) |
| 870 | |
| 871 | |
| 872 | def _make_inheritable(self, handle): |
| 873 | """Return a duplicate of handle, which is inheritable""" |
Brian Curtin | a2936cf | 2010-04-24 15:40:11 +0000 | [diff] [blame] | 874 | return _subprocess.DuplicateHandle(_subprocess.GetCurrentProcess(), |
| 875 | handle, _subprocess.GetCurrentProcess(), 0, 1, |
| 876 | _subprocess.DUPLICATE_SAME_ACCESS) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 877 | |
| 878 | |
| 879 | def _find_w9xpopen(self): |
| 880 | """Find and return absolut path to w9xpopen.exe""" |
Brian Curtin | a2936cf | 2010-04-24 15:40:11 +0000 | [diff] [blame] | 881 | w9xpopen = os.path.join( |
| 882 | os.path.dirname(_subprocess.GetModuleFileName(0)), |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 883 | "w9xpopen.exe") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 884 | if not os.path.exists(w9xpopen): |
| 885 | # Eeek - file-not-found - possibly an embedding |
| 886 | # situation - see if we can locate it in sys.exec_prefix |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 887 | w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix), |
| 888 | "w9xpopen.exe") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 889 | if not os.path.exists(w9xpopen): |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 890 | raise RuntimeError("Cannot locate w9xpopen.exe, which is " |
| 891 | "needed for Popen to work with your " |
| 892 | "shell or platform.") |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 893 | return w9xpopen |
| 894 | |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 895 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 896 | def _execute_child(self, args, executable, preexec_fn, close_fds, |
| 897 | cwd, env, universal_newlines, |
| 898 | startupinfo, creationflags, shell, |
| 899 | p2cread, p2cwrite, |
| 900 | c2pread, c2pwrite, |
| 901 | errread, errwrite): |
| 902 | """Execute program (MS Windows version)""" |
| 903 | |
Peter Astrand | c26516b | 2005-02-21 08:13:02 +0000 | [diff] [blame] | 904 | if not isinstance(args, types.StringTypes): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 905 | args = list2cmdline(args) |
| 906 | |
Peter Astrand | c1d6536 | 2004-11-07 14:30:34 +0000 | [diff] [blame] | 907 | # Process startup details |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 908 | if startupinfo is None: |
Georg Brandl | ad62489 | 2006-06-04 22:15:37 +0000 | [diff] [blame] | 909 | startupinfo = STARTUPINFO() |
| 910 | if None not in (p2cread, c2pwrite, errwrite): |
Brian Curtin | a2936cf | 2010-04-24 15:40:11 +0000 | [diff] [blame] | 911 | startupinfo.dwFlags |= _subprocess.STARTF_USESTDHANDLES |
Peter Astrand | c1d6536 | 2004-11-07 14:30:34 +0000 | [diff] [blame] | 912 | startupinfo.hStdInput = p2cread |
| 913 | startupinfo.hStdOutput = c2pwrite |
| 914 | startupinfo.hStdError = errwrite |
| 915 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 916 | if shell: |
Brian Curtin | a2936cf | 2010-04-24 15:40:11 +0000 | [diff] [blame] | 917 | startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW |
| 918 | startupinfo.wShowWindow = _subprocess.SW_HIDE |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 919 | comspec = os.environ.get("COMSPEC", "cmd.exe") |
Tim Golden | 8e4756c | 2010-08-12 11:00:35 +0000 | [diff] [blame] | 920 | args = '{} /c "{}"'.format (comspec, args) |
| 921 | if (_subprocess.GetVersion() >= 0x80000000 or |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 922 | os.path.basename(comspec).lower() == "command.com"): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 923 | # Win9x, or using command.com on NT. We need to |
| 924 | # use the w9xpopen intermediate program. For more |
| 925 | # information, see KB Q150956 |
| 926 | # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp) |
| 927 | w9xpopen = self._find_w9xpopen() |
| 928 | args = '"%s" %s' % (w9xpopen, args) |
| 929 | # Not passing CREATE_NEW_CONSOLE has been known to |
| 930 | # cause random failures on win9x. Specifically a |
| 931 | # dialog: "Your program accessed mem currently in |
| 932 | # use at xxx" and a hopeful warning about the |
| 933 | # stability of your system. Cost is Ctrl+C wont |
| 934 | # kill children. |
Brian Curtin | a2936cf | 2010-04-24 15:40:11 +0000 | [diff] [blame] | 935 | creationflags |= _subprocess.CREATE_NEW_CONSOLE |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 936 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 937 | # Start the process |
| 938 | try: |
Brian Curtin | a2936cf | 2010-04-24 15:40:11 +0000 | [diff] [blame] | 939 | hp, ht, pid, tid = _subprocess.CreateProcess(executable, args, |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 940 | # no special security |
| 941 | None, None, |
Peter Astrand | 81a191b | 2007-05-26 22:18:20 +0000 | [diff] [blame] | 942 | int(not close_fds), |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 943 | creationflags, |
| 944 | env, |
| 945 | cwd, |
| 946 | startupinfo) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 947 | except pywintypes.error, e: |
| 948 | # Translate pywintypes.error to WindowsError, which is |
| 949 | # a subclass of OSError. FIXME: We should really |
Ezio Melotti | c2077b0 | 2011-03-16 12:34:31 +0200 | [diff] [blame] | 950 | # translate errno using _sys_errlist (or similar), but |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 951 | # how can this be done from Python? |
| 952 | raise WindowsError(*e.args) |
Tim Golden | 431774f | 2010-08-08 11:17:56 +0000 | [diff] [blame] | 953 | finally: |
| 954 | # Child is launched. Close the parent's copy of those pipe |
| 955 | # handles that only the child should have open. You need |
| 956 | # to make sure that no handles to the write end of the |
| 957 | # output pipe are maintained in this process or else the |
| 958 | # pipe will not close when the child process exits and the |
| 959 | # ReadFile will hang. |
| 960 | if p2cread is not None: |
| 961 | p2cread.Close() |
| 962 | if c2pwrite is not None: |
| 963 | c2pwrite.Close() |
| 964 | if errwrite is not None: |
| 965 | errwrite.Close() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 966 | |
| 967 | # Retain the process handle, but close the thread handle |
Martin v. Löwis | 17de8ff | 2006-04-10 15:55:37 +0000 | [diff] [blame] | 968 | self._child_created = True |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 969 | self._handle = hp |
| 970 | self.pid = pid |
| 971 | ht.Close() |
| 972 | |
Brett Cannon | 42a0ba7 | 2010-05-14 00:21:48 +0000 | [diff] [blame] | 973 | def _internal_poll(self, _deadstate=None, |
Victor Stinner | 2b271f7 | 2010-05-14 21:52:26 +0000 | [diff] [blame] | 974 | _WaitForSingleObject=_subprocess.WaitForSingleObject, |
| 975 | _WAIT_OBJECT_0=_subprocess.WAIT_OBJECT_0, |
| 976 | _GetExitCodeProcess=_subprocess.GetExitCodeProcess): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 977 | """Check if child process has terminated. Returns returncode |
Brett Cannon | 42a0ba7 | 2010-05-14 00:21:48 +0000 | [diff] [blame] | 978 | attribute. |
| 979 | |
| 980 | This method is called by __del__, so it can only refer to objects |
| 981 | in its local scope. |
| 982 | |
| 983 | """ |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 984 | if self.returncode is None: |
Brett Cannon | 42a0ba7 | 2010-05-14 00:21:48 +0000 | [diff] [blame] | 985 | if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0: |
| 986 | self.returncode = _GetExitCodeProcess(self._handle) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 987 | return self.returncode |
| 988 | |
| 989 | |
| 990 | def wait(self): |
| 991 | """Wait for child process to terminate. Returns returncode |
| 992 | attribute.""" |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 993 | if self.returncode is None: |
Brian Curtin | a2936cf | 2010-04-24 15:40:11 +0000 | [diff] [blame] | 994 | _subprocess.WaitForSingleObject(self._handle, |
| 995 | _subprocess.INFINITE) |
| 996 | self.returncode = _subprocess.GetExitCodeProcess(self._handle) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 997 | return self.returncode |
| 998 | |
| 999 | |
| 1000 | def _readerthread(self, fh, buffer): |
| 1001 | buffer.append(fh.read()) |
| 1002 | |
| 1003 | |
Peter Astrand | 23109f0 | 2005-03-03 20:28:59 +0000 | [diff] [blame] | 1004 | def _communicate(self, input): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1005 | stdout = None # Return |
| 1006 | stderr = None # Return |
| 1007 | |
| 1008 | if self.stdout: |
| 1009 | stdout = [] |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 1010 | stdout_thread = threading.Thread(target=self._readerthread, |
| 1011 | args=(self.stdout, stdout)) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1012 | stdout_thread.setDaemon(True) |
| 1013 | stdout_thread.start() |
| 1014 | if self.stderr: |
| 1015 | stderr = [] |
Tim Peters | e8374a5 | 2004-10-13 03:15:00 +0000 | [diff] [blame] | 1016 | stderr_thread = threading.Thread(target=self._readerthread, |
| 1017 | args=(self.stderr, stderr)) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1018 | stderr_thread.setDaemon(True) |
| 1019 | stderr_thread.start() |
| 1020 | |
| 1021 | if self.stdin: |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 1022 | if input is not None: |
Ross Lagerwall | 104c3f1 | 2011-04-05 15:24:34 +0200 | [diff] [blame] | 1023 | try: |
| 1024 | self.stdin.write(input) |
| 1025 | except IOError as e: |
| 1026 | if e.errno != errno.EPIPE: |
| 1027 | raise |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1028 | self.stdin.close() |
| 1029 | |
| 1030 | if self.stdout: |
| 1031 | stdout_thread.join() |
| 1032 | if self.stderr: |
| 1033 | stderr_thread.join() |
| 1034 | |
| 1035 | # All data exchanged. Translate lists into strings. |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 1036 | if stdout is not None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1037 | stdout = stdout[0] |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 1038 | if stderr is not None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1039 | stderr = stderr[0] |
| 1040 | |
| 1041 | # Translate newlines, if requested. We cannot let the file |
| 1042 | # object do the translation: It is based on stdio, which is |
| 1043 | # impossible to combine with select (unless forcing no |
| 1044 | # buffering). |
Neal Norwitz | a6d01ce | 2006-05-02 06:23:22 +0000 | [diff] [blame] | 1045 | if self.universal_newlines and hasattr(file, 'newlines'): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1046 | if stdout: |
| 1047 | stdout = self._translate_newlines(stdout) |
| 1048 | if stderr: |
| 1049 | stderr = self._translate_newlines(stderr) |
| 1050 | |
| 1051 | self.wait() |
| 1052 | return (stdout, stderr) |
| 1053 | |
Christian Heimes | e74c8f2 | 2008-04-19 02:23:57 +0000 | [diff] [blame] | 1054 | def send_signal(self, sig): |
| 1055 | """Send a signal to the process |
| 1056 | """ |
| 1057 | if sig == signal.SIGTERM: |
| 1058 | self.terminate() |
Brian Curtin | e5aa886 | 2010-04-02 23:26:06 +0000 | [diff] [blame] | 1059 | elif sig == signal.CTRL_C_EVENT: |
| 1060 | os.kill(self.pid, signal.CTRL_C_EVENT) |
| 1061 | elif sig == signal.CTRL_BREAK_EVENT: |
| 1062 | os.kill(self.pid, signal.CTRL_BREAK_EVENT) |
Christian Heimes | e74c8f2 | 2008-04-19 02:23:57 +0000 | [diff] [blame] | 1063 | else: |
Brian Curtin | e80513c | 2010-09-07 13:27:20 +0000 | [diff] [blame] | 1064 | raise ValueError("Unsupported signal: {}".format(sig)) |
Christian Heimes | e74c8f2 | 2008-04-19 02:23:57 +0000 | [diff] [blame] | 1065 | |
| 1066 | def terminate(self): |
| 1067 | """Terminates the process |
| 1068 | """ |
Antoine Pitrou | f60845b | 2012-03-11 19:29:12 +0100 | [diff] [blame] | 1069 | try: |
| 1070 | _subprocess.TerminateProcess(self._handle, 1) |
| 1071 | except OSError as e: |
| 1072 | # ERROR_ACCESS_DENIED (winerror 5) is received when the |
| 1073 | # process already died. |
| 1074 | if e.winerror != 5: |
| 1075 | raise |
| 1076 | rc = _subprocess.GetExitCodeProcess(self._handle) |
| 1077 | if rc == _subprocess.STILL_ACTIVE: |
| 1078 | raise |
| 1079 | self.returncode = rc |
Christian Heimes | e74c8f2 | 2008-04-19 02:23:57 +0000 | [diff] [blame] | 1080 | |
| 1081 | kill = terminate |
| 1082 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1083 | else: |
| 1084 | # |
| 1085 | # POSIX methods |
| 1086 | # |
| 1087 | def _get_handles(self, stdin, stdout, stderr): |
Amaury Forgeot d'Arc | 8318afa | 2009-07-10 16:47:42 +0000 | [diff] [blame] | 1088 | """Construct and return tuple with IO objects: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1089 | p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite |
| 1090 | """ |
| 1091 | p2cread, p2cwrite = None, None |
| 1092 | c2pread, c2pwrite = None, None |
| 1093 | errread, errwrite = None, None |
| 1094 | |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 1095 | if stdin is None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1096 | pass |
| 1097 | elif stdin == PIPE: |
Charles-François Natali | 2a34eb3 | 2011-08-25 21:20:54 +0200 | [diff] [blame] | 1098 | p2cread, p2cwrite = self.pipe_cloexec() |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 1099 | elif isinstance(stdin, int): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1100 | p2cread = stdin |
| 1101 | else: |
| 1102 | # Assuming file-like object |
| 1103 | p2cread = stdin.fileno() |
| 1104 | |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 1105 | if stdout is None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1106 | pass |
| 1107 | elif stdout == PIPE: |
Charles-François Natali | 2a34eb3 | 2011-08-25 21:20:54 +0200 | [diff] [blame] | 1108 | c2pread, c2pwrite = self.pipe_cloexec() |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 1109 | elif isinstance(stdout, int): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1110 | c2pwrite = stdout |
| 1111 | else: |
| 1112 | # Assuming file-like object |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 1113 | c2pwrite = stdout.fileno() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1114 | |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 1115 | if stderr is None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1116 | pass |
| 1117 | elif stderr == PIPE: |
Charles-François Natali | 2a34eb3 | 2011-08-25 21:20:54 +0200 | [diff] [blame] | 1118 | errread, errwrite = self.pipe_cloexec() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1119 | elif stderr == STDOUT: |
| 1120 | errwrite = c2pwrite |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 1121 | elif isinstance(stderr, int): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1122 | errwrite = stderr |
| 1123 | else: |
| 1124 | # Assuming file-like object |
| 1125 | errwrite = stderr.fileno() |
| 1126 | |
| 1127 | return (p2cread, p2cwrite, |
| 1128 | c2pread, c2pwrite, |
| 1129 | errread, errwrite) |
| 1130 | |
| 1131 | |
Antoine Pitrou | 91ce0d9 | 2011-01-03 18:45:09 +0000 | [diff] [blame] | 1132 | def _set_cloexec_flag(self, fd, cloexec=True): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1133 | try: |
| 1134 | cloexec_flag = fcntl.FD_CLOEXEC |
| 1135 | except AttributeError: |
| 1136 | cloexec_flag = 1 |
| 1137 | |
| 1138 | old = fcntl.fcntl(fd, fcntl.F_GETFD) |
Antoine Pitrou | 91ce0d9 | 2011-01-03 18:45:09 +0000 | [diff] [blame] | 1139 | if cloexec: |
| 1140 | fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag) |
| 1141 | else: |
| 1142 | fcntl.fcntl(fd, fcntl.F_SETFD, old & ~cloexec_flag) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1143 | |
| 1144 | |
Charles-François Natali | 2a34eb3 | 2011-08-25 21:20:54 +0200 | [diff] [blame] | 1145 | def pipe_cloexec(self): |
| 1146 | """Create a pipe with FDs set CLOEXEC.""" |
| 1147 | # Pipes' FDs are set CLOEXEC by default because we don't want them |
| 1148 | # to be inherited by other subprocesses: the CLOEXEC flag is removed |
| 1149 | # from the child's FDs by _dup2(), between fork() and exec(). |
| 1150 | # This is not atomic: we would need the pipe2() syscall for that. |
| 1151 | r, w = os.pipe() |
| 1152 | self._set_cloexec_flag(r) |
| 1153 | self._set_cloexec_flag(w) |
| 1154 | return r, w |
| 1155 | |
| 1156 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1157 | def _close_fds(self, but): |
Amaury Forgeot d'Arc | 5fe420e | 2009-06-18 22:32:50 +0000 | [diff] [blame] | 1158 | if hasattr(os, 'closerange'): |
| 1159 | os.closerange(3, but) |
| 1160 | os.closerange(but + 1, MAXFD) |
| 1161 | else: |
| 1162 | for i in xrange(3, MAXFD): |
| 1163 | if i == but: |
| 1164 | continue |
| 1165 | try: |
| 1166 | os.close(i) |
| 1167 | except: |
| 1168 | pass |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 1169 | |
| 1170 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1171 | def _execute_child(self, args, executable, preexec_fn, close_fds, |
| 1172 | cwd, env, universal_newlines, |
| 1173 | startupinfo, creationflags, shell, |
| 1174 | p2cread, p2cwrite, |
| 1175 | c2pread, c2pwrite, |
| 1176 | errread, errwrite): |
| 1177 | """Execute program (POSIX version)""" |
| 1178 | |
Peter Astrand | c26516b | 2005-02-21 08:13:02 +0000 | [diff] [blame] | 1179 | if isinstance(args, types.StringTypes): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1180 | args = [args] |
Georg Brandl | 6c0e1e8 | 2006-10-29 09:05:04 +0000 | [diff] [blame] | 1181 | else: |
| 1182 | args = list(args) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1183 | |
| 1184 | if shell: |
| 1185 | args = ["/bin/sh", "-c"] + args |
Stefan Krah | e9a6a7d | 2010-07-19 14:41:08 +0000 | [diff] [blame] | 1186 | if executable: |
| 1187 | args[0] = executable |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1188 | |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 1189 | if executable is None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1190 | executable = args[0] |
| 1191 | |
| 1192 | # For transferring possible exec failure from child to parent |
| 1193 | # The first char specifies the exception type: 0 means |
| 1194 | # OSError, 1 means some other error. |
Charles-François Natali | 2a34eb3 | 2011-08-25 21:20:54 +0200 | [diff] [blame] | 1195 | errpipe_read, errpipe_write = self.pipe_cloexec() |
Gregory P. Smith | 87d4979 | 2008-01-19 20:57:59 +0000 | [diff] [blame] | 1196 | try: |
Gregory P. Smith | 92ffc63 | 2008-01-19 22:23:56 +0000 | [diff] [blame] | 1197 | try: |
Facundo Batista | 8c826b7 | 2009-06-19 18:02:28 +0000 | [diff] [blame] | 1198 | gc_was_enabled = gc.isenabled() |
| 1199 | # Disable gc to avoid bug where gc -> file_dealloc -> |
| 1200 | # write to stderr -> hang. http://bugs.python.org/issue1336 |
| 1201 | gc.disable() |
| 1202 | try: |
| 1203 | self.pid = os.fork() |
Georg Brandl | 3e8b869 | 2009-07-16 21:47:51 +0000 | [diff] [blame] | 1204 | except: |
Facundo Batista | 8c826b7 | 2009-06-19 18:02:28 +0000 | [diff] [blame] | 1205 | if gc_was_enabled: |
| 1206 | gc.enable() |
Georg Brandl | 3e8b869 | 2009-07-16 21:47:51 +0000 | [diff] [blame] | 1207 | raise |
Facundo Batista | 8c826b7 | 2009-06-19 18:02:28 +0000 | [diff] [blame] | 1208 | self._child_created = True |
| 1209 | if self.pid == 0: |
| 1210 | # Child |
| 1211 | try: |
| 1212 | # Close parent's pipe ends |
| 1213 | if p2cwrite is not None: |
| 1214 | os.close(p2cwrite) |
| 1215 | if c2pread is not None: |
| 1216 | os.close(c2pread) |
| 1217 | if errread is not None: |
| 1218 | os.close(errread) |
| 1219 | os.close(errpipe_read) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1220 | |
Ross Lagerwall | d8e3901 | 2011-07-27 18:54:53 +0200 | [diff] [blame] | 1221 | # When duping fds, if there arises a situation |
| 1222 | # where one of the fds is either 0, 1 or 2, it |
| 1223 | # is possible that it is overwritten (#12607). |
| 1224 | if c2pwrite == 0: |
| 1225 | c2pwrite = os.dup(c2pwrite) |
| 1226 | if errwrite == 0 or errwrite == 1: |
| 1227 | errwrite = os.dup(errwrite) |
| 1228 | |
Facundo Batista | 8c826b7 | 2009-06-19 18:02:28 +0000 | [diff] [blame] | 1229 | # Dup fds for child |
Antoine Pitrou | 91ce0d9 | 2011-01-03 18:45:09 +0000 | [diff] [blame] | 1230 | def _dup2(a, b): |
| 1231 | # dup2() removes the CLOEXEC flag but |
| 1232 | # we must do it ourselves if dup2() |
| 1233 | # would be a no-op (issue #10806). |
| 1234 | if a == b: |
| 1235 | self._set_cloexec_flag(a, False) |
| 1236 | elif a is not None: |
| 1237 | os.dup2(a, b) |
| 1238 | _dup2(p2cread, 0) |
| 1239 | _dup2(c2pwrite, 1) |
| 1240 | _dup2(errwrite, 2) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1241 | |
Antoine Pitrou | 91ce0d9 | 2011-01-03 18:45:09 +0000 | [diff] [blame] | 1242 | # Close pipe fds. Make sure we don't close the |
| 1243 | # same fd more than once, or standard fds. |
| 1244 | closed = { None } |
| 1245 | for fd in [p2cread, c2pwrite, errwrite]: |
| 1246 | if fd not in closed and fd > 2: |
| 1247 | os.close(fd) |
| 1248 | closed.add(fd) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1249 | |
Facundo Batista | 8c826b7 | 2009-06-19 18:02:28 +0000 | [diff] [blame] | 1250 | if cwd is not None: |
| 1251 | os.chdir(cwd) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1252 | |
Facundo Batista | 8c826b7 | 2009-06-19 18:02:28 +0000 | [diff] [blame] | 1253 | if preexec_fn: |
| 1254 | preexec_fn() |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1255 | |
Charles-François Natali | 4c53314 | 2013-08-25 18:22:49 +0200 | [diff] [blame^] | 1256 | # Close all other fds, if asked for - after |
| 1257 | # preexec_fn(), which may open FDs. |
| 1258 | if close_fds: |
| 1259 | self._close_fds(but=errpipe_write) |
| 1260 | |
Facundo Batista | 8c826b7 | 2009-06-19 18:02:28 +0000 | [diff] [blame] | 1261 | if env is None: |
| 1262 | os.execvp(executable, args) |
| 1263 | else: |
| 1264 | os.execvpe(executable, args, env) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1265 | |
Facundo Batista | 8c826b7 | 2009-06-19 18:02:28 +0000 | [diff] [blame] | 1266 | except: |
| 1267 | exc_type, exc_value, tb = sys.exc_info() |
| 1268 | # Save the traceback and attach it to the exception object |
| 1269 | exc_lines = traceback.format_exception(exc_type, |
| 1270 | exc_value, |
| 1271 | tb) |
| 1272 | exc_value.child_traceback = ''.join(exc_lines) |
| 1273 | os.write(errpipe_write, pickle.dumps(exc_value)) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1274 | |
Facundo Batista | 8c826b7 | 2009-06-19 18:02:28 +0000 | [diff] [blame] | 1275 | # This exitcode won't be reported to applications, so it |
| 1276 | # really doesn't matter what we return. |
| 1277 | os._exit(255) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1278 | |
Facundo Batista | 8c826b7 | 2009-06-19 18:02:28 +0000 | [diff] [blame] | 1279 | # Parent |
| 1280 | if gc_was_enabled: |
| 1281 | gc.enable() |
| 1282 | finally: |
| 1283 | # be sure the FD is closed no matter what |
| 1284 | os.close(errpipe_write) |
| 1285 | |
| 1286 | if p2cread is not None and p2cwrite is not None: |
| 1287 | os.close(p2cread) |
| 1288 | if c2pwrite is not None and c2pread is not None: |
| 1289 | os.close(c2pwrite) |
| 1290 | if errwrite is not None and errread is not None: |
| 1291 | os.close(errwrite) |
| 1292 | |
| 1293 | # Wait for exec to fail or succeed; possibly raising exception |
Gregory P. Smith | cce211f | 2010-03-01 00:05:08 +0000 | [diff] [blame] | 1294 | # Exception limited to 1M |
| 1295 | data = _eintr_retry_call(os.read, errpipe_read, 1048576) |
Facundo Batista | 8c826b7 | 2009-06-19 18:02:28 +0000 | [diff] [blame] | 1296 | finally: |
| 1297 | # be sure the FD is closed no matter what |
| 1298 | os.close(errpipe_read) |
| 1299 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1300 | if data != "": |
Gregory P. Smith | 312efbc | 2010-12-14 15:02:53 +0000 | [diff] [blame] | 1301 | try: |
| 1302 | _eintr_retry_call(os.waitpid, self.pid, 0) |
| 1303 | except OSError as e: |
| 1304 | if e.errno != errno.ECHILD: |
| 1305 | raise |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1306 | child_exception = pickle.loads(data) |
| 1307 | raise child_exception |
| 1308 | |
| 1309 | |
Brett Cannon | 42a0ba7 | 2010-05-14 00:21:48 +0000 | [diff] [blame] | 1310 | def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED, |
| 1311 | _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED, |
| 1312 | _WEXITSTATUS=os.WEXITSTATUS): |
| 1313 | # This method is called (indirectly) by __del__, so it cannot |
| 1314 | # refer to anything outside of its local scope.""" |
| 1315 | if _WIFSIGNALED(sts): |
| 1316 | self.returncode = -_WTERMSIG(sts) |
| 1317 | elif _WIFEXITED(sts): |
| 1318 | self.returncode = _WEXITSTATUS(sts) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1319 | else: |
| 1320 | # Should never happen |
| 1321 | raise RuntimeError("Unknown child exit status!") |
| 1322 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1323 | |
Brett Cannon | 42a0ba7 | 2010-05-14 00:21:48 +0000 | [diff] [blame] | 1324 | def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid, |
Andrew Svetlov | 332562f | 2012-12-24 20:09:27 +0200 | [diff] [blame] | 1325 | _WNOHANG=os.WNOHANG, _os_error=os.error, _ECHILD=errno.ECHILD): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1326 | """Check if child process has terminated. Returns returncode |
Brett Cannon | 42a0ba7 | 2010-05-14 00:21:48 +0000 | [diff] [blame] | 1327 | attribute. |
| 1328 | |
| 1329 | This method is called by __del__, so it cannot reference anything |
| 1330 | outside of the local scope (nor can any methods it calls). |
| 1331 | |
| 1332 | """ |
Peter Astrand | d38ddf4 | 2005-02-10 08:32:50 +0000 | [diff] [blame] | 1333 | if self.returncode is None: |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1334 | try: |
Brett Cannon | 42a0ba7 | 2010-05-14 00:21:48 +0000 | [diff] [blame] | 1335 | pid, sts = _waitpid(self.pid, _WNOHANG) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1336 | if pid == self.pid: |
| 1337 | self._handle_exitstatus(sts) |
Gregory P. Smith | 0798cbc | 2012-09-29 12:02:48 -0700 | [diff] [blame] | 1338 | except _os_error as e: |
Martin v. Löwis | 17de8ff | 2006-04-10 15:55:37 +0000 | [diff] [blame] | 1339 | if _deadstate is not None: |
| 1340 | self.returncode = _deadstate |
Andrew Svetlov | 332562f | 2012-12-24 20:09:27 +0200 | [diff] [blame] | 1341 | if e.errno == _ECHILD: |
Gregory P. Smith | 0798cbc | 2012-09-29 12:02:48 -0700 | [diff] [blame] | 1342 | # This happens if SIGCLD is set to be ignored or |
| 1343 | # waiting for child processes has otherwise been |
| 1344 | # disabled for our process. This child is dead, we |
| 1345 | # can't get the status. |
| 1346 | # http://bugs.python.org/issue15756 |
| 1347 | self.returncode = 0 |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1348 | return self.returncode |
| 1349 | |
| 1350 | |
| 1351 | def wait(self): |
| 1352 | """Wait for child process to terminate. Returns returncode |
| 1353 | attribute.""" |
Gregory P. Smith | f2705ae | 2012-11-10 21:13:20 -0800 | [diff] [blame] | 1354 | while self.returncode is None: |
Gregory P. Smith | 312efbc | 2010-12-14 15:02:53 +0000 | [diff] [blame] | 1355 | try: |
| 1356 | pid, sts = _eintr_retry_call(os.waitpid, self.pid, 0) |
| 1357 | except OSError as e: |
| 1358 | if e.errno != errno.ECHILD: |
| 1359 | raise |
| 1360 | # This happens if SIGCLD is set to be ignored or waiting |
| 1361 | # for child processes has otherwise been disabled for our |
| 1362 | # process. This child is dead, we can't get the status. |
Gregory P. Smith | f2705ae | 2012-11-10 21:13:20 -0800 | [diff] [blame] | 1363 | pid = self.pid |
Gregory P. Smith | 312efbc | 2010-12-14 15:02:53 +0000 | [diff] [blame] | 1364 | sts = 0 |
Gregory P. Smith | f2705ae | 2012-11-10 21:13:20 -0800 | [diff] [blame] | 1365 | # Check the pid and loop as waitpid has been known to return |
| 1366 | # 0 even without WNOHANG in odd situations. issue14396. |
| 1367 | if pid == self.pid: |
| 1368 | self._handle_exitstatus(sts) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1369 | return self.returncode |
| 1370 | |
| 1371 | |
Peter Astrand | 23109f0 | 2005-03-03 20:28:59 +0000 | [diff] [blame] | 1372 | def _communicate(self, input): |
Gregory P. Smith | dd7ca24 | 2009-07-04 01:49:29 +0000 | [diff] [blame] | 1373 | if self.stdin: |
| 1374 | # Flush stdio buffer. This might block, if the user has |
| 1375 | # been writing to .stdin in an uncontrolled fashion. |
| 1376 | self.stdin.flush() |
| 1377 | if not input: |
| 1378 | self.stdin.close() |
| 1379 | |
| 1380 | if _has_poll: |
| 1381 | stdout, stderr = self._communicate_with_poll(input) |
| 1382 | else: |
| 1383 | stdout, stderr = self._communicate_with_select(input) |
| 1384 | |
| 1385 | # All data exchanged. Translate lists into strings. |
| 1386 | if stdout is not None: |
| 1387 | stdout = ''.join(stdout) |
| 1388 | if stderr is not None: |
| 1389 | stderr = ''.join(stderr) |
| 1390 | |
| 1391 | # Translate newlines, if requested. We cannot let the file |
| 1392 | # object do the translation: It is based on stdio, which is |
| 1393 | # impossible to combine with select (unless forcing no |
| 1394 | # buffering). |
| 1395 | if self.universal_newlines and hasattr(file, 'newlines'): |
| 1396 | if stdout: |
| 1397 | stdout = self._translate_newlines(stdout) |
| 1398 | if stderr: |
| 1399 | stderr = self._translate_newlines(stderr) |
| 1400 | |
| 1401 | self.wait() |
| 1402 | return (stdout, stderr) |
| 1403 | |
| 1404 | |
| 1405 | def _communicate_with_poll(self, input): |
| 1406 | stdout = None # Return |
| 1407 | stderr = None # Return |
| 1408 | fd2file = {} |
| 1409 | fd2output = {} |
| 1410 | |
| 1411 | poller = select.poll() |
| 1412 | def register_and_append(file_obj, eventmask): |
| 1413 | poller.register(file_obj.fileno(), eventmask) |
| 1414 | fd2file[file_obj.fileno()] = file_obj |
| 1415 | |
| 1416 | def close_unregister_and_remove(fd): |
| 1417 | poller.unregister(fd) |
| 1418 | fd2file[fd].close() |
| 1419 | fd2file.pop(fd) |
| 1420 | |
| 1421 | if self.stdin and input: |
| 1422 | register_and_append(self.stdin, select.POLLOUT) |
| 1423 | |
| 1424 | select_POLLIN_POLLPRI = select.POLLIN | select.POLLPRI |
| 1425 | if self.stdout: |
| 1426 | register_and_append(self.stdout, select_POLLIN_POLLPRI) |
| 1427 | fd2output[self.stdout.fileno()] = stdout = [] |
| 1428 | if self.stderr: |
| 1429 | register_and_append(self.stderr, select_POLLIN_POLLPRI) |
| 1430 | fd2output[self.stderr.fileno()] = stderr = [] |
| 1431 | |
| 1432 | input_offset = 0 |
| 1433 | while fd2file: |
| 1434 | try: |
| 1435 | ready = poller.poll() |
| 1436 | except select.error, e: |
| 1437 | if e.args[0] == errno.EINTR: |
| 1438 | continue |
| 1439 | raise |
| 1440 | |
| 1441 | for fd, mode in ready: |
| 1442 | if mode & select.POLLOUT: |
| 1443 | chunk = input[input_offset : input_offset + _PIPE_BUF] |
Ross Lagerwall | 104c3f1 | 2011-04-05 15:24:34 +0200 | [diff] [blame] | 1444 | try: |
| 1445 | input_offset += os.write(fd, chunk) |
| 1446 | except OSError as e: |
| 1447 | if e.errno == errno.EPIPE: |
| 1448 | close_unregister_and_remove(fd) |
| 1449 | else: |
| 1450 | raise |
| 1451 | else: |
| 1452 | if input_offset >= len(input): |
| 1453 | close_unregister_and_remove(fd) |
Gregory P. Smith | dd7ca24 | 2009-07-04 01:49:29 +0000 | [diff] [blame] | 1454 | elif mode & select_POLLIN_POLLPRI: |
| 1455 | data = os.read(fd, 4096) |
| 1456 | if not data: |
| 1457 | close_unregister_and_remove(fd) |
| 1458 | fd2output[fd].append(data) |
| 1459 | else: |
| 1460 | # Ignore hang up or errors. |
| 1461 | close_unregister_and_remove(fd) |
| 1462 | |
| 1463 | return (stdout, stderr) |
| 1464 | |
| 1465 | |
| 1466 | def _communicate_with_select(self, input): |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1467 | read_set = [] |
| 1468 | write_set = [] |
| 1469 | stdout = None # Return |
| 1470 | stderr = None # Return |
| 1471 | |
Gregory P. Smith | dd7ca24 | 2009-07-04 01:49:29 +0000 | [diff] [blame] | 1472 | if self.stdin and input: |
| 1473 | write_set.append(self.stdin) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1474 | if self.stdout: |
| 1475 | read_set.append(self.stdout) |
Tim Peters | e718f61 | 2004-10-12 21:51:32 +0000 | [diff] [blame] | 1476 | stdout = [] |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1477 | if self.stderr: |
| 1478 | read_set.append(self.stderr) |
| 1479 | stderr = [] |
| 1480 | |
Peter Astrand | 1812f8c | 2007-01-07 14:34:16 +0000 | [diff] [blame] | 1481 | input_offset = 0 |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1482 | while read_set or write_set: |
Gregory P. Smith | f414064 | 2008-07-06 07:16:40 +0000 | [diff] [blame] | 1483 | try: |
| 1484 | rlist, wlist, xlist = select.select(read_set, write_set, []) |
| 1485 | except select.error, e: |
| 1486 | if e.args[0] == errno.EINTR: |
| 1487 | continue |
| 1488 | raise |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1489 | |
| 1490 | if self.stdin in wlist: |
Gregory P. Smith | dd7ca24 | 2009-07-04 01:49:29 +0000 | [diff] [blame] | 1491 | chunk = input[input_offset : input_offset + _PIPE_BUF] |
Ross Lagerwall | 104c3f1 | 2011-04-05 15:24:34 +0200 | [diff] [blame] | 1492 | try: |
| 1493 | bytes_written = os.write(self.stdin.fileno(), chunk) |
| 1494 | except OSError as e: |
| 1495 | if e.errno == errno.EPIPE: |
| 1496 | self.stdin.close() |
| 1497 | write_set.remove(self.stdin) |
| 1498 | else: |
| 1499 | raise |
| 1500 | else: |
| 1501 | input_offset += bytes_written |
| 1502 | if input_offset >= len(input): |
| 1503 | self.stdin.close() |
| 1504 | write_set.remove(self.stdin) |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1505 | |
| 1506 | if self.stdout in rlist: |
| 1507 | data = os.read(self.stdout.fileno(), 1024) |
| 1508 | if data == "": |
| 1509 | self.stdout.close() |
| 1510 | read_set.remove(self.stdout) |
| 1511 | stdout.append(data) |
| 1512 | |
| 1513 | if self.stderr in rlist: |
| 1514 | data = os.read(self.stderr.fileno(), 1024) |
| 1515 | if data == "": |
| 1516 | self.stderr.close() |
| 1517 | read_set.remove(self.stderr) |
| 1518 | stderr.append(data) |
| 1519 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1520 | return (stdout, stderr) |
| 1521 | |
Gregory P. Smith | dd7ca24 | 2009-07-04 01:49:29 +0000 | [diff] [blame] | 1522 | |
Christian Heimes | e74c8f2 | 2008-04-19 02:23:57 +0000 | [diff] [blame] | 1523 | def send_signal(self, sig): |
| 1524 | """Send a signal to the process |
| 1525 | """ |
| 1526 | os.kill(self.pid, sig) |
| 1527 | |
| 1528 | def terminate(self): |
| 1529 | """Terminate the process with SIGTERM |
| 1530 | """ |
| 1531 | self.send_signal(signal.SIGTERM) |
| 1532 | |
| 1533 | def kill(self): |
| 1534 | """Kill the process with SIGKILL |
| 1535 | """ |
| 1536 | self.send_signal(signal.SIGKILL) |
| 1537 | |
Fredrik Lundh | 5b3687d | 2004-10-12 15:26:28 +0000 | [diff] [blame] | 1538 | |
| 1539 | def _demo_posix(): |
| 1540 | # |
| 1541 | # Example 1: Simple redirection: Get process list |
| 1542 | # |
| 1543 | plist = Popen(["ps"], stdout=PIPE).communicate()[0] |
| 1544 | print "Process list:" |
| 1545 | print plist |
| 1546 | |
| 1547 | # |
| 1548 | # Example 2: Change uid before executing child |
| 1549 | # |
| 1550 | if os.getuid() == 0: |
| 1551 | p = Popen(["id"], preexec_fn=lambda: os.setuid(100)) |
| 1552 | p.wait() |
| 1553 | |
| 1554 | # |
| 1555 | # Example 3: Connecting several subprocesses |
| 1556 | # |
| 1557 | print "Looking for 'hda'..." |
| 1558 | p1 = Popen(["dmesg"], stdout=PIPE) |
| 1559 | p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) |
| 1560 | print repr(p2.communicate()[0]) |
| 1561 | |
| 1562 | # |
| 1563 | # Example 4: Catch execution error |
| 1564 | # |
| 1565 | print |
| 1566 | print "Trying a weird file..." |
| 1567 | try: |
| 1568 | print Popen(["/this/path/does/not/exist"]).communicate() |
| 1569 | except OSError, e: |
| 1570 | if e.errno == errno.ENOENT: |
| 1571 | print "The file didn't exist. I thought so..." |
| 1572 | print "Child traceback:" |
| 1573 | print e.child_traceback |
| 1574 | else: |
| 1575 | print "Error", e.errno |
| 1576 | else: |
| 1577 | print >>sys.stderr, "Gosh. No error." |
| 1578 | |
| 1579 | |
| 1580 | def _demo_windows(): |
| 1581 | # |
| 1582 | # Example 1: Connecting several subprocesses |
| 1583 | # |
| 1584 | print "Looking for 'PROMPT' in set output..." |
| 1585 | p1 = Popen("set", stdout=PIPE, shell=True) |
| 1586 | p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE) |
| 1587 | print repr(p2.communicate()[0]) |
| 1588 | |
| 1589 | # |
| 1590 | # Example 2: Simple execution of program |
| 1591 | # |
| 1592 | print "Executing calc..." |
| 1593 | p = Popen("calc") |
| 1594 | p.wait() |
| 1595 | |
| 1596 | |
| 1597 | if __name__ == "__main__": |
| 1598 | if mswindows: |
| 1599 | _demo_windows() |
| 1600 | else: |
| 1601 | _demo_posix() |