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