1# subprocess - Subprocesses with accessible I/O streams 2# 3# For more information about this module, see PEP 324. 4# 5# Copyright (c) 2003-2004 by Peter Astrand <astrand@lysator.liu.se> 6# 7# By obtaining, using, and/or copying this software and/or its 8# associated documentation, you agree that you have read, understood, 9# and will comply with the following terms and conditions: 10# 11# Permission to use, copy, modify, and distribute this software and 12# its associated documentation for any purpose and without fee is 13# hereby granted, provided that the above copyright notice appears in 14# all copies, and that both that copyright notice and this permission 15# notice appear in supporting documentation, and that the name of the 16# author not be used in advertising or publicity pertaining to 17# distribution of the software without specific, written prior 18# permission. 19# 20# THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 21# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. 22# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR 23# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS 24# OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, 25# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION 26# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 27# 28# Use of this file within git is permitted under GPLv2. 29# 30 31r"""subprocess - Subprocesses with accessible I/O streams 32 33This module allows you to spawn processes, connect to their 34input/output/error pipes, and obtain their return codes. This module 35intends to replace several other, older modules and functions, like: 36 37os.system 38os.spawn* 39os.popen* 40popen2.* 41commands.* 42 43Information about how the subprocess module can be used to replace these 44modules and functions can be found below. 45 46 47 48Using the subprocess module 49=========================== 50This module defines one class called Popen: 51 52class Popen(args, bufsize=0, executable=None, 53 stdin=None, stdout=None, stderr=None, 54 preexec_fn=None, close_fds=False, shell=False, 55 cwd=None, env=None, universal_newlines=False, 56 startupinfo=None, creationflags=0): 57 58 59Arguments are: 60 61args should be a string, or a sequence of program arguments. The 62program to execute is normally the first item in the args sequence or 63string, but can be explicitly set by using the executable argument. 64 65On UNIX, with shell=False (default): In this case, the Popen class 66uses os.execvp() to execute the child program. args should normally 67be a sequence. A string will be treated as a sequence with the string 68as the only item (the program to execute). 69 70On UNIX, with shell=True: If args is a string, it specifies the 71command string to execute through the shell. If args is a sequence, 72the first item specifies the command string, and any additional items 73will be treated as additional shell arguments. 74 75On Windows: the Popen class uses CreateProcess() to execute the child 76program, which operates on strings. If args is a sequence, it will be 77converted to a string using the list2cmdline method. Please note that 78not all MS Windows applications interpret the command line the same 79way: The list2cmdline is designed for applications using the same 80rules as the MS C runtime. 81 82bufsize, if given, has the same meaning as the corresponding argument 83to the built-in open() function: 0 means unbuffered, 1 means line 84buffered, any other positive value means use a buffer of 85(approximately) that size. A negative bufsize means to use the system 86default, which usually means fully buffered. The default value for 87bufsize is 0 (unbuffered). 88 89stdin, stdout and stderr specify the executed programs' standard 90input, standard output and standard error file handles, respectively. 91Valid values are PIPE, an existing file descriptor (a positive 92integer), an existing file object, and None. PIPE indicates that a 93new pipe to the child should be created. With None, no redirection 94will occur; the child's file handles will be inherited from the 95parent. Additionally, stderr can be STDOUT, which indicates that the 96stderr data from the applications should be captured into the same 97file handle as for stdout. 98 99If preexec_fn is set to a callable object, this object will be called 100in the child process just before the child is executed. 101 102If close_fds is true, all file descriptors except 0, 1 and 2 will be 103closed before the child process is executed. 104 105if shell is true, the specified command will be executed through the 106shell. 107 108If cwd is not None, the current directory will be changed to cwd 109before the child is executed. 110 111If env is not None, it defines the environment variables for the new 112process. 113 114If universal_newlines is true, the file objects stdout and stderr are 115opened as a text files, but lines may be terminated by any of '\n', 116the Unix end-of-line convention, '\r', the Macintosh convention or 117'\r\n', the Windows convention. All of these external representations 118are seen as '\n' by the Python program. Note: This feature is only 119available if Python is built with universal newline support (the 120default). Also, the newlines attribute of the file objects stdout, 121stdin and stderr are not updated by the communicate() method. 122 123The startupinfo and creationflags, if given, will be passed to the 124underlying CreateProcess() function. They can specify things such as 125appearance of the main window and priority for the new process. 126(Windows only) 127 128 129This module also defines two shortcut functions: 130 131call(*args, **kwargs): 132 Run command with arguments. Wait for command to complete, then 133 return the returncode attribute. 134 135 The arguments are the same as for the Popen constructor. Example: 136 137 retcode = call(["ls", "-l"]) 138 139 140Exceptions 141---------- 142Exceptions raised in the child process, before the new program has 143started to execute, will be re-raised in the parent. Additionally, 144the exception object will have one extra attribute called 145'child_traceback', which is a string containing traceback information 146from the childs point of view. 147 148The most common exception raised is OSError. This occurs, for 149example, when trying to execute a non-existent file. Applications 150should prepare for OSErrors. 151 152A ValueError will be raised if Popen is called with invalid arguments. 153 154 155Security 156-------- 157Unlike some other popen functions, this implementation will never call 158/bin/sh implicitly. This means that all characters, including shell 159metacharacters, can safely be passed to child processes. 160 161 162Popen objects 163============= 164Instances of the Popen class have the following methods: 165 166poll() 167 Check if child process has terminated. Returns returncode 168 attribute. 169 170wait() 171 Wait for child process to terminate. Returns returncode attribute. 172 173communicate(input=None) 174 Interact with process: Send data to stdin. Read data from stdout 175 and stderr, until end-of-file is reached. Wait for process to 176 terminate. The optional stdin argument should be a string to be 177 sent to the child process, or None, if no data should be sent to 178 the child. 179 180 communicate() returns a tuple (stdout, stderr). 181 182 Note: The data read is buffered in memory, so do not use this 183 method if the data size is large or unlimited. 184 185The following attributes are also available: 186 187stdin 188 If the stdin argument is PIPE, this attribute is a file object 189 that provides input to the child process. Otherwise, it is None. 190 191stdout 192 If the stdout argument is PIPE, this attribute is a file object 193 that provides output from the child process. Otherwise, it is 194 None. 195 196stderr 197 If the stderr argument is PIPE, this attribute is file object that 198 provides error output from the child process. Otherwise, it is 199 None. 200 201pid 202 The process ID of the child process. 203 204returncode 205 The child return code. A None value indicates that the process 206 hasn't terminated yet. A negative value -N indicates that the 207 child was terminated by signal N (UNIX only). 208 209 210Replacing older functions with the subprocess module 211==================================================== 212In this section, "a ==> b" means that b can be used as a replacement 213for a. 214 215Note: All functions in this section fail (more or less) silently if 216the executed program cannot be found; this module raises an OSError 217exception. 218 219In the following examples, we assume that the subprocess module is 220imported with "from subprocess import *". 221 222 223Replacing /bin/sh shell backquote 224--------------------------------- 225output=`mycmd myarg` 226==> 227output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0] 228 229 230Replacing shell pipe line 231------------------------- 232output=`dmesg | grep hda` 233==> 234p1 = Popen(["dmesg"], stdout=PIPE) 235p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) 236output = p2.communicate()[0] 237 238 239Replacing os.system() 240--------------------- 241sts = os.system("mycmd" + " myarg") 242==> 243p = Popen("mycmd" + " myarg", shell=True) 244sts = os.waitpid(p.pid, 0) 245 246Note: 247 248* Calling the program through the shell is usually not required. 249 250* It's easier to look at the returncode attribute than the 251 exitstatus. 252 253A more real-world example would look like this: 254 255try: 256 retcode = call("mycmd" + " myarg", shell=True) 257 if retcode < 0: 258 print >>sys.stderr, "Child was terminated by signal", -retcode 259 else: 260 print >>sys.stderr, "Child returned", retcode 261except OSError, e: 262 print >>sys.stderr, "Execution failed:", e 263 264 265Replacing os.spawn* 266------------------- 267P_NOWAIT example: 268 269pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") 270==> 271pid = Popen(["/bin/mycmd", "myarg"]).pid 272 273 274P_WAIT example: 275 276retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg") 277==> 278retcode = call(["/bin/mycmd", "myarg"]) 279 280 281Vector example: 282 283os.spawnvp(os.P_NOWAIT, path, args) 284==> 285Popen([path] + args[1:]) 286 287 288Environment example: 289 290os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env) 291==> 292Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"}) 293 294 295Replacing os.popen* 296------------------- 297pipe = os.popen(cmd, mode='r', bufsize) 298==> 299pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout 300 301pipe = os.popen(cmd, mode='w', bufsize) 302==> 303pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin 304 305 306(child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize) 307==> 308p = Popen(cmd, shell=True, bufsize=bufsize, 309 stdin=PIPE, stdout=PIPE, close_fds=True) 310(child_stdin, child_stdout) = (p.stdin, p.stdout) 311 312 313(child_stdin, 314 child_stdout, 315 child_stderr) = os.popen3(cmd, mode, bufsize) 316==> 317p = Popen(cmd, shell=True, bufsize=bufsize, 318 stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) 319(child_stdin, 320 child_stdout, 321 child_stderr) = (p.stdin, p.stdout, p.stderr) 322 323 324(child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize) 325==> 326p = Popen(cmd, shell=True, bufsize=bufsize, 327 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) 328(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout) 329 330 331Replacing popen2.* 332------------------ 333Note: If the cmd argument to popen2 functions is a string, the command 334is executed through /bin/sh. If it is a list, the command is directly 335executed. 336 337(child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode) 338==> 339p = Popen(["somestring"], shell=True, bufsize=bufsize 340 stdin=PIPE, stdout=PIPE, close_fds=True) 341(child_stdout, child_stdin) = (p.stdout, p.stdin) 342 343 344(child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode) 345==> 346p = Popen(["mycmd", "myarg"], bufsize=bufsize, 347 stdin=PIPE, stdout=PIPE, close_fds=True) 348(child_stdout, child_stdin) = (p.stdout, p.stdin) 349 350The popen2.Popen3 and popen3.Popen4 basically works as subprocess.Popen, 351except that: 352 353* subprocess.Popen raises an exception if the execution fails 354* the capturestderr argument is replaced with the stderr argument. 355* stdin=PIPE and stdout=PIPE must be specified. 356* popen2 closes all filedescriptors by default, but you have to specify 357 close_fds=True with subprocess.Popen. 358 359 360""" 361 362import sys 363mswindows = (sys.platform =="win32") 364 365import os 366import types 367import traceback 368 369if mswindows: 370import threading 371import msvcrt 372if0:# <-- change this to use pywin32 instead of the _subprocess driver 373import pywintypes 374from win32api import GetStdHandle, STD_INPUT_HANDLE, \ 375 STD_OUTPUT_HANDLE, STD_ERROR_HANDLE 376from win32api import GetCurrentProcess, DuplicateHandle, \ 377 GetModuleFileName, GetVersion 378from win32con import DUPLICATE_SAME_ACCESS, SW_HIDE 379from win32pipe import CreatePipe 380from win32process import CreateProcess, STARTUPINFO, \ 381 GetExitCodeProcess, STARTF_USESTDHANDLES, \ 382 STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE 383from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0 384else: 385from _subprocess import* 386class STARTUPINFO: 387 dwFlags =0 388 hStdInput =None 389 hStdOutput =None 390 hStdError =None 391class pywintypes: 392 error =IOError 393else: 394import select 395import errno 396import fcntl 397import pickle 398 399__all__ = ["Popen","PIPE","STDOUT","call"] 400 401try: 402 MAXFD = os.sysconf("SC_OPEN_MAX") 403except: 404 MAXFD =256 405 406# True/False does not exist on 2.2.0 407try: 408False 409exceptNameError: 410False=0 411True=1 412 413_active = [] 414 415def_cleanup(): 416for inst in _active[:]: 417 inst.poll() 418 419PIPE = -1 420STDOUT = -2 421 422 423defcall(*args, **kwargs): 424"""Run command with arguments. Wait for command to complete, then 425 return the returncode attribute. 426 427 The arguments are the same as for the Popen constructor. Example: 428 429 retcode = call(["ls", "-l"]) 430 """ 431returnPopen(*args, **kwargs).wait() 432 433 434deflist2cmdline(seq): 435""" 436 Translate a sequence of arguments into a command line 437 string, using the same rules as the MS C runtime: 438 439 1) Arguments are delimited by white space, which is either a 440 space or a tab. 441 442 2) A string surrounded by double quotation marks is 443 interpreted as a single argument, regardless of white space 444 contained within. A quoted string can be embedded in an 445 argument. 446 447 3) A double quotation mark preceded by a backslash is 448 interpreted as a literal double quotation mark. 449 450 4) Backslashes are interpreted literally, unless they 451 immediately precede a double quotation mark. 452 453 5) If backslashes immediately precede a double quotation mark, 454 every pair of backslashes is interpreted as a literal 455 backslash. If the number of backslashes is odd, the last 456 backslash escapes the next double quotation mark as 457 described in rule 3. 458 """ 459 460# See 461# http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp 462 result = [] 463 needquote =False 464for arg in seq: 465 bs_buf = [] 466 467# Add a space to separate this argument from the others 468if result: 469 result.append(' ') 470 471 needquote = (" "in arg)or("\t"in arg) 472if needquote: 473 result.append('"') 474 475for c in arg: 476if c =='\\': 477# Don't know if we need to double yet. 478 bs_buf.append(c) 479elif c =='"': 480# Double backspaces. 481 result.append('\\'*len(bs_buf)*2) 482 bs_buf = [] 483 result.append('\\"') 484else: 485# Normal char 486if bs_buf: 487 result.extend(bs_buf) 488 bs_buf = [] 489 result.append(c) 490 491# Add remaining backspaces, if any. 492if bs_buf: 493 result.extend(bs_buf) 494 495if needquote: 496 result.extend(bs_buf) 497 result.append('"') 498 499return''.join(result) 500 501 502classPopen(object): 503def__init__(self, args, bufsize=0, executable=None, 504 stdin=None, stdout=None, stderr=None, 505 preexec_fn=None, close_fds=False, shell=False, 506 cwd=None, env=None, universal_newlines=False, 507 startupinfo=None, creationflags=0): 508"""Create new Popen instance.""" 509_cleanup() 510 511if notisinstance(bufsize, (int,long)): 512raiseTypeError("bufsize must be an integer") 513 514if mswindows: 515if preexec_fn is not None: 516raiseValueError("preexec_fn is not supported on Windows " 517"platforms") 518if close_fds: 519raiseValueError("close_fds is not supported on Windows " 520"platforms") 521else: 522# POSIX 523if startupinfo is not None: 524raiseValueError("startupinfo is only supported on Windows " 525"platforms") 526if creationflags !=0: 527raiseValueError("creationflags is only supported on Windows " 528"platforms") 529 530 self.stdin =None 531 self.stdout =None 532 self.stderr =None 533 self.pid =None 534 self.returncode =None 535 self.universal_newlines = universal_newlines 536 537# Input and output objects. The general principle is like 538# this: 539# 540# Parent Child 541# ------ ----- 542# p2cwrite ---stdin---> p2cread 543# c2pread <--stdout--- c2pwrite 544# errread <--stderr--- errwrite 545# 546# On POSIX, the child objects are file descriptors. On 547# Windows, these are Windows file handles. The parent objects 548# are file descriptors on both platforms. The parent objects 549# are None when not using PIPEs. The child objects are None 550# when not redirecting. 551 552(p2cread, p2cwrite, 553 c2pread, c2pwrite, 554 errread, errwrite) = self._get_handles(stdin, stdout, stderr) 555 556 self._execute_child(args, executable, preexec_fn, close_fds, 557 cwd, env, universal_newlines, 558 startupinfo, creationflags, shell, 559 p2cread, p2cwrite, 560 c2pread, c2pwrite, 561 errread, errwrite) 562 563if p2cwrite: 564 self.stdin = os.fdopen(p2cwrite,'wb', bufsize) 565if c2pread: 566if universal_newlines: 567 self.stdout = os.fdopen(c2pread,'rU', bufsize) 568else: 569 self.stdout = os.fdopen(c2pread,'rb', bufsize) 570if errread: 571if universal_newlines: 572 self.stderr = os.fdopen(errread,'rU', bufsize) 573else: 574 self.stderr = os.fdopen(errread,'rb', bufsize) 575 576 _active.append(self) 577 578 579def_translate_newlines(self, data): 580 data = data.replace("\r\n","\n") 581 data = data.replace("\r","\n") 582return data 583 584 585if mswindows: 586# 587# Windows methods 588# 589def_get_handles(self, stdin, stdout, stderr): 590"""Construct and return tupel with IO objects: 591 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite 592 """ 593if stdin ==None and stdout ==None and stderr ==None: 594return(None,None,None,None,None,None) 595 596 p2cread, p2cwrite =None,None 597 c2pread, c2pwrite =None,None 598 errread, errwrite =None,None 599 600if stdin ==None: 601 p2cread =GetStdHandle(STD_INPUT_HANDLE) 602elif stdin == PIPE: 603 p2cread, p2cwrite =CreatePipe(None,0) 604# Detach and turn into fd 605 p2cwrite = p2cwrite.Detach() 606 p2cwrite = msvcrt.open_osfhandle(p2cwrite,0) 607eliftype(stdin) == types.IntType: 608 p2cread = msvcrt.get_osfhandle(stdin) 609else: 610# Assuming file-like object 611 p2cread = msvcrt.get_osfhandle(stdin.fileno()) 612 p2cread = self._make_inheritable(p2cread) 613 614if stdout ==None: 615 c2pwrite =GetStdHandle(STD_OUTPUT_HANDLE) 616elif stdout == PIPE: 617 c2pread, c2pwrite =CreatePipe(None,0) 618# Detach and turn into fd 619 c2pread = c2pread.Detach() 620 c2pread = msvcrt.open_osfhandle(c2pread,0) 621eliftype(stdout) == types.IntType: 622 c2pwrite = msvcrt.get_osfhandle(stdout) 623else: 624# Assuming file-like object 625 c2pwrite = msvcrt.get_osfhandle(stdout.fileno()) 626 c2pwrite = self._make_inheritable(c2pwrite) 627 628if stderr ==None: 629 errwrite =GetStdHandle(STD_ERROR_HANDLE) 630elif stderr == PIPE: 631 errread, errwrite =CreatePipe(None,0) 632# Detach and turn into fd 633 errread = errread.Detach() 634 errread = msvcrt.open_osfhandle(errread,0) 635elif stderr == STDOUT: 636 errwrite = c2pwrite 637eliftype(stderr) == types.IntType: 638 errwrite = msvcrt.get_osfhandle(stderr) 639else: 640# Assuming file-like object 641 errwrite = msvcrt.get_osfhandle(stderr.fileno()) 642 errwrite = self._make_inheritable(errwrite) 643 644return(p2cread, p2cwrite, 645 c2pread, c2pwrite, 646 errread, errwrite) 647 648 649def_make_inheritable(self, handle): 650"""Return a duplicate of handle, which is inheritable""" 651returnDuplicateHandle(GetCurrentProcess(), handle, 652GetCurrentProcess(),0,1, 653 DUPLICATE_SAME_ACCESS) 654 655 656def_find_w9xpopen(self): 657"""Find and return absolut path to w9xpopen.exe""" 658 w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)), 659"w9xpopen.exe") 660if not os.path.exists(w9xpopen): 661# Eeek - file-not-found - possibly an embedding 662# situation - see if we can locate it in sys.exec_prefix 663 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix), 664"w9xpopen.exe") 665if not os.path.exists(w9xpopen): 666raiseRuntimeError("Cannot locate w9xpopen.exe, which is " 667"needed for Popen to work with your " 668"shell or platform.") 669return w9xpopen 670 671 672def_execute_child(self, args, executable, preexec_fn, close_fds, 673 cwd, env, universal_newlines, 674 startupinfo, creationflags, shell, 675 p2cread, p2cwrite, 676 c2pread, c2pwrite, 677 errread, errwrite): 678"""Execute program (MS Windows version)""" 679 680if notisinstance(args, types.StringTypes): 681 args =list2cmdline(args) 682 683# Process startup details 684 default_startupinfo =STARTUPINFO() 685if startupinfo ==None: 686 startupinfo = default_startupinfo 687if not None in(p2cread, c2pwrite, errwrite): 688 startupinfo.dwFlags |= STARTF_USESTDHANDLES 689 startupinfo.hStdInput = p2cread 690 startupinfo.hStdOutput = c2pwrite 691 startupinfo.hStdError = errwrite 692 693if shell: 694 default_startupinfo.dwFlags |= STARTF_USESHOWWINDOW 695 default_startupinfo.wShowWindow = SW_HIDE 696 comspec = os.environ.get("COMSPEC","cmd.exe") 697 args = comspec +" /c "+ args 698if(GetVersion() >=0x80000000L or 699 os.path.basename(comspec).lower() =="command.com"): 700# Win9x, or using command.com on NT. We need to 701# use the w9xpopen intermediate program. For more 702# information, see KB Q150956 703# (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp) 704 w9xpopen = self._find_w9xpopen() 705 args ='"%s"%s'% (w9xpopen, args) 706# Not passing CREATE_NEW_CONSOLE has been known to 707# cause random failures on win9x. Specifically a 708# dialog: "Your program accessed mem currently in 709# use at xxx" and a hopeful warning about the 710# stability of your system. Cost is Ctrl+C wont 711# kill children. 712 creationflags |= CREATE_NEW_CONSOLE 713 714# Start the process 715try: 716 hp, ht, pid, tid =CreateProcess(executable, args, 717# no special security 718None,None, 719# must inherit handles to pass std 720# handles 7211, 722 creationflags, 723 env, 724 cwd, 725 startupinfo) 726except pywintypes.error, e: 727# Translate pywintypes.error to WindowsError, which is 728# a subclass of OSError. FIXME: We should really 729# translate errno using _sys_errlist (or simliar), but 730# how can this be done from Python? 731raiseWindowsError(*e.args) 732 733# Retain the process handle, but close the thread handle 734 self._handle = hp 735 self.pid = pid 736 ht.Close() 737 738# Child is launched. Close the parent's copy of those pipe 739# handles that only the child should have open. You need 740# to make sure that no handles to the write end of the 741# output pipe are maintained in this process or else the 742# pipe will not close when the child process exits and the 743# ReadFile will hang. 744if p2cread !=None: 745 p2cread.Close() 746if c2pwrite !=None: 747 c2pwrite.Close() 748if errwrite !=None: 749 errwrite.Close() 750 751 752defpoll(self): 753"""Check if child process has terminated. Returns returncode 754 attribute.""" 755if self.returncode ==None: 756ifWaitForSingleObject(self._handle,0) == WAIT_OBJECT_0: 757 self.returncode =GetExitCodeProcess(self._handle) 758 _active.remove(self) 759return self.returncode 760 761 762defwait(self): 763"""Wait for child process to terminate. Returns returncode 764 attribute.""" 765if self.returncode ==None: 766 obj =WaitForSingleObject(self._handle, INFINITE) 767 self.returncode =GetExitCodeProcess(self._handle) 768 _active.remove(self) 769return self.returncode 770 771 772def_readerthread(self, fh,buffer): 773buffer.append(fh.read()) 774 775 776defcommunicate(self,input=None): 777"""Interact with process: Send data to stdin. Read data from 778 stdout and stderr, until end-of-file is reached. Wait for 779 process to terminate. The optional input argument should be a 780 string to be sent to the child process, or None, if no data 781 should be sent to the child. 782 783 communicate() returns a tuple (stdout, stderr).""" 784 stdout =None# Return 785 stderr =None# Return 786 787if self.stdout: 788 stdout = [] 789 stdout_thread = threading.Thread(target=self._readerthread, 790 args=(self.stdout, stdout)) 791 stdout_thread.setDaemon(True) 792 stdout_thread.start() 793if self.stderr: 794 stderr = [] 795 stderr_thread = threading.Thread(target=self._readerthread, 796 args=(self.stderr, stderr)) 797 stderr_thread.setDaemon(True) 798 stderr_thread.start() 799 800if self.stdin: 801ifinput!=None: 802 self.stdin.write(input) 803 self.stdin.close() 804 805if self.stdout: 806 stdout_thread.join() 807if self.stderr: 808 stderr_thread.join() 809 810# All data exchanged. Translate lists into strings. 811if stdout !=None: 812 stdout = stdout[0] 813if stderr !=None: 814 stderr = stderr[0] 815 816# Translate newlines, if requested. We cannot let the file 817# object do the translation: It is based on stdio, which is 818# impossible to combine with select (unless forcing no 819# buffering). 820if self.universal_newlines andhasattr(open,'newlines'): 821if stdout: 822 stdout = self._translate_newlines(stdout) 823if stderr: 824 stderr = self._translate_newlines(stderr) 825 826 self.wait() 827return(stdout, stderr) 828 829else: 830# 831# POSIX methods 832# 833def_get_handles(self, stdin, stdout, stderr): 834"""Construct and return tupel with IO objects: 835 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite 836 """ 837 p2cread, p2cwrite =None,None 838 c2pread, c2pwrite =None,None 839 errread, errwrite =None,None 840 841if stdin ==None: 842pass 843elif stdin == PIPE: 844 p2cread, p2cwrite = os.pipe() 845eliftype(stdin) == types.IntType: 846 p2cread = stdin 847else: 848# Assuming file-like object 849 p2cread = stdin.fileno() 850 851if stdout ==None: 852pass 853elif stdout == PIPE: 854 c2pread, c2pwrite = os.pipe() 855eliftype(stdout) == types.IntType: 856 c2pwrite = stdout 857else: 858# Assuming file-like object 859 c2pwrite = stdout.fileno() 860 861if stderr ==None: 862pass 863elif stderr == PIPE: 864 errread, errwrite = os.pipe() 865elif stderr == STDOUT: 866 errwrite = c2pwrite 867eliftype(stderr) == types.IntType: 868 errwrite = stderr 869else: 870# Assuming file-like object 871 errwrite = stderr.fileno() 872 873return(p2cread, p2cwrite, 874 c2pread, c2pwrite, 875 errread, errwrite) 876 877 878def_set_cloexec_flag(self, fd): 879try: 880 cloexec_flag = fcntl.FD_CLOEXEC 881exceptAttributeError: 882 cloexec_flag =1 883 884 old = fcntl.fcntl(fd, fcntl.F_GETFD) 885 fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag) 886 887 888def_close_fds(self, but): 889for i inrange(3, MAXFD): 890if i == but: 891continue 892try: 893 os.close(i) 894except: 895pass 896 897 898def_execute_child(self, args, executable, preexec_fn, close_fds, 899 cwd, env, universal_newlines, 900 startupinfo, creationflags, shell, 901 p2cread, p2cwrite, 902 c2pread, c2pwrite, 903 errread, errwrite): 904"""Execute program (POSIX version)""" 905 906ifisinstance(args, types.StringTypes): 907 args = [args] 908 909if shell: 910 args = ["/bin/sh","-c"] + args 911 912if executable ==None: 913 executable = args[0] 914 915# For transferring possible exec failure from child to parent 916# The first char specifies the exception type: 0 means 917# OSError, 1 means some other error. 918 errpipe_read, errpipe_write = os.pipe() 919 self._set_cloexec_flag(errpipe_write) 920 921 self.pid = os.fork() 922if self.pid ==0: 923# Child 924try: 925# Close parent's pipe ends 926if p2cwrite: 927 os.close(p2cwrite) 928if c2pread: 929 os.close(c2pread) 930if errread: 931 os.close(errread) 932 os.close(errpipe_read) 933 934# Dup fds for child 935if p2cread: 936 os.dup2(p2cread,0) 937if c2pwrite: 938 os.dup2(c2pwrite,1) 939if errwrite: 940 os.dup2(errwrite,2) 941 942# Close pipe fds. Make sure we doesn't close the same 943# fd more than once. 944if p2cread: 945 os.close(p2cread) 946if c2pwrite and c2pwrite not in(p2cread,): 947 os.close(c2pwrite) 948if errwrite and errwrite not in(p2cread, c2pwrite): 949 os.close(errwrite) 950 951# Close all other fds, if asked for 952if close_fds: 953 self._close_fds(but=errpipe_write) 954 955if cwd !=None: 956 os.chdir(cwd) 957 958if preexec_fn: 959apply(preexec_fn) 960 961if env ==None: 962 os.execvp(executable, args) 963else: 964 os.execvpe(executable, args, env) 965 966except: 967 exc_type, exc_value, tb = sys.exc_info() 968# Save the traceback and attach it to the exception object 969 exc_lines = traceback.format_exception(exc_type, 970 exc_value, 971 tb) 972 exc_value.child_traceback =''.join(exc_lines) 973 os.write(errpipe_write, pickle.dumps(exc_value)) 974 975# This exitcode won't be reported to applications, so it 976# really doesn't matter what we return. 977 os._exit(255) 978 979# Parent 980 os.close(errpipe_write) 981if p2cread and p2cwrite: 982 os.close(p2cread) 983if c2pwrite and c2pread: 984 os.close(c2pwrite) 985if errwrite and errread: 986 os.close(errwrite) 987 988# Wait for exec to fail or succeed; possibly raising exception 989 data = os.read(errpipe_read,1048576)# Exceptions limited to 1 MB 990 os.close(errpipe_read) 991if data !="": 992 os.waitpid(self.pid,0) 993 child_exception = pickle.loads(data) 994raise child_exception 995 996 997def_handle_exitstatus(self, sts): 998if os.WIFSIGNALED(sts): 999 self.returncode = -os.WTERMSIG(sts)1000elif os.WIFEXITED(sts):1001 self.returncode = os.WEXITSTATUS(sts)1002else:1003# Should never happen1004raiseRuntimeError("Unknown child exit status!")10051006 _active.remove(self)100710081009defpoll(self):1010"""Check if child process has terminated. Returns returncode1011 attribute."""1012if self.returncode ==None:1013try:1014 pid, sts = os.waitpid(self.pid, os.WNOHANG)1015if pid == self.pid:1016 self._handle_exitstatus(sts)1017except os.error:1018pass1019return self.returncode102010211022defwait(self):1023"""Wait for child process to terminate. Returns returncode1024 attribute."""1025if self.returncode ==None:1026 pid, sts = os.waitpid(self.pid,0)1027 self._handle_exitstatus(sts)1028return self.returncode102910301031defcommunicate(self,input=None):1032"""Interact with process: Send data to stdin. Read data from1033 stdout and stderr, until end-of-file is reached. Wait for1034 process to terminate. The optional input argument should be a1035 string to be sent to the child process, or None, if no data1036 should be sent to the child.10371038 communicate() returns a tuple (stdout, stderr)."""1039 read_set = []1040 write_set = []1041 stdout =None# Return1042 stderr =None# Return10431044if self.stdin:1045# Flush stdio buffer. This might block, if the user has1046# been writing to .stdin in an uncontrolled fashion.1047 self.stdin.flush()1048ifinput:1049 write_set.append(self.stdin)1050else:1051 self.stdin.close()1052if self.stdout:1053 read_set.append(self.stdout)1054 stdout = []1055if self.stderr:1056 read_set.append(self.stderr)1057 stderr = []10581059while read_set or write_set:1060 rlist, wlist, xlist = select.select(read_set, write_set, [])10611062if self.stdin in wlist:1063# When select has indicated that the file is writable,1064# we can write up to PIPE_BUF bytes without risk1065# blocking. POSIX defines PIPE_BUF >= 5121066 bytes_written = os.write(self.stdin.fileno(),input[:512])1067input=input[bytes_written:]1068if notinput:1069 self.stdin.close()1070 write_set.remove(self.stdin)10711072if self.stdout in rlist:1073 data = os.read(self.stdout.fileno(),1024)1074if data =="":1075 self.stdout.close()1076 read_set.remove(self.stdout)1077 stdout.append(data)10781079if self.stderr in rlist:1080 data = os.read(self.stderr.fileno(),1024)1081if data =="":1082 self.stderr.close()1083 read_set.remove(self.stderr)1084 stderr.append(data)10851086# All data exchanged. Translate lists into strings.1087if stdout !=None:1088 stdout =''.join(stdout)1089if stderr !=None:1090 stderr =''.join(stderr)10911092# Translate newlines, if requested. We cannot let the file1093# object do the translation: It is based on stdio, which is1094# impossible to combine with select (unless forcing no1095# buffering).1096if self.universal_newlines andhasattr(open,'newlines'):1097if stdout:1098 stdout = self._translate_newlines(stdout)1099if stderr:1100 stderr = self._translate_newlines(stderr)11011102 self.wait()1103return(stdout, stderr)110411051106def_demo_posix():1107#1108# Example 1: Simple redirection: Get process list1109#1110 plist =Popen(["ps"], stdout=PIPE).communicate()[0]1111print"Process list:"1112print plist11131114#1115# Example 2: Change uid before executing child1116#1117if os.getuid() ==0:1118 p =Popen(["id"], preexec_fn=lambda: os.setuid(100))1119 p.wait()11201121#1122# Example 3: Connecting several subprocesses1123#1124print"Looking for 'hda'..."1125 p1 =Popen(["dmesg"], stdout=PIPE)1126 p2 =Popen(["grep","hda"], stdin=p1.stdout, stdout=PIPE)1127printrepr(p2.communicate()[0])11281129#1130# Example 4: Catch execution error1131#1132print1133print"Trying a weird file..."1134try:1135printPopen(["/this/path/does/not/exist"]).communicate()1136exceptOSError, e:1137if e.errno == errno.ENOENT:1138print"The file didn't exist. I thought so..."1139print"Child traceback:"1140print e.child_traceback1141else:1142print"Error", e.errno1143else:1144print>>sys.stderr,"Gosh. No error."114511461147def_demo_windows():1148#1149# Example 1: Connecting several subprocesses1150#1151print"Looking for 'PROMPT' in set output..."1152 p1 =Popen("set", stdout=PIPE, shell=True)1153 p2 =Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)1154printrepr(p2.communicate()[0])11551156#1157# Example 2: Simple execution of program1158#1159print"Executing calc..."1160 p =Popen("calc")1161 p.wait()116211631164if __name__ =="__main__":1165if mswindows:1166_demo_windows()1167else:1168_demo_posix()