1
2
3
4
5
6
7
8
9
10
11
12 r"""subprocess - Subprocesses with accessible I/O streams
13
14 This module allows you to spawn processes, connect to their
15 input/output/error pipes, and obtain their return codes. This module
16 intends to replace several other, older modules and functions, like:
17
18 os.system
19 os.spawn*
20 os.popen*
21 popen2.*
22 commands.*
23
24 Information about how the subprocess module can be used to replace these
25 modules and functions can be found below.
26
27
28
29 Using the subprocess module
30 ===========================
31 This module defines one class called Popen:
32
33 class Popen(args, bufsize=0, executable=None,
34 stdin=None, stdout=None, stderr=None,
35 preexec_fn=None, close_fds=False, shell=False,
36 cwd=None, env=None, universal_newlines=False,
37 startupinfo=None, creationflags=0):
38
39
40 Arguments are:
41
42 args should be a string, or a sequence of program arguments. The
43 program to execute is normally the first item in the args sequence or
44 string, but can be explicitly set by using the executable argument.
45
46 On UNIX, with shell=False (default): In this case, the Popen class
47 uses os.execvp() to execute the child program. args should normally
48 be a sequence. A string will be treated as a sequence with the string
49 as the only item (the program to execute).
50
51 On UNIX, with shell=True: If args is a string, it specifies the
52 command string to execute through the shell. If args is a sequence,
53 the first item specifies the command string, and any additional items
54 will be treated as additional shell arguments.
55
56 On Windows: the Popen class uses CreateProcess() to execute the child
57 program, which operates on strings. If args is a sequence, it will be
58 converted to a string using the list2cmdline method. Please note that
59 not all MS Windows applications interpret the command line the same
60 way: The list2cmdline is designed for applications using the same
61 rules as the MS C runtime.
62
63 bufsize, if given, has the same meaning as the corresponding argument
64 to the built-in open() function: 0 means unbuffered, 1 means line
65 buffered, any other positive value means use a buffer of
66 (approximately) that size. A negative bufsize means to use the system
67 default, which usually means fully buffered. The default value for
68 bufsize is 0 (unbuffered).
69
70 stdin, stdout and stderr specify the executed programs' standard
71 input, standard output and standard error file handles, respectively.
72 Valid values are PIPE, an existing file descriptor (a positive
73 integer), an existing file object, and None. PIPE indicates that a
74 new pipe to the child should be created. With None, no redirection
75 will occur; the child's file handles will be inherited from the
76 parent. Additionally, stderr can be STDOUT, which indicates that the
77 stderr data from the applications should be captured into the same
78 file handle as for stdout.
79
80 If preexec_fn is set to a callable object, this object will be called
81 in the child process just before the child is executed.
82
83 If close_fds is true, all file descriptors except 0, 1 and 2 will be
84 closed before the child process is executed.
85
86 if shell is true, the specified command will be executed through the
87 shell.
88
89 If cwd is not None, the current directory will be changed to cwd
90 before the child is executed.
91
92 If env is not None, it defines the environment variables for the new
93 process.
94
95 If universal_newlines is true, the file objects stdout and stderr are
96 opened as a text files, but lines may be terminated by any of '\n',
97 the Unix end-of-line convention, '\r', the Macintosh convention or
98 '\r\n', the Windows convention. All of these external representations
99 are seen as '\n' by the Python program. Note: This feature is only
100 available if Python is built with universal newline support (the
101 default). Also, the newlines attribute of the file objects stdout,
102 stdin and stderr are not updated by the communicate() method.
103
104 The startupinfo and creationflags, if given, will be passed to the
105 underlying CreateProcess() function. They can specify things such as
106 appearance of the main window and priority for the new process.
107 (Windows only)
108
109
110 This module also defines two shortcut functions:
111
112 call(*popenargs, **kwargs):
113 Run command with arguments. Wait for command to complete, then
114 return the returncode attribute.
115
116 The arguments are the same as for the Popen constructor. Example:
117
118 retcode = call(["ls", "-l"])
119
120 check_call(*popenargs, **kwargs):
121 Run command with arguments. Wait for command to complete. If the
122 exit code was zero then return, otherwise raise
123 CalledProcessError. The CalledProcessError object will have the
124 return code in the returncode attribute.
125
126 The arguments are the same as for the Popen constructor. Example:
127
128 check_call(["ls", "-l"])
129
130 Exceptions
131 ----------
132 Exceptions raised in the child process, before the new program has
133 started to execute, will be re-raised in the parent. Additionally,
134 the exception object will have one extra attribute called
135 'child_traceback', which is a string containing traceback information
136 from the childs point of view.
137
138 The most common exception raised is OSError. This occurs, for
139 example, when trying to execute a non-existent file. Applications
140 should prepare for OSErrors.
141
142 A ValueError will be raised if Popen is called with invalid arguments.
143
144 check_call() will raise CalledProcessError, if the called process
145 returns a non-zero return code.
146
147
148 Security
149 --------
150 Unlike some other popen functions, this implementation will never call
151 /bin/sh implicitly. This means that all characters, including shell
152 metacharacters, can safely be passed to child processes.
153
154
155 Popen objects
156 =============
157 Instances of the Popen class have the following methods:
158
159 poll()
160 Check if child process has terminated. Returns returncode
161 attribute.
162
163 wait()
164 Wait for child process to terminate. Returns returncode attribute.
165
166 communicate(input=None)
167 Interact with process: Send data to stdin. Read data from stdout
168 and stderr, until end-of-file is reached. Wait for process to
169 terminate. The optional stdin argument should be a string to be
170 sent to the child process, or None, if no data should be sent to
171 the child.
172
173 communicate() returns a tuple (stdout, stderr).
174
175 Note: The data read is buffered in memory, so do not use this
176 method if the data size is large or unlimited.
177
178 The following attributes are also available:
179
180 stdin
181 If the stdin argument is PIPE, this attribute is a file object
182 that provides input to the child process. Otherwise, it is None.
183
184 stdout
185 If the stdout argument is PIPE, this attribute is a file object
186 that provides output from the child process. Otherwise, it is
187 None.
188
189 stderr
190 If the stderr argument is PIPE, this attribute is file object that
191 provides error output from the child process. Otherwise, it is
192 None.
193
194 pid
195 The process ID of the child process.
196
197 returncode
198 The child return code. A None value indicates that the process
199 hasn't terminated yet. A negative value -N indicates that the
200 child was terminated by signal N (UNIX only).
201
202
203 Replacing older functions with the subprocess module
204 ====================================================
205 In this section, "a ==> b" means that b can be used as a replacement
206 for a.
207
208 Note: All functions in this section fail (more or less) silently if
209 the executed program cannot be found; this module raises an OSError
210 exception.
211
212 In the following examples, we assume that the subprocess module is
213 imported with "from subprocess import *".
214
215
216 Replacing /bin/sh shell backquote
217 ---------------------------------
218 output=`mycmd myarg`
219 ==>
220 output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
221
222
223 Replacing shell pipe line
224 -------------------------
225 output=`dmesg | grep hda`
226 ==>
227 p1 = Popen(["dmesg"], stdout=PIPE)
228 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
229 output = p2.communicate()[0]
230
231
232 Replacing os.system()
233 ---------------------
234 sts = os.system("mycmd" + " myarg")
235 ==>
236 p = Popen("mycmd" + " myarg", shell=True)
237 pid, sts = os.waitpid(p.pid, 0)
238
239 Note:
240
241 * Calling the program through the shell is usually not required.
242
243 * It's easier to look at the returncode attribute than the
244 exitstatus.
245
246 A more real-world example would look like this:
247
248 try:
249 retcode = call("mycmd" + " myarg", shell=True)
250 if retcode < 0:
251 print >>sys.stderr, "Child was terminated by signal", -retcode
252 else:
253 print >>sys.stderr, "Child returned", retcode
254 except OSError, e:
255 print >>sys.stderr, "Execution failed:", e
256
257
258 Replacing os.spawn*
259 -------------------
260 P_NOWAIT example:
261
262 pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
263 ==>
264 pid = Popen(["/bin/mycmd", "myarg"]).pid
265
266
267 P_WAIT example:
268
269 retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
270 ==>
271 retcode = call(["/bin/mycmd", "myarg"])
272
273
274 Vector example:
275
276 os.spawnvp(os.P_NOWAIT, path, args)
277 ==>
278 Popen([path] + args[1:])
279
280
281 Environment example:
282
283 os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
284 ==>
285 Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
286
287
288 Replacing os.popen*
289 -------------------
290 pipe = os.popen(cmd, mode='r', bufsize)
291 ==>
292 pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout
293
294 pipe = os.popen(cmd, mode='w', bufsize)
295 ==>
296 pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
297
298
299 (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
300 ==>
301 p = Popen(cmd, shell=True, bufsize=bufsize,
302 stdin=PIPE, stdout=PIPE, close_fds=True)
303 (child_stdin, child_stdout) = (p.stdin, p.stdout)
304
305
306 (child_stdin,
307 child_stdout,
308 child_stderr) = os.popen3(cmd, mode, bufsize)
309 ==>
310 p = Popen(cmd, shell=True, bufsize=bufsize,
311 stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
312 (child_stdin,
313 child_stdout,
314 child_stderr) = (p.stdin, p.stdout, p.stderr)
315
316
317 (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
318 ==>
319 p = Popen(cmd, shell=True, bufsize=bufsize,
320 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
321 (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
322
323
324 Replacing popen2.*
325 ------------------
326 Note: If the cmd argument to popen2 functions is a string, the command
327 is executed through /bin/sh. If it is a list, the command is directly
328 executed.
329
330 (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
331 ==>
332 p = Popen(["somestring"], shell=True, bufsize=bufsize
333 stdin=PIPE, stdout=PIPE, close_fds=True)
334 (child_stdout, child_stdin) = (p.stdout, p.stdin)
335
336
337 (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
338 ==>
339 p = Popen(["mycmd", "myarg"], bufsize=bufsize,
340 stdin=PIPE, stdout=PIPE, close_fds=True)
341 (child_stdout, child_stdin) = (p.stdout, p.stdin)
342
343 The popen2.Popen3 and popen3.Popen4 basically works as subprocess.Popen,
344 except that:
345
346 * subprocess.Popen raises an exception if the execution fails
347 * the capturestderr argument is replaced with the stderr argument.
348 * stdin=PIPE and stdout=PIPE must be specified.
349 * popen2 closes all filedescriptors by default, but you have to specify
350 close_fds=True with subprocess.Popen.
351
352
353 """
354
355 import sys
356 mswindows = (sys.platform == "win32")
357
358 import os
359 import types
360 import traceback
361
362
364 """This exception is raised when a process run by check_call() returns
365 a non-zero exit status. The exit status will be stored in the
366 returncode attribute."""
368 self.returncode = returncode
369 self.cmd = cmd
371 return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
372
373
374 if mswindows:
375 try:
376 import threading
377 except ImportError:
378
379
380
381 pass
382 import msvcrt
383 try:
384
385 from _subprocess import *
387 dwFlags = 0
388 hStdInput = None
389 hStdOutput = None
390 hStdError = None
391 wShowWindow = 0
394 except ImportError:
395
396
397
398 import pywintypes
399 from win32api import GetStdHandle, STD_INPUT_HANDLE, \
400 STD_OUTPUT_HANDLE, STD_ERROR_HANDLE
401 from win32api import GetCurrentProcess, DuplicateHandle, \
402 GetModuleFileName, GetVersion
403 from win32con import DUPLICATE_SAME_ACCESS, SW_HIDE
404 from win32pipe import CreatePipe
405 from win32process import CreateProcess, STARTUPINFO, \
406 GetExitCodeProcess, STARTF_USESTDHANDLES, \
407 STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE
408 from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0
409
410
411 else:
412 import select
413 import errno
414 import fcntl
415 import pickle
416
417 try:
418 fcntl.F_GETFD
419 except AttributeError:
420 fcntl.F_GETFD = 1
421
422 try:
423 fcntl.F_SETFD
424 except AttributeError:
425 fcntl.F_SETFD = 2
426
427 __all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "CalledProcessError"]
428
429 try:
430 MAXFD = os.sysconf("SC_OPEN_MAX")
431 except KeyboardInterrupt:
432 raise
433 except:
434 MAXFD = 256
435
436 try:
437 isinstance(1, int)
438 except TypeError:
440 return isinstance(obj, type(1))
442 return type(obj) in (type(1), type(1L))
443 else:
445 return isinstance(obj, int)
447 return isinstance(obj, (int, long))
448
449 try:
450 types.StringTypes
451 except AttributeError:
452 try:
453 types.StringTypes = (str, unicode)
454 except NameError:
455 types.StringTypes = (str,)
458
459 _active = []
460
462 for inst in _active[:]:
463 if inst.poll(_deadstate=sys.maxsize) >= 0:
464 try:
465 _active.remove(inst)
466 except ValueError:
467
468
469 pass
470
471 PIPE = -1
472 STDOUT = -2
473
474
475 -def call(*popenargs, **kwargs):
476 """Run command with arguments. Wait for command to complete, then
477 return the returncode attribute.
478
479 The arguments are the same as for the Popen constructor. Example:
480
481 retcode = call(["ls", "-l"])
482 """
483 return apply(Popen, popenargs, kwargs).wait()
484
485
487 """Run command with arguments. Wait for command to complete. If
488 the exit code was zero then return, otherwise raise
489 CalledProcessError. The CalledProcessError object will have the
490 return code in the returncode attribute.
491
492 The arguments are the same as for the Popen constructor. Example:
493
494 check_call(["ls", "-l"])
495 """
496 retcode = call(*popenargs, **kwargs)
497 cmd = kwargs.get("args")
498 if cmd is None:
499 cmd = popenargs[0]
500 if retcode:
501 raise CalledProcessError(retcode, cmd)
502 return retcode
503
504
506 """
507 Translate a sequence of arguments into a command line
508 string, using the same rules as the MS C runtime:
509
510 1) Arguments are delimited by white space, which is either a
511 space or a tab.
512
513 2) A string surrounded by double quotation marks is
514 interpreted as a single argument, regardless of white space
515 contained within. A quoted string can be embedded in an
516 argument.
517
518 3) A double quotation mark preceded by a backslash is
519 interpreted as a literal double quotation mark.
520
521 4) Backslashes are interpreted literally, unless they
522 immediately precede a double quotation mark.
523
524 5) If backslashes immediately precede a double quotation mark,
525 every pair of backslashes is interpreted as a literal
526 backslash. If the number of backslashes is odd, the last
527 backslash escapes the next double quotation mark as
528 described in rule 3.
529 """
530
531
532
533 result = []
534 needquote = False
535 for arg in seq:
536 bs_buf = []
537
538
539 if result:
540 result.append(' ')
541
542 needquote = (" " in arg) or ("\t" in arg)
543 if needquote:
544 result.append('"')
545
546 for c in arg:
547 if c == '\\':
548
549 bs_buf.append(c)
550 elif c == '"':
551
552 result.append('\\' * len(bs_buf)*2)
553 bs_buf = []
554 result.append('\\"')
555 else:
556
557 if bs_buf:
558 result.extend(bs_buf)
559 bs_buf = []
560 result.append(c)
561
562
563 if bs_buf:
564 result.extend(bs_buf)
565
566 if needquote:
567 result.extend(bs_buf)
568 result.append('"')
569
570 return ''.join(result)
571
573 - def __init__(self, args, bufsize=0, executable=None,
574 stdin=None, stdout=None, stderr=None,
575 preexec_fn=None, close_fds=False, shell=False,
576 cwd=None, env=None, universal_newlines=False,
577 startupinfo=None, creationflags=0):
578 """Create new Popen instance."""
579 _cleanup()
580
581 self._child_created = False
582 if not is_int_or_long(bufsize):
583 raise TypeError("bufsize must be an integer")
584
585 if mswindows:
586 if preexec_fn is not None:
587 raise ValueError("preexec_fn is not supported on Windows "
588 "platforms")
589 if close_fds:
590 raise ValueError("close_fds is not supported on Windows "
591 "platforms")
592 else:
593
594 if startupinfo is not None:
595 raise ValueError("startupinfo is only supported on Windows "
596 "platforms")
597 if creationflags != 0:
598 raise ValueError("creationflags is only supported on Windows "
599 "platforms")
600
601 self.stdin = None
602 self.stdout = None
603 self.stderr = None
604 self.pid = None
605 self.returncode = None
606 self.universal_newlines = universal_newlines
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623 (p2cread, p2cwrite,
624 c2pread, c2pwrite,
625 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
626
627 self._execute_child(args, executable, preexec_fn, close_fds,
628 cwd, env, universal_newlines,
629 startupinfo, creationflags, shell,
630 p2cread, p2cwrite,
631 c2pread, c2pwrite,
632 errread, errwrite)
633
634 if p2cwrite:
635 self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
636 if c2pread:
637 if universal_newlines:
638 self.stdout = os.fdopen(c2pread, 'rU', bufsize)
639 else:
640 self.stdout = os.fdopen(c2pread, 'rb', bufsize)
641 if errread:
642 if universal_newlines:
643 self.stderr = os.fdopen(errread, 'rU', bufsize)
644 else:
645 self.stderr = os.fdopen(errread, 'rb', bufsize)
646
647
649 data = data.replace("\r\n", "\n")
650 data = data.replace("\r", "\n")
651 return data
652
653
655 if not self._child_created:
656
657 return
658
659 self.poll(_deadstate=sys.maxsize)
660 if self.returncode is None and _active is not None:
661
662 _active.append(self)
663
664
666 """Interact with process: Send data to stdin. Read data from
667 stdout and stderr, until end-of-file is reached. Wait for
668 process to terminate. The optional input argument should be a
669 string to be sent to the child process, or None, if no data
670 should be sent to the child.
671
672 communicate() returns a tuple (stdout, stderr)."""
673
674
675
676 if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
677 stdout = None
678 stderr = None
679 if self.stdin:
680 if input:
681 self.stdin.write(input)
682 self.stdin.close()
683 elif self.stdout:
684 stdout = self.stdout.read()
685 elif self.stderr:
686 stderr = self.stderr.read()
687 self.wait()
688 return (stdout, stderr)
689
690 return self._communicate(input)
691
692
693 if mswindows:
694
695
696
698 """Construct and return tupel with IO objects:
699 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
700 """
701 if stdin is None and stdout is None and stderr is None:
702 return (None, None, None, None, None, None)
703
704 p2cread, p2cwrite = None, None
705 c2pread, c2pwrite = None, None
706 errread, errwrite = None, None
707
708 if stdin is None:
709 p2cread = GetStdHandle(STD_INPUT_HANDLE)
710 elif stdin == PIPE:
711 p2cread, p2cwrite = CreatePipe(None, 0)
712
713 p2cwrite = p2cwrite.Detach()
714 p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0)
715 elif is_int(stdin):
716 p2cread = msvcrt.get_osfhandle(stdin)
717 else:
718
719 p2cread = msvcrt.get_osfhandle(stdin.fileno())
720 p2cread = self._make_inheritable(p2cread)
721
722 if stdout is None:
723 c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
724 elif stdout == PIPE:
725 c2pread, c2pwrite = CreatePipe(None, 0)
726
727 c2pread = c2pread.Detach()
728 c2pread = msvcrt.open_osfhandle(c2pread, 0)
729 elif is_int(stdout):
730 c2pwrite = msvcrt.get_osfhandle(stdout)
731 else:
732
733 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
734 c2pwrite = self._make_inheritable(c2pwrite)
735
736 if stderr is None:
737 errwrite = GetStdHandle(STD_ERROR_HANDLE)
738 elif stderr == PIPE:
739 errread, errwrite = CreatePipe(None, 0)
740
741 errread = errread.Detach()
742 errread = msvcrt.open_osfhandle(errread, 0)
743 elif stderr == STDOUT:
744 errwrite = c2pwrite
745 elif is_int(stderr):
746 errwrite = msvcrt.get_osfhandle(stderr)
747 else:
748
749 errwrite = msvcrt.get_osfhandle(stderr.fileno())
750 errwrite = self._make_inheritable(errwrite)
751
752 return (p2cread, p2cwrite,
753 c2pread, c2pwrite,
754 errread, errwrite)
755
756
758 """Return a duplicate of handle, which is inheritable"""
759 return DuplicateHandle(GetCurrentProcess(), handle,
760 GetCurrentProcess(), 0, 1,
761 DUPLICATE_SAME_ACCESS)
762
763
765 """Find and return absolut path to w9xpopen.exe"""
766 w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)),
767 "w9xpopen.exe")
768 if not os.path.exists(w9xpopen):
769
770
771 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
772 "w9xpopen.exe")
773 if not os.path.exists(w9xpopen):
774 raise RuntimeError("Cannot locate w9xpopen.exe, which is "
775 "needed for Popen to work with your "
776 "shell or platform.")
777 return w9xpopen
778
779
780 - def _execute_child(self, args, executable, preexec_fn, close_fds,
781 cwd, env, universal_newlines,
782 startupinfo, creationflags, shell,
783 p2cread, p2cwrite,
784 c2pread, c2pwrite,
785 errread, errwrite):
786 """Execute program (MS Windows version)"""
787
788 if not isinstance(args, types.StringTypes):
789 args = list2cmdline(args)
790
791
792 if startupinfo is None:
793 startupinfo = STARTUPINFO()
794 if None not in (p2cread, c2pwrite, errwrite):
795 startupinfo.dwFlags = startupinfo.dwFlags | STARTF_USESTDHANDLES
796 startupinfo.hStdInput = p2cread
797 startupinfo.hStdOutput = c2pwrite
798 startupinfo.hStdError = errwrite
799
800 if shell:
801 startupinfo.dwFlags = startupinfo.dwFlags | STARTF_USESHOWWINDOW
802 startupinfo.wShowWindow = SW_HIDE
803 comspec = os.environ.get("COMSPEC", "cmd.exe")
804 args = comspec + " /c " + args
805 if (GetVersion() >= 0x80000000L or
806 os.path.basename(comspec).lower() == "command.com"):
807
808
809
810
811 w9xpopen = self._find_w9xpopen()
812 args = '"%s" %s' % (w9xpopen, args)
813
814
815
816
817
818
819 creationflags = creationflags | CREATE_NEW_CONSOLE
820
821
822 try:
823 hp, ht, pid, tid = CreateProcess(executable, args,
824
825 None, None,
826
827
828 1,
829 creationflags,
830 env,
831 cwd,
832 startupinfo)
833 except pywintypes.error, e:
834
835
836
837
838 raise WindowsError(*e.args)
839
840
841 self._child_created = True
842 self._handle = hp
843 self.pid = pid
844 ht.Close()
845
846
847
848
849
850
851
852 if p2cread is not None:
853 p2cread.Close()
854 if c2pwrite is not None:
855 c2pwrite.Close()
856 if errwrite is not None:
857 errwrite.Close()
858
859
860 - def poll(self, _deadstate=None):
861 """Check if child process has terminated. Returns returncode
862 attribute."""
863 if self.returncode is None:
864 if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
865 self.returncode = GetExitCodeProcess(self._handle)
866 return self.returncode
867
868
870 """Wait for child process to terminate. Returns returncode
871 attribute."""
872 if self.returncode is None:
873 obj = WaitForSingleObject(self._handle, INFINITE)
874 self.returncode = GetExitCodeProcess(self._handle)
875 return self.returncode
876
877
880
881
883 stdout = None
884 stderr = None
885
886 if self.stdout:
887 stdout = []
888 stdout_thread = threading.Thread(target=self._readerthread,
889 args=(self.stdout, stdout))
890 stdout_thread.setDaemon(True)
891 stdout_thread.start()
892 if self.stderr:
893 stderr = []
894 stderr_thread = threading.Thread(target=self._readerthread,
895 args=(self.stderr, stderr))
896 stderr_thread.setDaemon(True)
897 stderr_thread.start()
898
899 if self.stdin:
900 if input is not None:
901 self.stdin.write(input)
902 self.stdin.close()
903
904 if self.stdout:
905 stdout_thread.join()
906 if self.stderr:
907 stderr_thread.join()
908
909
910 if stdout is not None:
911 stdout = stdout[0]
912 if stderr is not None:
913 stderr = stderr[0]
914
915
916
917
918
919 if self.universal_newlines and hasattr(file, 'newlines'):
920 if stdout:
921 stdout = self._translate_newlines(stdout)
922 if stderr:
923 stderr = self._translate_newlines(stderr)
924
925 self.wait()
926 return (stdout, stderr)
927
928 else:
929
930
931
933 """Construct and return tupel with IO objects:
934 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
935 """
936 p2cread, p2cwrite = None, None
937 c2pread, c2pwrite = None, None
938 errread, errwrite = None, None
939
940 if stdin is None:
941 pass
942 elif stdin == PIPE:
943 p2cread, p2cwrite = os.pipe()
944 elif is_int(stdin):
945 p2cread = stdin
946 else:
947
948 p2cread = stdin.fileno()
949
950 if stdout is None:
951 pass
952 elif stdout == PIPE:
953 c2pread, c2pwrite = os.pipe()
954 elif is_int(stdout):
955 c2pwrite = stdout
956 else:
957
958 c2pwrite = stdout.fileno()
959
960 if stderr is None:
961 pass
962 elif stderr == PIPE:
963 errread, errwrite = os.pipe()
964 elif stderr == STDOUT:
965 errwrite = c2pwrite
966 elif is_int(stderr):
967 errwrite = stderr
968 else:
969
970 errwrite = stderr.fileno()
971
972 return (p2cread, p2cwrite,
973 c2pread, c2pwrite,
974 errread, errwrite)
975
976
978 try:
979 cloexec_flag = fcntl.FD_CLOEXEC
980 except AttributeError:
981 cloexec_flag = 1
982
983 old = fcntl.fcntl(fd, fcntl.F_GETFD)
984 fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
985
986
988 for i in range(3, MAXFD):
989 if i == but:
990 continue
991 try:
992 os.close(i)
993 except KeyboardInterrupt:
994 raise
995 except:
996 pass
997
998
999 - def _execute_child(self, args, executable, preexec_fn, close_fds,
1000 cwd, env, universal_newlines,
1001 startupinfo, creationflags, shell,
1002 p2cread, p2cwrite,
1003 c2pread, c2pwrite,
1004 errread, errwrite):
1005 """Execute program (POSIX version)"""
1006
1007 if is_string(args):
1008 args = [args]
1009
1010 if shell:
1011 args = ["/bin/sh", "-c"] + args
1012
1013 if executable is None:
1014 executable = args[0]
1015
1016
1017
1018
1019 errpipe_read, errpipe_write = os.pipe()
1020 self._set_cloexec_flag(errpipe_write)
1021
1022 self.pid = os.fork()
1023 self._child_created = True
1024 if self.pid == 0:
1025
1026 try:
1027
1028 if p2cwrite:
1029 os.close(p2cwrite)
1030 if c2pread:
1031 os.close(c2pread)
1032 if errread:
1033 os.close(errread)
1034 os.close(errpipe_read)
1035
1036
1037 if p2cread:
1038 os.dup2(p2cread, 0)
1039 if c2pwrite:
1040 os.dup2(c2pwrite, 1)
1041 if errwrite:
1042 os.dup2(errwrite, 2)
1043
1044
1045
1046 try:
1047 set
1048 except NameError:
1049
1050
1051 if p2cread:
1052 os.close(p2cread)
1053 if c2pwrite and c2pwrite not in (p2cread,):
1054 os.close(c2pwrite)
1055 if errwrite and errwrite not in (p2cread, c2pwrite):
1056 os.close(errwrite)
1057 else:
1058 for fd in set((p2cread, c2pwrite, errwrite))-set((0,1,2)):
1059 if fd: os.close(fd)
1060
1061
1062 if close_fds:
1063 self._close_fds(but=errpipe_write)
1064
1065 if cwd is not None:
1066 os.chdir(cwd)
1067
1068 if preexec_fn:
1069 apply(preexec_fn)
1070
1071 if env is None:
1072 os.execvp(executable, args)
1073 else:
1074 os.execvpe(executable, args, env)
1075
1076 except KeyboardInterrupt:
1077 raise
1078
1079 except:
1080 exc_type, exc_value, tb = sys.exc_info()
1081
1082 exc_lines = traceback.format_exception(exc_type,
1083 exc_value,
1084 tb)
1085 exc_value.child_traceback = ''.join(exc_lines)
1086 os.write(errpipe_write, pickle.dumps(exc_value))
1087
1088
1089
1090 os._exit(255)
1091
1092
1093 os.close(errpipe_write)
1094 if p2cread and p2cwrite:
1095 os.close(p2cread)
1096 if c2pwrite and c2pread:
1097 os.close(c2pwrite)
1098 if errwrite and errread:
1099 os.close(errwrite)
1100
1101
1102 data = os.read(errpipe_read, 1048576)
1103 os.close(errpipe_read)
1104 if data != "":
1105 os.waitpid(self.pid, 0)
1106 child_exception = pickle.loads(data)
1107 raise child_exception
1108
1109
1111 if os.WIFSIGNALED(sts):
1112 self.returncode = -os.WTERMSIG(sts)
1113 elif os.WIFEXITED(sts):
1114 self.returncode = os.WEXITSTATUS(sts)
1115 else:
1116
1117 raise RuntimeError("Unknown child exit status!")
1118
1119
1120 - def poll(self, _deadstate=None):
1121 """Check if child process has terminated. Returns returncode
1122 attribute."""
1123 if self.returncode is None:
1124 try:
1125 pid, sts = os.waitpid(self.pid, os.WNOHANG)
1126 if pid == self.pid:
1127 self._handle_exitstatus(sts)
1128 except os.error:
1129 if _deadstate is not None:
1130 self.returncode = _deadstate
1131 return self.returncode
1132
1133
1135 """Wait for child process to terminate. Returns returncode
1136 attribute."""
1137 if self.returncode is None:
1138 pid, sts = os.waitpid(self.pid, 0)
1139 self._handle_exitstatus(sts)
1140 return self.returncode
1141
1142
1144 read_set = []
1145 write_set = []
1146 stdout = None
1147 stderr = None
1148
1149 if self.stdin:
1150
1151
1152 self.stdin.flush()
1153 if input:
1154 write_set.append(self.stdin)
1155 else:
1156 self.stdin.close()
1157 if self.stdout:
1158 read_set.append(self.stdout)
1159 stdout = []
1160 if self.stderr:
1161 read_set.append(self.stderr)
1162 stderr = []
1163
1164 input_offset = 0
1165 while read_set or write_set:
1166 rlist, wlist, xlist = select.select(read_set, write_set, [])
1167
1168 if self.stdin in wlist:
1169
1170
1171
1172 m = memoryview(input)[input_offset:input_offset+512]
1173 bytes_written = os.write(self.stdin.fileno(), m)
1174 input_offset = input_offset + bytes_written
1175 if input_offset >= len(input):
1176 self.stdin.close()
1177 write_set.remove(self.stdin)
1178
1179 if self.stdout in rlist:
1180 data = os.read(self.stdout.fileno(), 1024)
1181 if data == "":
1182 self.stdout.close()
1183 read_set.remove(self.stdout)
1184 stdout.append(data)
1185
1186 if self.stderr in rlist:
1187 data = os.read(self.stderr.fileno(), 1024)
1188 if data == "":
1189 self.stderr.close()
1190 read_set.remove(self.stderr)
1191 stderr.append(data)
1192
1193
1194 if stdout is not None:
1195 stdout = ''.join(stdout)
1196 if stderr is not None:
1197 stderr = ''.join(stderr)
1198
1199
1200
1201
1202
1203 if self.universal_newlines and hasattr(file, 'newlines'):
1204 if stdout:
1205 stdout = self._translate_newlines(stdout)
1206 if stderr:
1207 stderr = self._translate_newlines(stderr)
1208
1209 self.wait()
1210 return (stdout, stderr)
1211
1212
1214
1215
1216
1217 plist = Popen(["ps"], stdout=PIPE).communicate()[0]
1218 print "Process list:"
1219 print plist
1220
1221
1222
1223
1224 if os.getuid() == 0:
1225 p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1226 p.wait()
1227
1228
1229
1230
1231 print "Looking for 'hda'..."
1232 p1 = Popen(["dmesg"], stdout=PIPE)
1233 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
1234 print repr(p2.communicate()[0])
1235
1236
1237
1238
1239 print
1240 print "Trying a weird file..."
1241 try:
1242 print Popen(["/this/path/does/not/exist"]).communicate()
1243 except OSError, e:
1244 if e.errno == errno.ENOENT:
1245 print "The file didn't exist. I thought so..."
1246 print "Child traceback:"
1247 print e.child_traceback
1248 else:
1249 print "Error", e.errno
1250 else:
1251 sys.stderr.write( "Gosh. No error.\n" )
1252
1253
1255
1256
1257
1258 print "Looking for 'PROMPT' in set output..."
1259 p1 = Popen("set", stdout=PIPE, shell=True)
1260 p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
1261 print repr(p2.communicate()[0])
1262
1263
1264
1265
1266 print "Executing calc..."
1267 p = Popen("calc")
1268 p.wait()
1269
1270
1271 if __name__ == "__main__":
1272 if mswindows:
1273 _demo_windows()
1274 else:
1275 _demo_posix()
1276
1277
1278
1279
1280
1281
1282