blob: 4e7b0644a6bd21f5107d279e97162648954ba6d1 [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001# subprocess - Subprocesses with accessible I/O streams
2#
Tim Peterse718f612004-10-12 21:51:32 +00003# For more information about this module, see PEP 324.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00004#
Peter Astrand3a708df2005-09-23 17:37:29 +00005# Copyright (c) 2003-2005 by Peter Astrand <astrand@lysator.liu.se>
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00006#
Peter Astrand69bf13f2005-02-14 08:56:32 +00007# Licensed to PSF under a Contributor Agreement.
Peter Astrand3a708df2005-09-23 17:37:29 +00008# See http://www.python.org/2.4/license for licensing details.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00009
Raymond Hettinger837dd932004-10-17 16:36:53 +000010r"""subprocess - Subprocesses with accessible I/O streams
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000011
Fredrik Lundh15aaacc2004-10-17 14:47:05 +000012This module allows you to spawn processes, connect to their
13input/output/error pipes, and obtain their return codes. This module
Benjamin Peterson944996f2014-03-12 21:41:35 -050014intends to replace several older modules and functions:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000015
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
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000108This module also defines some shortcut functions:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000109
Peter Astrand5f5e1412004-12-05 20:15:36 +0000110call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000111 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
Peter Astrand454f7672005-01-01 09:36:35 +0000118check_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
Peter Astrand7d1d4362006-07-14 14:04:45 +0000122 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000123
124 The arguments are the same as for the Popen constructor. Example:
125
126 check_call(["ls", "-l"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000127
Gregory P. Smith26576802008-12-05 02:27:01 +0000128check_output(*popenargs, **kwargs):
Georg Brandl6ab5d082009-12-20 14:33:20 +0000129 Run command with arguments and return its output as a byte string.
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000130
Georg Brandl6ab5d082009-12-20 14:33:20 +0000131 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.
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000134
Georg Brandl6ab5d082009-12-20 14:33:20 +0000135 The arguments are the same as for the Popen constructor. Example:
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000136
Georg Brandl02e7dfd2009-12-28 08:09:32 +0000137 output = check_output(["ls", "-l", "/dev/null"])
138
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000139
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000140Exceptions
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
Ezio Melottif5469cf2013-08-17 15:43:51 +0300146from the child's point of view.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000147
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
Gregory P. Smith26576802008-12-05 02:27:01 +0000154check_call() and check_output() will raise CalledProcessError, if the
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000155called process returns a non-zero return code.
Peter Astrand454f7672005-01-01 09:36:35 +0000156
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000157
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
Neal Norwitza186ee22006-12-29 03:01:53 +0000179 terminate. The optional input argument should be a string to be
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000180 sent to the child process, or None, if no data should be sent to
181 the child.
Tim Peterse718f612004-10-12 21:51:32 +0000182
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000183 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)
Peter Astrand6fdf3cb2004-11-30 18:06:42 +0000238p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000239output = p2.communicate()[0]
240
241
242Replacing os.system()
243---------------------
244sts = os.system("mycmd" + " myarg")
245==>
246p = Popen("mycmd" + " myarg", shell=True)
Neal Norwitz84404832006-07-10 00:05:34 +0000247pid, sts = os.waitpid(p.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000248
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-------------------
Tim Peterse718f612004-10-12 21:51:32 +0000270P_NOWAIT example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000271
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
Tim Peterse718f612004-10-12 21:51:32 +0000284Vector example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000285
286os.spawnvp(os.P_NOWAIT, path, args)
287==>
288Popen([path] + args[1:])
289
290
Tim Peterse718f612004-10-12 21:51:32 +0000291Environment example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000292
293os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
294==>
295Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
296
297
Tim Peterse718f612004-10-12 21:51:32 +0000298Replacing os.popen*
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000299-------------------
Philip Jenvey8b902042009-09-29 19:10:15 +0000300pipe = os.popen("cmd", mode='r', bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000301==>
Philip Jenvey8b902042009-09-29 19:10:15 +0000302pipe = Popen("cmd", shell=True, bufsize=bufsize, stdout=PIPE).stdout
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000303
Philip Jenvey8b902042009-09-29 19:10:15 +0000304pipe = os.popen("cmd", mode='w', bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000305==>
Philip Jenvey8b902042009-09-29 19:10:15 +0000306pipe = Popen("cmd", shell=True, bufsize=bufsize, stdin=PIPE).stdin
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000307
308
Philip Jenvey8b902042009-09-29 19:10:15 +0000309(child_stdin, child_stdout) = os.popen2("cmd", mode, bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000310==>
Philip Jenvey8b902042009-09-29 19:10:15 +0000311p = Popen("cmd", shell=True, bufsize=bufsize,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000312 stdin=PIPE, stdout=PIPE, close_fds=True)
313(child_stdin, child_stdout) = (p.stdin, p.stdout)
314
315
316(child_stdin,
317 child_stdout,
Philip Jenvey8b902042009-09-29 19:10:15 +0000318 child_stderr) = os.popen3("cmd", mode, bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000319==>
Philip Jenvey8b902042009-09-29 19:10:15 +0000320p = Popen("cmd", shell=True, bufsize=bufsize,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000321 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
Philip Jenvey8b902042009-09-29 19:10:15 +0000327(child_stdin, child_stdout_and_stderr) = os.popen4("cmd", mode,
328 bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000329==>
Philip Jenvey8b902042009-09-29 19:10:15 +0000330p = Popen("cmd", shell=True, bufsize=bufsize,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000331 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
332(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
333
Philip Jenvey8b902042009-09-29 19:10:15 +0000334On 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()
Florent Xiclunacf741ce2010-03-08 10:58:12 +0000350if rc is not None and rc % 256:
Philip Jenvey8b902042009-09-29 19:10:15 +0000351 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
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000359
360Replacing popen2.*
361------------------
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000362(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
Philip Jenvey8b902042009-09-29 19:10:15 +0000368On 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:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000371
Philip Jenvey8b902042009-09-29 19:10:15 +0000372(child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize,
373 mode)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000374==>
375p = Popen(["mycmd", "myarg"], bufsize=bufsize,
376 stdin=PIPE, stdout=PIPE, close_fds=True)
377(child_stdout, child_stdin) = (p.stdout, p.stdin)
378
Neal Norwitzaa87fb62007-05-11 06:23:01 +0000379The popen2.Popen3 and popen2.Popen4 basically works as subprocess.Popen,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000380except 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
Tim Peterse718f612004-10-12 21:51:32 +0000386 close_fds=True with subprocess.Popen.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000387"""
388
389import sys
390mswindows = (sys.platform == "win32")
391
392import os
Peter Astrandc26516b2005-02-21 08:13:02 +0000393import types
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000394import traceback
Gregory P. Smith87d49792008-01-19 20:57:59 +0000395import gc
Christian Heimese74c8f22008-04-19 02:23:57 +0000396import signal
Ross Lagerwall104c3f12011-04-05 15:24:34 +0200397import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000398
Peter Astrand454f7672005-01-01 09:36:35 +0000399# Exception classes used by this module.
Peter Astrand7d1d4362006-07-14 14:04:45 +0000400class CalledProcessError(Exception):
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000401 """This exception is raised when a process run by check_call() or
Gregory P. Smith26576802008-12-05 02:27:01 +0000402 check_output() returns a non-zero exit status.
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000403 The exit status will be stored in the returncode attribute;
Gregory P. Smith26576802008-12-05 02:27:01 +0000404 check_output() will also store the output in the output attribute.
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000405 """
406 def __init__(self, returncode, cmd, output=None):
Peter Astrand7d1d4362006-07-14 14:04:45 +0000407 self.returncode = returncode
408 self.cmd = cmd
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000409 self.output = output
Peter Astrand7d1d4362006-07-14 14:04:45 +0000410 def __str__(self):
411 return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
Tim Peters73a9ead2006-07-18 21:55:15 +0000412
Peter Astrand454f7672005-01-01 09:36:35 +0000413
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000414if mswindows:
415 import threading
416 import msvcrt
Brian Curtina2936cf2010-04-24 15:40:11 +0000417 import _subprocess
418 class STARTUPINFO:
419 dwFlags = 0
420 hStdInput = None
421 hStdOutput = None
422 hStdError = None
423 wShowWindow = 0
424 class pywintypes:
425 error = IOError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000426else:
427 import select
Gregory P. Smithdd7ca242009-07-04 01:49:29 +0000428 _has_poll = hasattr(select, 'poll')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000429 import fcntl
430 import pickle
431
Amaury Forgeot d'Arcce32eb72009-07-09 22:37:22 +0000432 # When select or poll has indicated that the file is writable,
433 # we can write up to _PIPE_BUF bytes without risk of blocking.
434 # POSIX defines PIPE_BUF as >= 512.
435 _PIPE_BUF = getattr(select, 'PIPE_BUF', 512)
436
437
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000438__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call",
Gregory P. Smith26576802008-12-05 02:27:01 +0000439 "check_output", "CalledProcessError"]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000440
Brian Curtina2936cf2010-04-24 15:40:11 +0000441if mswindows:
Brian Curtin77b75912011-04-29 16:21:51 -0500442 from _subprocess import (CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP,
443 STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
444 STD_ERROR_HANDLE, SW_HIDE,
445 STARTF_USESTDHANDLES, STARTF_USESHOWWINDOW)
Brian Curtin20de4582011-04-29 16:28:52 -0500446
Brian Curtin77b75912011-04-29 16:21:51 -0500447 __all__.extend(["CREATE_NEW_CONSOLE", "CREATE_NEW_PROCESS_GROUP",
448 "STD_INPUT_HANDLE", "STD_OUTPUT_HANDLE",
449 "STD_ERROR_HANDLE", "SW_HIDE",
450 "STARTF_USESTDHANDLES", "STARTF_USESHOWWINDOW"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000451try:
452 MAXFD = os.sysconf("SC_OPEN_MAX")
453except:
454 MAXFD = 256
455
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000456_active = []
457
458def _cleanup():
459 for inst in _active[:]:
Georg Brandl02e7dfd2009-12-28 08:09:32 +0000460 res = inst._internal_poll(_deadstate=sys.maxint)
Charles-François Natalib02302c2011-08-18 17:18:28 +0200461 if res is not None:
Martin v. Löwis17de8ff2006-04-10 15:55:37 +0000462 try:
463 _active.remove(inst)
464 except ValueError:
465 # This can happen if two threads create a new Popen instance.
466 # It's harmless that it was already removed, so ignore.
467 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000468
469PIPE = -1
470STDOUT = -2
471
472
Gregory P. Smithcce211f2010-03-01 00:05:08 +0000473def _eintr_retry_call(func, *args):
474 while True:
475 try:
476 return func(*args)
Victor Stinnere7901312011-07-05 14:08:01 +0200477 except (OSError, IOError) as e:
Gregory P. Smithcce211f2010-03-01 00:05:08 +0000478 if e.errno == errno.EINTR:
479 continue
480 raise
481
482
Kristján Valur Jónsson8927e8f2013-03-19 15:07:35 -0700483# XXX This function is only used by multiprocessing and the test suite,
484# but it's here so that it can be imported when Python is compiled without
485# threads.
486
487def _args_from_interpreter_flags():
488 """Return a list of command-line arguments reproducing the current
489 settings in sys.flags and sys.warnoptions."""
490 flag_opt_map = {
491 'debug': 'd',
492 # 'inspect': 'i',
493 # 'interactive': 'i',
494 'optimize': 'O',
495 'dont_write_bytecode': 'B',
496 'no_user_site': 's',
497 'no_site': 'S',
498 'ignore_environment': 'E',
499 'verbose': 'v',
500 'bytes_warning': 'b',
Kristján Valur Jónsson8927e8f2013-03-19 15:07:35 -0700501 'py3k_warning': '3',
502 }
503 args = []
504 for flag, opt in flag_opt_map.items():
505 v = getattr(sys.flags, flag)
506 if v > 0:
507 args.append('-' + opt * v)
Gregory P. Smith64fa45a2015-12-13 13:57:50 -0800508 if getattr(sys.flags, 'hash_randomization') != 0:
509 args.append('-R')
Kristján Valur Jónsson8927e8f2013-03-19 15:07:35 -0700510 for opt in sys.warnoptions:
511 args.append('-W' + opt)
512 return args
513
514
Peter Astrand5f5e1412004-12-05 20:15:36 +0000515def call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000516 """Run command with arguments. Wait for command to complete, then
517 return the returncode attribute.
518
519 The arguments are the same as for the Popen constructor. Example:
520
521 retcode = call(["ls", "-l"])
522 """
Peter Astrand5f5e1412004-12-05 20:15:36 +0000523 return Popen(*popenargs, **kwargs).wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000524
525
Peter Astrand454f7672005-01-01 09:36:35 +0000526def check_call(*popenargs, **kwargs):
527 """Run command with arguments. Wait for command to complete. If
528 the exit code was zero then return, otherwise raise
529 CalledProcessError. The CalledProcessError object will have the
Peter Astrand7d1d4362006-07-14 14:04:45 +0000530 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000531
532 The arguments are the same as for the Popen constructor. Example:
533
534 check_call(["ls", "-l"])
535 """
536 retcode = call(*popenargs, **kwargs)
Peter Astrand454f7672005-01-01 09:36:35 +0000537 if retcode:
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000538 cmd = kwargs.get("args")
539 if cmd is None:
540 cmd = popenargs[0]
Peter Astrand7d1d4362006-07-14 14:04:45 +0000541 raise CalledProcessError(retcode, cmd)
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000542 return 0
543
544
Gregory P. Smith26576802008-12-05 02:27:01 +0000545def check_output(*popenargs, **kwargs):
Georg Brandl6ab5d082009-12-20 14:33:20 +0000546 r"""Run command with arguments and return its output as a byte string.
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000547
548 If the exit code was non-zero it raises a CalledProcessError. The
549 CalledProcessError object will have the return code in the returncode
550 attribute and output in the output attribute.
551
552 The arguments are the same as for the Popen constructor. Example:
553
Gregory P. Smith26576802008-12-05 02:27:01 +0000554 >>> check_output(["ls", "-l", "/dev/null"])
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000555 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
556
557 The stdout argument is not allowed as it is used internally.
Georg Brandl02e7dfd2009-12-28 08:09:32 +0000558 To capture standard error in the result, use stderr=STDOUT.
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000559
Gregory P. Smith26576802008-12-05 02:27:01 +0000560 >>> check_output(["/bin/sh", "-c",
Georg Brandl6ab5d082009-12-20 14:33:20 +0000561 ... "ls -l non_existent_file ; exit 0"],
Georg Brandl02e7dfd2009-12-28 08:09:32 +0000562 ... stderr=STDOUT)
Mark Dickinson3e4caeb2009-02-21 20:27:01 +0000563 'ls: non_existent_file: No such file or directory\n'
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000564 """
565 if 'stdout' in kwargs:
566 raise ValueError('stdout argument not allowed, it will be overridden.')
Amaury Forgeot d'Arc5fe420e2009-06-18 22:32:50 +0000567 process = Popen(stdout=PIPE, *popenargs, **kwargs)
Gregory P. Smith97f49f42008-12-04 20:21:09 +0000568 output, unused_err = process.communicate()
569 retcode = process.poll()
570 if retcode:
571 cmd = kwargs.get("args")
572 if cmd is None:
573 cmd = popenargs[0]
574 raise CalledProcessError(retcode, cmd, output=output)
575 return output
Peter Astrand454f7672005-01-01 09:36:35 +0000576
577
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000578def list2cmdline(seq):
579 """
580 Translate a sequence of arguments into a command line
581 string, using the same rules as the MS C runtime:
582
583 1) Arguments are delimited by white space, which is either a
584 space or a tab.
585
586 2) A string surrounded by double quotation marks is
587 interpreted as a single argument, regardless of white space
Jean-Paul Calderoneb33f0c12010-06-18 20:00:17 +0000588 contained within. A quoted string can be embedded in an
589 argument.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000590
591 3) A double quotation mark preceded by a backslash is
592 interpreted as a literal double quotation mark.
593
594 4) Backslashes are interpreted literally, unless they
595 immediately precede a double quotation mark.
596
597 5) If backslashes immediately precede a double quotation mark,
598 every pair of backslashes is interpreted as a literal
599 backslash. If the number of backslashes is odd, the last
600 backslash escapes the next double quotation mark as
601 described in rule 3.
602 """
603
604 # See
Eric Smithd19915e2009-11-09 15:16:23 +0000605 # http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
606 # or search http://msdn.microsoft.com for
607 # "Parsing C++ Command-Line Arguments"
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000608 result = []
609 needquote = False
610 for arg in seq:
611 bs_buf = []
612
613 # Add a space to separate this argument from the others
614 if result:
615 result.append(' ')
616
Jean-Paul Calderoneb33f0c12010-06-18 20:00:17 +0000617 needquote = (" " in arg) or ("\t" in arg) or not arg
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000618 if needquote:
619 result.append('"')
620
621 for c in arg:
622 if c == '\\':
Tim Peterse718f612004-10-12 21:51:32 +0000623 # Don't know if we need to double yet.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000624 bs_buf.append(c)
625 elif c == '"':
Gregory P. Smithe047e6d2008-01-19 20:49:02 +0000626 # Double backslashes.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000627 result.append('\\' * len(bs_buf)*2)
628 bs_buf = []
629 result.append('\\"')
630 else:
631 # Normal char
632 if bs_buf:
633 result.extend(bs_buf)
634 bs_buf = []
635 result.append(c)
636
Gregory P. Smithe047e6d2008-01-19 20:49:02 +0000637 # Add remaining backslashes, if any.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000638 if bs_buf:
639 result.extend(bs_buf)
640
641 if needquote:
Peter Astrand7e78ade2005-03-03 21:10:23 +0000642 result.extend(bs_buf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000643 result.append('"')
644
645 return ''.join(result)
646
647
648class Popen(object):
Serhiy Storchaka30615852014-02-10 19:19:53 +0200649 _child_created = False # Set here since __del__ checks it
650
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000651 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
Peter Astrand738131d2004-11-30 21:04:45 +0000659 if not isinstance(bufsize, (int, long)):
660 raise TypeError("bufsize must be an integer")
661
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000662 if mswindows:
Tim Peterse8374a52004-10-13 03:15:00 +0000663 if preexec_fn is not None:
664 raise ValueError("preexec_fn is not supported on Windows "
665 "platforms")
Peter Astrand81a191b2007-05-26 22:18:20 +0000666 if close_fds and (stdin is not None or stdout is not None or
667 stderr is not None):
Tim Peterse8374a52004-10-13 03:15:00 +0000668 raise ValueError("close_fds is not supported on Windows "
Peter Astrand81a191b2007-05-26 22:18:20 +0000669 "platforms if you redirect stdin/stdout/stderr")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000670 else:
671 # POSIX
Tim Peterse8374a52004-10-13 03:15:00 +0000672 if startupinfo is not None:
673 raise ValueError("startupinfo is only supported on Windows "
674 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000675 if creationflags != 0:
Tim Peterse8374a52004-10-13 03:15:00 +0000676 raise ValueError("creationflags is only supported on Windows "
677 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000678
Tim Peterse718f612004-10-12 21:51:32 +0000679 self.stdin = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000680 self.stdout = None
681 self.stderr = None
682 self.pid = None
683 self.returncode = None
684 self.universal_newlines = universal_newlines
685
686 # Input and output objects. The general principle is like
687 # this:
688 #
689 # Parent Child
690 # ------ -----
691 # p2cwrite ---stdin---> p2cread
692 # c2pread <--stdout--- c2pwrite
693 # errread <--stderr--- errwrite
694 #
695 # On POSIX, the child objects are file descriptors. On
696 # Windows, these are Windows file handles. The parent objects
697 # are file descriptors on both platforms. The parent objects
698 # are None when not using PIPEs. The child objects are None
699 # when not redirecting.
Tim Peterse718f612004-10-12 21:51:32 +0000700
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000701 (p2cread, p2cwrite,
702 c2pread, c2pwrite,
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200703 errread, errwrite), to_close = self._get_handles(stdin, stdout, stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000704
Gregory P. Smith9d3b6e92012-11-10 22:49:03 -0800705 try:
706 self._execute_child(args, executable, preexec_fn, close_fds,
707 cwd, env, universal_newlines,
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200708 startupinfo, creationflags, shell, to_close,
Gregory P. Smith9d3b6e92012-11-10 22:49:03 -0800709 p2cread, p2cwrite,
710 c2pread, c2pwrite,
711 errread, errwrite)
712 except Exception:
713 # Preserve original exception in case os.close raises.
714 exc_type, exc_value, exc_trace = sys.exc_info()
715
Gregory P. Smith9d3b6e92012-11-10 22:49:03 -0800716 for fd in to_close:
717 try:
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200718 if mswindows:
719 fd.Close()
720 else:
721 os.close(fd)
Gregory P. Smith9d3b6e92012-11-10 22:49:03 -0800722 except EnvironmentError:
723 pass
724
725 raise exc_type, exc_value, exc_trace
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000726
Peter Astrand5f9c6ae2007-02-06 15:37:50 +0000727 if mswindows:
Hirokazu Yamamotoeacbbdf2009-03-03 22:18:14 +0000728 if p2cwrite is not None:
729 p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
730 if c2pread is not None:
731 c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
732 if errread is not None:
733 errread = msvcrt.open_osfhandle(errread.Detach(), 0)
Peter Astrand5f9c6ae2007-02-06 15:37:50 +0000734
Peter Astrandf5400032007-02-02 19:06:36 +0000735 if p2cwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000736 self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
Peter Astrandf5400032007-02-02 19:06:36 +0000737 if c2pread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000738 if universal_newlines:
739 self.stdout = os.fdopen(c2pread, 'rU', bufsize)
740 else:
741 self.stdout = os.fdopen(c2pread, 'rb', bufsize)
Peter Astrandf5400032007-02-02 19:06:36 +0000742 if errread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000743 if universal_newlines:
744 self.stderr = os.fdopen(errread, 'rU', bufsize)
745 else:
746 self.stderr = os.fdopen(errread, 'rb', bufsize)
Tim Peterse718f612004-10-12 21:51:32 +0000747
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000748
749 def _translate_newlines(self, data):
750 data = data.replace("\r\n", "\n")
751 data = data.replace("\r", "\n")
752 return data
753
Martin v. Löwis17de8ff2006-04-10 15:55:37 +0000754
Serhiy Storchaka30615852014-02-10 19:19:53 +0200755 def __del__(self, _maxint=sys.maxint):
Victor Stinner776e69b2011-06-01 01:03:00 +0200756 # If __init__ hasn't had a chance to execute (e.g. if it
757 # was passed an undeclared keyword argument), we don't
758 # have a _child_created attribute at all.
Serhiy Storchaka30615852014-02-10 19:19:53 +0200759 if not self._child_created:
Martin v. Löwis17de8ff2006-04-10 15:55:37 +0000760 # We didn't get to successfully create a child process.
761 return
762 # In case the child hasn't been waited on, check if it's done.
Brett Cannon42a0ba72010-05-14 00:21:48 +0000763 self._internal_poll(_deadstate=_maxint)
Georg Brandl13cf38c2006-07-20 16:28:39 +0000764 if self.returncode is None and _active is not None:
Martin v. Löwis17de8ff2006-04-10 15:55:37 +0000765 # Child is still running, keep us alive until we can wait on it.
766 _active.append(self)
767
768
Peter Astrand23109f02005-03-03 20:28:59 +0000769 def communicate(self, input=None):
770 """Interact with process: Send data to stdin. Read data from
771 stdout and stderr, until end-of-file is reached. Wait for
772 process to terminate. The optional input argument should be a
773 string to be sent to the child process, or None, if no data
774 should be sent to the child.
Tim Peterseba28be2005-03-28 01:08:02 +0000775
Peter Astrand23109f02005-03-03 20:28:59 +0000776 communicate() returns a tuple (stdout, stderr)."""
777
778 # Optimization: If we are only using one pipe, or no pipe at
779 # all, using select() or threads is unnecessary.
780 if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
Tim Peterseba28be2005-03-28 01:08:02 +0000781 stdout = None
782 stderr = None
Peter Astrand23109f02005-03-03 20:28:59 +0000783 if self.stdin:
784 if input:
Ross Lagerwall104c3f12011-04-05 15:24:34 +0200785 try:
786 self.stdin.write(input)
787 except IOError as e:
788 if e.errno != errno.EPIPE and e.errno != errno.EINVAL:
789 raise
Peter Astrand23109f02005-03-03 20:28:59 +0000790 self.stdin.close()
791 elif self.stdout:
Victor Stinnere7901312011-07-05 14:08:01 +0200792 stdout = _eintr_retry_call(self.stdout.read)
Gregory P. Smith4036fd42008-05-26 20:22:14 +0000793 self.stdout.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000794 elif self.stderr:
Victor Stinnere7901312011-07-05 14:08:01 +0200795 stderr = _eintr_retry_call(self.stderr.read)
Gregory P. Smith4036fd42008-05-26 20:22:14 +0000796 self.stderr.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000797 self.wait()
798 return (stdout, stderr)
Tim Peterseba28be2005-03-28 01:08:02 +0000799
Peter Astrand23109f02005-03-03 20:28:59 +0000800 return self._communicate(input)
801
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000802
Gregory P. Smitha36f8fe2008-08-04 00:13:29 +0000803 def poll(self):
804 return self._internal_poll()
805
806
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000807 if mswindows:
808 #
809 # Windows methods
810 #
811 def _get_handles(self, stdin, stdout, stderr):
Amaury Forgeot d'Arc8318afa2009-07-10 16:47:42 +0000812 """Construct and return tuple with IO objects:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000813 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
814 """
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200815 to_close = set()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000816 if stdin is None and stdout is None and stderr is None:
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200817 return (None, None, None, None, None, None), to_close
Tim Peterse718f612004-10-12 21:51:32 +0000818
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000819 p2cread, p2cwrite = None, None
820 c2pread, c2pwrite = None, None
821 errread, errwrite = None, None
822
Peter Astrandd38ddf42005-02-10 08:32:50 +0000823 if stdin is None:
Brian Curtina2936cf2010-04-24 15:40:11 +0000824 p2cread = _subprocess.GetStdHandle(_subprocess.STD_INPUT_HANDLE)
Hirokazu Yamamotoeacbbdf2009-03-03 22:18:14 +0000825 if p2cread is None:
Brian Curtina2936cf2010-04-24 15:40:11 +0000826 p2cread, _ = _subprocess.CreatePipe(None, 0)
Hirokazu Yamamotoeacbbdf2009-03-03 22:18:14 +0000827 elif stdin == PIPE:
Brian Curtina2936cf2010-04-24 15:40:11 +0000828 p2cread, p2cwrite = _subprocess.CreatePipe(None, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000829 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000830 p2cread = msvcrt.get_osfhandle(stdin)
831 else:
832 # Assuming file-like object
833 p2cread = msvcrt.get_osfhandle(stdin.fileno())
834 p2cread = self._make_inheritable(p2cread)
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200835 # We just duplicated the handle, it has to be closed at the end
836 to_close.add(p2cread)
837 if stdin == PIPE:
838 to_close.add(p2cwrite)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000839
Peter Astrandd38ddf42005-02-10 08:32:50 +0000840 if stdout is None:
Brian Curtina2936cf2010-04-24 15:40:11 +0000841 c2pwrite = _subprocess.GetStdHandle(_subprocess.STD_OUTPUT_HANDLE)
Hirokazu Yamamotoeacbbdf2009-03-03 22:18:14 +0000842 if c2pwrite is None:
Brian Curtina2936cf2010-04-24 15:40:11 +0000843 _, c2pwrite = _subprocess.CreatePipe(None, 0)
Hirokazu Yamamotoeacbbdf2009-03-03 22:18:14 +0000844 elif stdout == PIPE:
Brian Curtina2936cf2010-04-24 15:40:11 +0000845 c2pread, c2pwrite = _subprocess.CreatePipe(None, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000846 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000847 c2pwrite = msvcrt.get_osfhandle(stdout)
848 else:
849 # Assuming file-like object
850 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
851 c2pwrite = self._make_inheritable(c2pwrite)
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200852 # We just duplicated the handle, it has to be closed at the end
853 to_close.add(c2pwrite)
854 if stdout == PIPE:
855 to_close.add(c2pread)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000856
Peter Astrandd38ddf42005-02-10 08:32:50 +0000857 if stderr is None:
Brian Curtina2936cf2010-04-24 15:40:11 +0000858 errwrite = _subprocess.GetStdHandle(_subprocess.STD_ERROR_HANDLE)
Hirokazu Yamamotoeacbbdf2009-03-03 22:18:14 +0000859 if errwrite is None:
Brian Curtina2936cf2010-04-24 15:40:11 +0000860 _, errwrite = _subprocess.CreatePipe(None, 0)
Hirokazu Yamamotoeacbbdf2009-03-03 22:18:14 +0000861 elif stderr == PIPE:
Brian Curtina2936cf2010-04-24 15:40:11 +0000862 errread, errwrite = _subprocess.CreatePipe(None, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000863 elif stderr == STDOUT:
864 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000865 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000866 errwrite = msvcrt.get_osfhandle(stderr)
867 else:
868 # Assuming file-like object
869 errwrite = msvcrt.get_osfhandle(stderr.fileno())
870 errwrite = self._make_inheritable(errwrite)
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200871 # We just duplicated the handle, it has to be closed at the end
872 to_close.add(errwrite)
873 if stderr == PIPE:
874 to_close.add(errread)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000875
876 return (p2cread, p2cwrite,
877 c2pread, c2pwrite,
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200878 errread, errwrite), to_close
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000879
880
881 def _make_inheritable(self, handle):
882 """Return a duplicate of handle, which is inheritable"""
Brian Curtina2936cf2010-04-24 15:40:11 +0000883 return _subprocess.DuplicateHandle(_subprocess.GetCurrentProcess(),
884 handle, _subprocess.GetCurrentProcess(), 0, 1,
885 _subprocess.DUPLICATE_SAME_ACCESS)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000886
887
888 def _find_w9xpopen(self):
889 """Find and return absolut path to w9xpopen.exe"""
Brian Curtina2936cf2010-04-24 15:40:11 +0000890 w9xpopen = os.path.join(
891 os.path.dirname(_subprocess.GetModuleFileName(0)),
Tim Peterse8374a52004-10-13 03:15:00 +0000892 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000893 if not os.path.exists(w9xpopen):
894 # Eeek - file-not-found - possibly an embedding
895 # situation - see if we can locate it in sys.exec_prefix
Tim Peterse8374a52004-10-13 03:15:00 +0000896 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
897 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000898 if not os.path.exists(w9xpopen):
Tim Peterse8374a52004-10-13 03:15:00 +0000899 raise RuntimeError("Cannot locate w9xpopen.exe, which is "
900 "needed for Popen to work with your "
901 "shell or platform.")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000902 return w9xpopen
903
Tim Peterse718f612004-10-12 21:51:32 +0000904
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000905 def _execute_child(self, args, executable, preexec_fn, close_fds,
906 cwd, env, universal_newlines,
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200907 startupinfo, creationflags, shell, to_close,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000908 p2cread, p2cwrite,
909 c2pread, c2pwrite,
910 errread, errwrite):
911 """Execute program (MS Windows version)"""
912
Peter Astrandc26516b2005-02-21 08:13:02 +0000913 if not isinstance(args, types.StringTypes):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000914 args = list2cmdline(args)
915
Peter Astrandc1d65362004-11-07 14:30:34 +0000916 # Process startup details
Peter Astrandd38ddf42005-02-10 08:32:50 +0000917 if startupinfo is None:
Georg Brandlad624892006-06-04 22:15:37 +0000918 startupinfo = STARTUPINFO()
919 if None not in (p2cread, c2pwrite, errwrite):
Brian Curtina2936cf2010-04-24 15:40:11 +0000920 startupinfo.dwFlags |= _subprocess.STARTF_USESTDHANDLES
Peter Astrandc1d65362004-11-07 14:30:34 +0000921 startupinfo.hStdInput = p2cread
922 startupinfo.hStdOutput = c2pwrite
923 startupinfo.hStdError = errwrite
924
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000925 if shell:
Brian Curtina2936cf2010-04-24 15:40:11 +0000926 startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW
927 startupinfo.wShowWindow = _subprocess.SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000928 comspec = os.environ.get("COMSPEC", "cmd.exe")
Tim Golden8e4756c2010-08-12 11:00:35 +0000929 args = '{} /c "{}"'.format (comspec, args)
930 if (_subprocess.GetVersion() >= 0x80000000 or
Tim Peterse8374a52004-10-13 03:15:00 +0000931 os.path.basename(comspec).lower() == "command.com"):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000932 # Win9x, or using command.com on NT. We need to
933 # use the w9xpopen intermediate program. For more
934 # information, see KB Q150956
935 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
936 w9xpopen = self._find_w9xpopen()
937 args = '"%s" %s' % (w9xpopen, args)
938 # Not passing CREATE_NEW_CONSOLE has been known to
939 # cause random failures on win9x. Specifically a
940 # dialog: "Your program accessed mem currently in
941 # use at xxx" and a hopeful warning about the
942 # stability of your system. Cost is Ctrl+C wont
943 # kill children.
Brian Curtina2936cf2010-04-24 15:40:11 +0000944 creationflags |= _subprocess.CREATE_NEW_CONSOLE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000945
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200946 def _close_in_parent(fd):
947 fd.Close()
948 to_close.remove(fd)
949
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000950 # Start the process
951 try:
Brian Curtina2936cf2010-04-24 15:40:11 +0000952 hp, ht, pid, tid = _subprocess.CreateProcess(executable, args,
Tim Peterse8374a52004-10-13 03:15:00 +0000953 # no special security
954 None, None,
Peter Astrand81a191b2007-05-26 22:18:20 +0000955 int(not close_fds),
Tim Peterse8374a52004-10-13 03:15:00 +0000956 creationflags,
957 env,
958 cwd,
959 startupinfo)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000960 except pywintypes.error, e:
961 # Translate pywintypes.error to WindowsError, which is
962 # a subclass of OSError. FIXME: We should really
Ezio Melottic2077b02011-03-16 12:34:31 +0200963 # translate errno using _sys_errlist (or similar), but
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000964 # how can this be done from Python?
965 raise WindowsError(*e.args)
Tim Golden431774f2010-08-08 11:17:56 +0000966 finally:
967 # Child is launched. Close the parent's copy of those pipe
968 # handles that only the child should have open. You need
969 # to make sure that no handles to the write end of the
970 # output pipe are maintained in this process or else the
971 # pipe will not close when the child process exits and the
972 # ReadFile will hang.
973 if p2cread is not None:
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200974 _close_in_parent(p2cread)
Tim Golden431774f2010-08-08 11:17:56 +0000975 if c2pwrite is not None:
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200976 _close_in_parent(c2pwrite)
Tim Golden431774f2010-08-08 11:17:56 +0000977 if errwrite is not None:
Antoine Pitrou33fc7442013-08-30 23:38:13 +0200978 _close_in_parent(errwrite)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000979
980 # Retain the process handle, but close the thread handle
Martin v. Löwis17de8ff2006-04-10 15:55:37 +0000981 self._child_created = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000982 self._handle = hp
983 self.pid = pid
984 ht.Close()
985
Brett Cannon42a0ba72010-05-14 00:21:48 +0000986 def _internal_poll(self, _deadstate=None,
Victor Stinner2b271f72010-05-14 21:52:26 +0000987 _WaitForSingleObject=_subprocess.WaitForSingleObject,
988 _WAIT_OBJECT_0=_subprocess.WAIT_OBJECT_0,
989 _GetExitCodeProcess=_subprocess.GetExitCodeProcess):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000990 """Check if child process has terminated. Returns returncode
Brett Cannon42a0ba72010-05-14 00:21:48 +0000991 attribute.
992
993 This method is called by __del__, so it can only refer to objects
994 in its local scope.
995
996 """
Peter Astrandd38ddf42005-02-10 08:32:50 +0000997 if self.returncode is None:
Brett Cannon42a0ba72010-05-14 00:21:48 +0000998 if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
999 self.returncode = _GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001000 return self.returncode
1001
1002
1003 def wait(self):
1004 """Wait for child process to terminate. Returns returncode
1005 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001006 if self.returncode is None:
Brian Curtina2936cf2010-04-24 15:40:11 +00001007 _subprocess.WaitForSingleObject(self._handle,
1008 _subprocess.INFINITE)
1009 self.returncode = _subprocess.GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001010 return self.returncode
1011
1012
1013 def _readerthread(self, fh, buffer):
1014 buffer.append(fh.read())
1015
1016
Peter Astrand23109f02005-03-03 20:28:59 +00001017 def _communicate(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001018 stdout = None # Return
1019 stderr = None # Return
1020
1021 if self.stdout:
1022 stdout = []
Tim Peterse8374a52004-10-13 03:15:00 +00001023 stdout_thread = threading.Thread(target=self._readerthread,
1024 args=(self.stdout, stdout))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001025 stdout_thread.setDaemon(True)
1026 stdout_thread.start()
1027 if self.stderr:
1028 stderr = []
Tim Peterse8374a52004-10-13 03:15:00 +00001029 stderr_thread = threading.Thread(target=self._readerthread,
1030 args=(self.stderr, stderr))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001031 stderr_thread.setDaemon(True)
1032 stderr_thread.start()
1033
1034 if self.stdin:
Peter Astrandd38ddf42005-02-10 08:32:50 +00001035 if input is not None:
Ross Lagerwall104c3f12011-04-05 15:24:34 +02001036 try:
1037 self.stdin.write(input)
1038 except IOError as e:
Victor Stinnerc3828072014-07-29 00:04:54 +02001039 if e.errno == errno.EPIPE:
1040 # communicate() should ignore broken pipe error
1041 pass
1042 elif (e.errno == errno.EINVAL
1043 and self.poll() is not None):
1044 # Issue #19612: stdin.write() fails with EINVAL
1045 # if the process already exited before the write
1046 pass
1047 else:
Ross Lagerwall104c3f12011-04-05 15:24:34 +02001048 raise
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001049 self.stdin.close()
1050
1051 if self.stdout:
1052 stdout_thread.join()
1053 if self.stderr:
1054 stderr_thread.join()
1055
1056 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +00001057 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001058 stdout = stdout[0]
Peter Astrandd38ddf42005-02-10 08:32:50 +00001059 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001060 stderr = stderr[0]
1061
1062 # Translate newlines, if requested. We cannot let the file
1063 # object do the translation: It is based on stdio, which is
1064 # impossible to combine with select (unless forcing no
1065 # buffering).
Neal Norwitza6d01ce2006-05-02 06:23:22 +00001066 if self.universal_newlines and hasattr(file, 'newlines'):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001067 if stdout:
1068 stdout = self._translate_newlines(stdout)
1069 if stderr:
1070 stderr = self._translate_newlines(stderr)
1071
1072 self.wait()
1073 return (stdout, stderr)
1074
Christian Heimese74c8f22008-04-19 02:23:57 +00001075 def send_signal(self, sig):
1076 """Send a signal to the process
1077 """
1078 if sig == signal.SIGTERM:
1079 self.terminate()
Brian Curtine5aa8862010-04-02 23:26:06 +00001080 elif sig == signal.CTRL_C_EVENT:
1081 os.kill(self.pid, signal.CTRL_C_EVENT)
1082 elif sig == signal.CTRL_BREAK_EVENT:
1083 os.kill(self.pid, signal.CTRL_BREAK_EVENT)
Christian Heimese74c8f22008-04-19 02:23:57 +00001084 else:
Brian Curtine80513c2010-09-07 13:27:20 +00001085 raise ValueError("Unsupported signal: {}".format(sig))
Christian Heimese74c8f22008-04-19 02:23:57 +00001086
1087 def terminate(self):
1088 """Terminates the process
1089 """
Antoine Pitrouf60845b2012-03-11 19:29:12 +01001090 try:
1091 _subprocess.TerminateProcess(self._handle, 1)
1092 except OSError as e:
1093 # ERROR_ACCESS_DENIED (winerror 5) is received when the
1094 # process already died.
1095 if e.winerror != 5:
1096 raise
1097 rc = _subprocess.GetExitCodeProcess(self._handle)
1098 if rc == _subprocess.STILL_ACTIVE:
1099 raise
1100 self.returncode = rc
Christian Heimese74c8f22008-04-19 02:23:57 +00001101
1102 kill = terminate
1103
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001104 else:
1105 #
1106 # POSIX methods
1107 #
1108 def _get_handles(self, stdin, stdout, stderr):
Amaury Forgeot d'Arc8318afa2009-07-10 16:47:42 +00001109 """Construct and return tuple with IO objects:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001110 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
1111 """
Antoine Pitrou33fc7442013-08-30 23:38:13 +02001112 to_close = set()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001113 p2cread, p2cwrite = None, None
1114 c2pread, c2pwrite = None, None
1115 errread, errwrite = None, None
1116
Peter Astrandd38ddf42005-02-10 08:32:50 +00001117 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001118 pass
1119 elif stdin == PIPE:
Charles-François Natali2a34eb32011-08-25 21:20:54 +02001120 p2cread, p2cwrite = self.pipe_cloexec()
Antoine Pitrou33fc7442013-08-30 23:38:13 +02001121 to_close.update((p2cread, p2cwrite))
Peter Astrandd38ddf42005-02-10 08:32:50 +00001122 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001123 p2cread = stdin
1124 else:
1125 # Assuming file-like object
1126 p2cread = stdin.fileno()
1127
Peter Astrandd38ddf42005-02-10 08:32:50 +00001128 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001129 pass
1130 elif stdout == PIPE:
Charles-François Natali2a34eb32011-08-25 21:20:54 +02001131 c2pread, c2pwrite = self.pipe_cloexec()
Antoine Pitrou33fc7442013-08-30 23:38:13 +02001132 to_close.update((c2pread, c2pwrite))
Peter Astrandd38ddf42005-02-10 08:32:50 +00001133 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001134 c2pwrite = stdout
1135 else:
1136 # Assuming file-like object
Tim Peterse718f612004-10-12 21:51:32 +00001137 c2pwrite = stdout.fileno()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001138
Peter Astrandd38ddf42005-02-10 08:32:50 +00001139 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001140 pass
1141 elif stderr == PIPE:
Charles-François Natali2a34eb32011-08-25 21:20:54 +02001142 errread, errwrite = self.pipe_cloexec()
Antoine Pitrou33fc7442013-08-30 23:38:13 +02001143 to_close.update((errread, errwrite))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001144 elif stderr == STDOUT:
1145 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +00001146 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001147 errwrite = stderr
1148 else:
1149 # Assuming file-like object
1150 errwrite = stderr.fileno()
1151
1152 return (p2cread, p2cwrite,
1153 c2pread, c2pwrite,
Antoine Pitrou33fc7442013-08-30 23:38:13 +02001154 errread, errwrite), to_close
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001155
1156
Antoine Pitrou91ce0d92011-01-03 18:45:09 +00001157 def _set_cloexec_flag(self, fd, cloexec=True):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001158 try:
1159 cloexec_flag = fcntl.FD_CLOEXEC
1160 except AttributeError:
1161 cloexec_flag = 1
1162
1163 old = fcntl.fcntl(fd, fcntl.F_GETFD)
Antoine Pitrou91ce0d92011-01-03 18:45:09 +00001164 if cloexec:
1165 fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
1166 else:
1167 fcntl.fcntl(fd, fcntl.F_SETFD, old & ~cloexec_flag)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001168
1169
Charles-François Natali2a34eb32011-08-25 21:20:54 +02001170 def pipe_cloexec(self):
1171 """Create a pipe with FDs set CLOEXEC."""
1172 # Pipes' FDs are set CLOEXEC by default because we don't want them
1173 # to be inherited by other subprocesses: the CLOEXEC flag is removed
1174 # from the child's FDs by _dup2(), between fork() and exec().
1175 # This is not atomic: we would need the pipe2() syscall for that.
1176 r, w = os.pipe()
1177 self._set_cloexec_flag(r)
1178 self._set_cloexec_flag(w)
1179 return r, w
1180
1181
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001182 def _close_fds(self, but):
Amaury Forgeot d'Arc5fe420e2009-06-18 22:32:50 +00001183 if hasattr(os, 'closerange'):
1184 os.closerange(3, but)
1185 os.closerange(but + 1, MAXFD)
1186 else:
1187 for i in xrange(3, MAXFD):
1188 if i == but:
1189 continue
1190 try:
1191 os.close(i)
1192 except:
1193 pass
Tim Peterse718f612004-10-12 21:51:32 +00001194
1195
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001196 def _execute_child(self, args, executable, preexec_fn, close_fds,
1197 cwd, env, universal_newlines,
Antoine Pitrou33fc7442013-08-30 23:38:13 +02001198 startupinfo, creationflags, shell, to_close,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001199 p2cread, p2cwrite,
1200 c2pread, c2pwrite,
1201 errread, errwrite):
1202 """Execute program (POSIX version)"""
1203
Peter Astrandc26516b2005-02-21 08:13:02 +00001204 if isinstance(args, types.StringTypes):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001205 args = [args]
Georg Brandl6c0e1e82006-10-29 09:05:04 +00001206 else:
1207 args = list(args)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001208
1209 if shell:
1210 args = ["/bin/sh", "-c"] + args
Stefan Krahe9a6a7d2010-07-19 14:41:08 +00001211 if executable:
1212 args[0] = executable
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001213
Peter Astrandd38ddf42005-02-10 08:32:50 +00001214 if executable is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001215 executable = args[0]
1216
Antoine Pitrou33fc7442013-08-30 23:38:13 +02001217 def _close_in_parent(fd):
1218 os.close(fd)
1219 to_close.remove(fd)
1220
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001221 # For transferring possible exec failure from child to parent
1222 # The first char specifies the exception type: 0 means
1223 # OSError, 1 means some other error.
Charles-François Natali2a34eb32011-08-25 21:20:54 +02001224 errpipe_read, errpipe_write = self.pipe_cloexec()
Gregory P. Smith87d49792008-01-19 20:57:59 +00001225 try:
Gregory P. Smith92ffc632008-01-19 22:23:56 +00001226 try:
Facundo Batista8c826b72009-06-19 18:02:28 +00001227 gc_was_enabled = gc.isenabled()
1228 # Disable gc to avoid bug where gc -> file_dealloc ->
1229 # write to stderr -> hang. http://bugs.python.org/issue1336
1230 gc.disable()
1231 try:
1232 self.pid = os.fork()
Georg Brandl3e8b8692009-07-16 21:47:51 +00001233 except:
Facundo Batista8c826b72009-06-19 18:02:28 +00001234 if gc_was_enabled:
1235 gc.enable()
Georg Brandl3e8b8692009-07-16 21:47:51 +00001236 raise
Facundo Batista8c826b72009-06-19 18:02:28 +00001237 self._child_created = True
1238 if self.pid == 0:
1239 # Child
1240 try:
1241 # Close parent's pipe ends
1242 if p2cwrite is not None:
1243 os.close(p2cwrite)
1244 if c2pread is not None:
1245 os.close(c2pread)
1246 if errread is not None:
1247 os.close(errread)
1248 os.close(errpipe_read)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001249
Ross Lagerwalld8e39012011-07-27 18:54:53 +02001250 # When duping fds, if there arises a situation
1251 # where one of the fds is either 0, 1 or 2, it
1252 # is possible that it is overwritten (#12607).
1253 if c2pwrite == 0:
1254 c2pwrite = os.dup(c2pwrite)
1255 if errwrite == 0 or errwrite == 1:
1256 errwrite = os.dup(errwrite)
1257
Facundo Batista8c826b72009-06-19 18:02:28 +00001258 # Dup fds for child
Antoine Pitrou91ce0d92011-01-03 18:45:09 +00001259 def _dup2(a, b):
1260 # dup2() removes the CLOEXEC flag but
1261 # we must do it ourselves if dup2()
1262 # would be a no-op (issue #10806).
1263 if a == b:
1264 self._set_cloexec_flag(a, False)
1265 elif a is not None:
1266 os.dup2(a, b)
1267 _dup2(p2cread, 0)
1268 _dup2(c2pwrite, 1)
1269 _dup2(errwrite, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001270
Antoine Pitrou91ce0d92011-01-03 18:45:09 +00001271 # Close pipe fds. Make sure we don't close the
1272 # same fd more than once, or standard fds.
1273 closed = { None }
1274 for fd in [p2cread, c2pwrite, errwrite]:
1275 if fd not in closed and fd > 2:
1276 os.close(fd)
1277 closed.add(fd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001278
Facundo Batista8c826b72009-06-19 18:02:28 +00001279 if cwd is not None:
1280 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001281
Facundo Batista8c826b72009-06-19 18:02:28 +00001282 if preexec_fn:
1283 preexec_fn()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001284
Charles-François Natali4c533142013-08-25 18:22:49 +02001285 # Close all other fds, if asked for - after
1286 # preexec_fn(), which may open FDs.
1287 if close_fds:
1288 self._close_fds(but=errpipe_write)
1289
Facundo Batista8c826b72009-06-19 18:02:28 +00001290 if env is None:
1291 os.execvp(executable, args)
1292 else:
1293 os.execvpe(executable, args, env)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001294
Facundo Batista8c826b72009-06-19 18:02:28 +00001295 except:
1296 exc_type, exc_value, tb = sys.exc_info()
1297 # Save the traceback and attach it to the exception object
1298 exc_lines = traceback.format_exception(exc_type,
1299 exc_value,
1300 tb)
1301 exc_value.child_traceback = ''.join(exc_lines)
1302 os.write(errpipe_write, pickle.dumps(exc_value))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001303
Facundo Batista8c826b72009-06-19 18:02:28 +00001304 # This exitcode won't be reported to applications, so it
1305 # really doesn't matter what we return.
1306 os._exit(255)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001307
Facundo Batista8c826b72009-06-19 18:02:28 +00001308 # Parent
1309 if gc_was_enabled:
1310 gc.enable()
1311 finally:
1312 # be sure the FD is closed no matter what
1313 os.close(errpipe_write)
1314
Facundo Batista8c826b72009-06-19 18:02:28 +00001315 # Wait for exec to fail or succeed; possibly raising exception
Gregory P. Smithcce211f2010-03-01 00:05:08 +00001316 # Exception limited to 1M
1317 data = _eintr_retry_call(os.read, errpipe_read, 1048576)
Facundo Batista8c826b72009-06-19 18:02:28 +00001318 finally:
Antoine Pitrou33fc7442013-08-30 23:38:13 +02001319 if p2cread is not None and p2cwrite is not None:
1320 _close_in_parent(p2cread)
1321 if c2pwrite is not None and c2pread is not None:
1322 _close_in_parent(c2pwrite)
1323 if errwrite is not None and errread is not None:
1324 _close_in_parent(errwrite)
1325
Facundo Batista8c826b72009-06-19 18:02:28 +00001326 # be sure the FD is closed no matter what
1327 os.close(errpipe_read)
1328
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001329 if data != "":
Gregory P. Smith312efbc2010-12-14 15:02:53 +00001330 try:
1331 _eintr_retry_call(os.waitpid, self.pid, 0)
1332 except OSError as e:
1333 if e.errno != errno.ECHILD:
1334 raise
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001335 child_exception = pickle.loads(data)
1336 raise child_exception
1337
1338
Brett Cannon42a0ba72010-05-14 00:21:48 +00001339 def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED,
1340 _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED,
1341 _WEXITSTATUS=os.WEXITSTATUS):
1342 # This method is called (indirectly) by __del__, so it cannot
Serhiy Storchaka30615852014-02-10 19:19:53 +02001343 # refer to anything outside of its local scope.
Brett Cannon42a0ba72010-05-14 00:21:48 +00001344 if _WIFSIGNALED(sts):
1345 self.returncode = -_WTERMSIG(sts)
1346 elif _WIFEXITED(sts):
1347 self.returncode = _WEXITSTATUS(sts)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001348 else:
1349 # Should never happen
1350 raise RuntimeError("Unknown child exit status!")
1351
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001352
Brett Cannon42a0ba72010-05-14 00:21:48 +00001353 def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid,
Andrew Svetlov332562f2012-12-24 20:09:27 +02001354 _WNOHANG=os.WNOHANG, _os_error=os.error, _ECHILD=errno.ECHILD):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001355 """Check if child process has terminated. Returns returncode
Brett Cannon42a0ba72010-05-14 00:21:48 +00001356 attribute.
1357
1358 This method is called by __del__, so it cannot reference anything
1359 outside of the local scope (nor can any methods it calls).
1360
1361 """
Peter Astrandd38ddf42005-02-10 08:32:50 +00001362 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001363 try:
Brett Cannon42a0ba72010-05-14 00:21:48 +00001364 pid, sts = _waitpid(self.pid, _WNOHANG)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001365 if pid == self.pid:
1366 self._handle_exitstatus(sts)
Gregory P. Smith0798cbc2012-09-29 12:02:48 -07001367 except _os_error as e:
Martin v. Löwis17de8ff2006-04-10 15:55:37 +00001368 if _deadstate is not None:
1369 self.returncode = _deadstate
Andrew Svetlov332562f2012-12-24 20:09:27 +02001370 if e.errno == _ECHILD:
Gregory P. Smith0798cbc2012-09-29 12:02:48 -07001371 # This happens if SIGCLD is set to be ignored or
1372 # waiting for child processes has otherwise been
1373 # disabled for our process. This child is dead, we
1374 # can't get the status.
1375 # http://bugs.python.org/issue15756
1376 self.returncode = 0
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001377 return self.returncode
1378
1379
1380 def wait(self):
1381 """Wait for child process to terminate. Returns returncode
1382 attribute."""
Gregory P. Smithf2705ae2012-11-10 21:13:20 -08001383 while self.returncode is None:
Gregory P. Smith312efbc2010-12-14 15:02:53 +00001384 try:
1385 pid, sts = _eintr_retry_call(os.waitpid, self.pid, 0)
1386 except OSError as e:
1387 if e.errno != errno.ECHILD:
1388 raise
1389 # This happens if SIGCLD is set to be ignored or waiting
1390 # for child processes has otherwise been disabled for our
1391 # process. This child is dead, we can't get the status.
Gregory P. Smithf2705ae2012-11-10 21:13:20 -08001392 pid = self.pid
Gregory P. Smith312efbc2010-12-14 15:02:53 +00001393 sts = 0
Gregory P. Smithf2705ae2012-11-10 21:13:20 -08001394 # Check the pid and loop as waitpid has been known to return
1395 # 0 even without WNOHANG in odd situations. issue14396.
1396 if pid == self.pid:
1397 self._handle_exitstatus(sts)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001398 return self.returncode
1399
1400
Peter Astrand23109f02005-03-03 20:28:59 +00001401 def _communicate(self, input):
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001402 if self.stdin:
1403 # Flush stdio buffer. This might block, if the user has
1404 # been writing to .stdin in an uncontrolled fashion.
1405 self.stdin.flush()
1406 if not input:
1407 self.stdin.close()
1408
1409 if _has_poll:
1410 stdout, stderr = self._communicate_with_poll(input)
1411 else:
1412 stdout, stderr = self._communicate_with_select(input)
1413
1414 # All data exchanged. Translate lists into strings.
1415 if stdout is not None:
1416 stdout = ''.join(stdout)
1417 if stderr is not None:
1418 stderr = ''.join(stderr)
1419
1420 # Translate newlines, if requested. We cannot let the file
1421 # object do the translation: It is based on stdio, which is
1422 # impossible to combine with select (unless forcing no
1423 # buffering).
1424 if self.universal_newlines and hasattr(file, 'newlines'):
1425 if stdout:
1426 stdout = self._translate_newlines(stdout)
1427 if stderr:
1428 stderr = self._translate_newlines(stderr)
1429
1430 self.wait()
1431 return (stdout, stderr)
1432
1433
1434 def _communicate_with_poll(self, input):
1435 stdout = None # Return
1436 stderr = None # Return
1437 fd2file = {}
1438 fd2output = {}
1439
1440 poller = select.poll()
1441 def register_and_append(file_obj, eventmask):
1442 poller.register(file_obj.fileno(), eventmask)
1443 fd2file[file_obj.fileno()] = file_obj
1444
1445 def close_unregister_and_remove(fd):
1446 poller.unregister(fd)
1447 fd2file[fd].close()
1448 fd2file.pop(fd)
1449
1450 if self.stdin and input:
1451 register_and_append(self.stdin, select.POLLOUT)
1452
1453 select_POLLIN_POLLPRI = select.POLLIN | select.POLLPRI
1454 if self.stdout:
1455 register_and_append(self.stdout, select_POLLIN_POLLPRI)
1456 fd2output[self.stdout.fileno()] = stdout = []
1457 if self.stderr:
1458 register_and_append(self.stderr, select_POLLIN_POLLPRI)
1459 fd2output[self.stderr.fileno()] = stderr = []
1460
1461 input_offset = 0
1462 while fd2file:
1463 try:
1464 ready = poller.poll()
1465 except select.error, e:
1466 if e.args[0] == errno.EINTR:
1467 continue
1468 raise
1469
1470 for fd, mode in ready:
1471 if mode & select.POLLOUT:
1472 chunk = input[input_offset : input_offset + _PIPE_BUF]
Ross Lagerwall104c3f12011-04-05 15:24:34 +02001473 try:
1474 input_offset += os.write(fd, chunk)
1475 except OSError as e:
1476 if e.errno == errno.EPIPE:
1477 close_unregister_and_remove(fd)
1478 else:
1479 raise
1480 else:
1481 if input_offset >= len(input):
1482 close_unregister_and_remove(fd)
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001483 elif mode & select_POLLIN_POLLPRI:
1484 data = os.read(fd, 4096)
1485 if not data:
1486 close_unregister_and_remove(fd)
1487 fd2output[fd].append(data)
1488 else:
1489 # Ignore hang up or errors.
1490 close_unregister_and_remove(fd)
1491
1492 return (stdout, stderr)
1493
1494
1495 def _communicate_with_select(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001496 read_set = []
1497 write_set = []
1498 stdout = None # Return
1499 stderr = None # Return
1500
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001501 if self.stdin and input:
1502 write_set.append(self.stdin)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001503 if self.stdout:
1504 read_set.append(self.stdout)
Tim Peterse718f612004-10-12 21:51:32 +00001505 stdout = []
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001506 if self.stderr:
1507 read_set.append(self.stderr)
1508 stderr = []
1509
Peter Astrand1812f8c2007-01-07 14:34:16 +00001510 input_offset = 0
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001511 while read_set or write_set:
Gregory P. Smithf4140642008-07-06 07:16:40 +00001512 try:
1513 rlist, wlist, xlist = select.select(read_set, write_set, [])
1514 except select.error, e:
1515 if e.args[0] == errno.EINTR:
1516 continue
1517 raise
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001518
1519 if self.stdin in wlist:
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001520 chunk = input[input_offset : input_offset + _PIPE_BUF]
Ross Lagerwall104c3f12011-04-05 15:24:34 +02001521 try:
1522 bytes_written = os.write(self.stdin.fileno(), chunk)
1523 except OSError as e:
1524 if e.errno == errno.EPIPE:
1525 self.stdin.close()
1526 write_set.remove(self.stdin)
1527 else:
1528 raise
1529 else:
1530 input_offset += bytes_written
1531 if input_offset >= len(input):
1532 self.stdin.close()
1533 write_set.remove(self.stdin)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001534
1535 if self.stdout in rlist:
1536 data = os.read(self.stdout.fileno(), 1024)
1537 if data == "":
1538 self.stdout.close()
1539 read_set.remove(self.stdout)
1540 stdout.append(data)
1541
1542 if self.stderr in rlist:
1543 data = os.read(self.stderr.fileno(), 1024)
1544 if data == "":
1545 self.stderr.close()
1546 read_set.remove(self.stderr)
1547 stderr.append(data)
1548
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001549 return (stdout, stderr)
1550
Gregory P. Smithdd7ca242009-07-04 01:49:29 +00001551
Christian Heimese74c8f22008-04-19 02:23:57 +00001552 def send_signal(self, sig):
1553 """Send a signal to the process
1554 """
1555 os.kill(self.pid, sig)
1556
1557 def terminate(self):
1558 """Terminate the process with SIGTERM
1559 """
1560 self.send_signal(signal.SIGTERM)
1561
1562 def kill(self):
1563 """Kill the process with SIGKILL
1564 """
1565 self.send_signal(signal.SIGKILL)
1566
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001567
1568def _demo_posix():
1569 #
1570 # Example 1: Simple redirection: Get process list
1571 #
1572 plist = Popen(["ps"], stdout=PIPE).communicate()[0]
1573 print "Process list:"
1574 print plist
1575
1576 #
1577 # Example 2: Change uid before executing child
1578 #
1579 if os.getuid() == 0:
1580 p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1581 p.wait()
1582
1583 #
1584 # Example 3: Connecting several subprocesses
1585 #
1586 print "Looking for 'hda'..."
1587 p1 = Popen(["dmesg"], stdout=PIPE)
1588 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
1589 print repr(p2.communicate()[0])
1590
1591 #
1592 # Example 4: Catch execution error
1593 #
1594 print
1595 print "Trying a weird file..."
1596 try:
1597 print Popen(["/this/path/does/not/exist"]).communicate()
1598 except OSError, e:
1599 if e.errno == errno.ENOENT:
1600 print "The file didn't exist. I thought so..."
1601 print "Child traceback:"
1602 print e.child_traceback
1603 else:
1604 print "Error", e.errno
1605 else:
1606 print >>sys.stderr, "Gosh. No error."
1607
1608
1609def _demo_windows():
1610 #
1611 # Example 1: Connecting several subprocesses
1612 #
1613 print "Looking for 'PROMPT' in set output..."
1614 p1 = Popen("set", stdout=PIPE, shell=True)
1615 p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
1616 print repr(p2.communicate()[0])
1617
1618 #
1619 # Example 2: Simple execution of program
1620 #
1621 print "Executing calc..."
1622 p = Popen("calc")
1623 p.wait()
1624
1625
1626if __name__ == "__main__":
1627 if mswindows:
1628 _demo_windows()
1629 else:
1630 _demo_posix()