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