source: python/trunk/Lib/subprocess.py@ 603

Last change on this file since 603 was 603, checked in by dmik, 10 years ago

python: Use configured SHELL in subprocess module.

Use the shell that was configured when building python whe
supbropcess.Popen(shell=True) is requested instead of the
hardcoded '/bin/sh' value which might be not there.

Closes #141.

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