blob: 949c30a50958719f5ff9f9e4dd4d2640e907fcab [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
14intends to replace several other, older modules and functions, like:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000015
16os.system
17os.spawn*
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000018
19Information about how the subprocess module can be used to replace these
20modules and functions can be found below.
21
22
23
24Using the subprocess module
25===========================
26This module defines one class called Popen:
27
28class Popen(args, bufsize=0, executable=None,
29 stdin=None, stdout=None, stderr=None,
30 preexec_fn=None, close_fds=False, shell=False,
31 cwd=None, env=None, universal_newlines=False,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000032 startupinfo=None, creationflags=0,
33 restore_signals=True, start_new_session=False):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000034
35
36Arguments are:
37
38args should be a string, or a sequence of program arguments. The
39program to execute is normally the first item in the args sequence or
40string, but can be explicitly set by using the executable argument.
41
42On UNIX, with shell=False (default): In this case, the Popen class
43uses os.execvp() to execute the child program. args should normally
44be a sequence. A string will be treated as a sequence with the string
45as the only item (the program to execute).
46
47On UNIX, with shell=True: If args is a string, it specifies the
48command string to execute through the shell. If args is a sequence,
49the first item specifies the command string, and any additional items
50will be treated as additional shell arguments.
51
52On Windows: the Popen class uses CreateProcess() to execute the child
53program, which operates on strings. If args is a sequence, it will be
54converted to a string using the list2cmdline method. Please note that
55not all MS Windows applications interpret the command line the same
56way: The list2cmdline is designed for applications using the same
57rules as the MS C runtime.
58
59bufsize, if given, has the same meaning as the corresponding argument
60to the built-in open() function: 0 means unbuffered, 1 means line
61buffered, any other positive value means use a buffer of
62(approximately) that size. A negative bufsize means to use the system
63default, which usually means fully buffered. The default value for
64bufsize is 0 (unbuffered).
65
66stdin, stdout and stderr specify the executed programs' standard
67input, standard output and standard error file handles, respectively.
68Valid values are PIPE, an existing file descriptor (a positive
69integer), an existing file object, and None. PIPE indicates that a
70new pipe to the child should be created. With None, no redirection
71will occur; the child's file handles will be inherited from the
72parent. Additionally, stderr can be STDOUT, which indicates that the
73stderr data from the applications should be captured into the same
74file handle as for stdout.
75
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000076On UNIX, if preexec_fn is set to a callable object, this object will be
77called in the child process just before the child is executed. The use
78of preexec_fn is not thread safe, using it in the presence of threads
79could lead to a deadlock in the child process before the new executable
80is executed.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000081
82If close_fds is true, all file descriptors except 0, 1 and 2 will be
83closed before the child process is executed.
84
85if shell is true, the specified command will be executed through the
86shell.
87
88If cwd is not None, the current directory will be changed to cwd
89before the child is executed.
90
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000091On UNIX, if restore_signals is True all signals that Python sets to
92SIG_IGN are restored to SIG_DFL in the child process before the exec.
93Currently this includes the SIGPIPE, SIGXFZ and SIGXFSZ signals. This
94parameter does nothing on Windows.
95
96On UNIX, if start_new_session is True, the setsid() system call will be made
97in the child process prior to executing the command.
98
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000099If env is not None, it defines the environment variables for the new
100process.
101
102If universal_newlines is true, the file objects stdout and stderr are
103opened as a text files, but lines may be terminated by any of '\n',
104the Unix end-of-line convention, '\r', the Macintosh convention or
105'\r\n', the Windows convention. All of these external representations
106are seen as '\n' by the Python program. Note: This feature is only
107available if Python is built with universal newline support (the
108default). Also, the newlines attribute of the file objects stdout,
109stdin and stderr are not updated by the communicate() method.
110
111The startupinfo and creationflags, if given, will be passed to the
112underlying CreateProcess() function. They can specify things such as
113appearance of the main window and priority for the new process.
114(Windows only)
115
116
Georg Brandlf9734072008-12-07 15:30:06 +0000117This module also defines some shortcut functions:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000118
Peter Astrand5f5e1412004-12-05 20:15:36 +0000119call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000120 Run command with arguments. Wait for command to complete, then
121 return the returncode attribute.
122
123 The arguments are the same as for the Popen constructor. Example:
124
Florent Xicluna4886d242010-03-08 13:27:26 +0000125 >>> retcode = subprocess.call(["ls", "-l"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000126
Peter Astrand454f7672005-01-01 09:36:35 +0000127check_call(*popenargs, **kwargs):
128 Run command with arguments. Wait for command to complete. If the
129 exit code was zero then return, otherwise raise
130 CalledProcessError. The CalledProcessError object will have the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000131 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000132
133 The arguments are the same as for the Popen constructor. Example:
134
Florent Xicluna4886d242010-03-08 13:27:26 +0000135 >>> subprocess.check_call(["ls", "-l"])
Georg Brandl2708f3a2009-12-20 14:38:23 +0000136 0
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000137
Brett Cannona23810f2008-05-26 19:04:21 +0000138getstatusoutput(cmd):
139 Return (status, output) of executing cmd in a shell.
140
141 Execute the string 'cmd' in a shell with os.popen() and return a 2-tuple
142 (status, output). cmd is actually run as '{ cmd ; } 2>&1', so that the
143 returned output will contain output or error messages. A trailing newline
144 is stripped from the output. The exit status for the command can be
145 interpreted according to the rules for the C function wait(). Example:
146
Brett Cannona23810f2008-05-26 19:04:21 +0000147 >>> subprocess.getstatusoutput('ls /bin/ls')
148 (0, '/bin/ls')
149 >>> subprocess.getstatusoutput('cat /bin/junk')
150 (256, 'cat: /bin/junk: No such file or directory')
151 >>> subprocess.getstatusoutput('/bin/junk')
152 (256, 'sh: /bin/junk: not found')
153
154getoutput(cmd):
155 Return output (stdout or stderr) of executing cmd in a shell.
156
157 Like getstatusoutput(), except the exit status is ignored and the return
158 value is a string containing the command's output. Example:
159
Brett Cannona23810f2008-05-26 19:04:21 +0000160 >>> subprocess.getoutput('ls /bin/ls')
161 '/bin/ls'
162
Georg Brandlf9734072008-12-07 15:30:06 +0000163check_output(*popenargs, **kwargs):
Georg Brandl2708f3a2009-12-20 14:38:23 +0000164 Run command with arguments and return its output as a byte string.
Georg Brandlf9734072008-12-07 15:30:06 +0000165
Georg Brandl2708f3a2009-12-20 14:38:23 +0000166 If the exit code was non-zero it raises a CalledProcessError. The
167 CalledProcessError object will have the return code in the returncode
168 attribute and output in the output attribute.
Georg Brandlf9734072008-12-07 15:30:06 +0000169
Georg Brandl2708f3a2009-12-20 14:38:23 +0000170 The arguments are the same as for the Popen constructor. Example:
Georg Brandlf9734072008-12-07 15:30:06 +0000171
Georg Brandl2708f3a2009-12-20 14:38:23 +0000172 >>> output = subprocess.check_output(["ls", "-l", "/dev/null"])
Georg Brandlf9734072008-12-07 15:30:06 +0000173
Brett Cannona23810f2008-05-26 19:04:21 +0000174
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000175Exceptions
176----------
177Exceptions raised in the child process, before the new program has
178started to execute, will be re-raised in the parent. Additionally,
179the exception object will have one extra attribute called
180'child_traceback', which is a string containing traceback information
181from the childs point of view.
182
183The most common exception raised is OSError. This occurs, for
184example, when trying to execute a non-existent file. Applications
185should prepare for OSErrors.
186
187A ValueError will be raised if Popen is called with invalid arguments.
188
Georg Brandlf9734072008-12-07 15:30:06 +0000189check_call() and check_output() will raise CalledProcessError, if the
190called process returns a non-zero return code.
Peter Astrand454f7672005-01-01 09:36:35 +0000191
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000192
193Security
194--------
195Unlike some other popen functions, this implementation will never call
196/bin/sh implicitly. This means that all characters, including shell
197metacharacters, can safely be passed to child processes.
198
199
200Popen objects
201=============
202Instances of the Popen class have the following methods:
203
204poll()
205 Check if child process has terminated. Returns returncode
206 attribute.
207
208wait()
209 Wait for child process to terminate. Returns returncode attribute.
210
211communicate(input=None)
212 Interact with process: Send data to stdin. Read data from stdout
213 and stderr, until end-of-file is reached. Wait for process to
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000214 terminate. The optional input argument should be a string to be
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000215 sent to the child process, or None, if no data should be sent to
216 the child.
Tim Peterse718f612004-10-12 21:51:32 +0000217
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000218 communicate() returns a tuple (stdout, stderr).
219
220 Note: The data read is buffered in memory, so do not use this
221 method if the data size is large or unlimited.
222
223The following attributes are also available:
224
225stdin
226 If the stdin argument is PIPE, this attribute is a file object
227 that provides input to the child process. Otherwise, it is None.
228
229stdout
230 If the stdout argument is PIPE, this attribute is a file object
231 that provides output from the child process. Otherwise, it is
232 None.
233
234stderr
235 If the stderr argument is PIPE, this attribute is file object that
236 provides error output from the child process. Otherwise, it is
237 None.
238
239pid
240 The process ID of the child process.
241
242returncode
243 The child return code. A None value indicates that the process
244 hasn't terminated yet. A negative value -N indicates that the
245 child was terminated by signal N (UNIX only).
246
247
248Replacing older functions with the subprocess module
249====================================================
250In this section, "a ==> b" means that b can be used as a replacement
251for a.
252
253Note: All functions in this section fail (more or less) silently if
254the executed program cannot be found; this module raises an OSError
255exception.
256
257In the following examples, we assume that the subprocess module is
258imported with "from subprocess import *".
259
260
261Replacing /bin/sh shell backquote
262---------------------------------
263output=`mycmd myarg`
264==>
265output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
266
267
268Replacing shell pipe line
269-------------------------
270output=`dmesg | grep hda`
271==>
272p1 = Popen(["dmesg"], stdout=PIPE)
Peter Astrand6fdf3cb2004-11-30 18:06:42 +0000273p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000274output = p2.communicate()[0]
275
276
277Replacing os.system()
278---------------------
279sts = os.system("mycmd" + " myarg")
280==>
281p = Popen("mycmd" + " myarg", shell=True)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000282pid, sts = os.waitpid(p.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000283
284Note:
285
286* Calling the program through the shell is usually not required.
287
288* It's easier to look at the returncode attribute than the
289 exitstatus.
290
291A more real-world example would look like this:
292
293try:
294 retcode = call("mycmd" + " myarg", shell=True)
295 if retcode < 0:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000296 print("Child was terminated by signal", -retcode, file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000297 else:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000298 print("Child returned", retcode, file=sys.stderr)
299except OSError as e:
300 print("Execution failed:", e, file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000301
302
303Replacing os.spawn*
304-------------------
Tim Peterse718f612004-10-12 21:51:32 +0000305P_NOWAIT example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000306
307pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
308==>
309pid = Popen(["/bin/mycmd", "myarg"]).pid
310
311
312P_WAIT example:
313
314retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
315==>
316retcode = call(["/bin/mycmd", "myarg"])
317
318
Tim Peterse718f612004-10-12 21:51:32 +0000319Vector example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000320
321os.spawnvp(os.P_NOWAIT, path, args)
322==>
323Popen([path] + args[1:])
324
325
Tim Peterse718f612004-10-12 21:51:32 +0000326Environment example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000327
328os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
329==>
330Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000331"""
332
333import sys
334mswindows = (sys.platform == "win32")
335
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000336import io
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000337import os
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000338import traceback
Christian Heimesfdab48e2008-01-20 09:06:41 +0000339import gc
Christian Heimesa342c012008-04-20 21:01:16 +0000340import signal
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000341import builtins
Gregory P. Smithd23047b2010-12-04 09:10:44 +0000342import warnings
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000343
Peter Astrand454f7672005-01-01 09:36:35 +0000344# Exception classes used by this module.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000345class CalledProcessError(Exception):
Georg Brandlf9734072008-12-07 15:30:06 +0000346 """This exception is raised when a process run by check_call() or
347 check_output() returns a non-zero exit status.
348 The exit status will be stored in the returncode attribute;
349 check_output() will also store the output in the output attribute.
350 """
351 def __init__(self, returncode, cmd, output=None):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000352 self.returncode = returncode
353 self.cmd = cmd
Georg Brandlf9734072008-12-07 15:30:06 +0000354 self.output = output
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000355 def __str__(self):
356 return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
357
Peter Astrand454f7672005-01-01 09:36:35 +0000358
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000359if mswindows:
360 import threading
361 import msvcrt
Brian Curtin1ce6b582010-04-24 16:19:22 +0000362 import _subprocess
363 class STARTUPINFO:
364 dwFlags = 0
365 hStdInput = None
366 hStdOutput = None
367 hStdError = None
368 wShowWindow = 0
369 class pywintypes:
370 error = IOError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000371else:
372 import select
Gregory P. Smithd06fa472009-07-04 02:46:54 +0000373 _has_poll = hasattr(select, 'poll')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000374 import errno
375 import fcntl
376 import pickle
377
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000378 try:
379 import _posixsubprocess
380 except ImportError:
381 _posixsubprocess = None
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000382 warnings.warn("The _posixsubprocess module is not being used. "
383 "Child process reliability may suffer if your "
384 "program uses threads.", RuntimeWarning)
385
Amaury Forgeot d'Arcace31022009-07-09 22:44:11 +0000386 # When select or poll has indicated that the file is writable,
387 # we can write up to _PIPE_BUF bytes without risk of blocking.
388 # POSIX defines PIPE_BUF as >= 512.
389 _PIPE_BUF = getattr(select, 'PIPE_BUF', 512)
390
391
Brett Cannona23810f2008-05-26 19:04:21 +0000392__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "getstatusoutput",
Georg Brandlf9734072008-12-07 15:30:06 +0000393 "getoutput", "check_output", "CalledProcessError"]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000394
Brian Curtin1ce6b582010-04-24 16:19:22 +0000395if mswindows:
Brett Cannon84df1e62010-05-14 00:33:40 +0000396 from _subprocess import CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP
Brian Curtin1ce6b582010-04-24 16:19:22 +0000397 __all__.extend(["CREATE_NEW_CONSOLE", "CREATE_NEW_PROCESS_GROUP"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000398try:
399 MAXFD = os.sysconf("SC_OPEN_MAX")
400except:
401 MAXFD = 256
402
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000403_active = []
404
405def _cleanup():
406 for inst in _active[:]:
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000407 res = inst._internal_poll(_deadstate=sys.maxsize)
Guido van Rossumb5d47ef2006-08-24 02:27:45 +0000408 if res is not None and res >= 0:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000409 try:
410 _active.remove(inst)
411 except ValueError:
412 # This can happen if two threads create a new Popen instance.
413 # It's harmless that it was already removed, so ignore.
414 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000415
416PIPE = -1
417STDOUT = -2
418
419
Gregory P. Smitha59c59f2010-03-01 00:17:40 +0000420def _eintr_retry_call(func, *args):
421 while True:
422 try:
423 return func(*args)
424 except OSError as e:
425 if e.errno == errno.EINTR:
426 continue
427 raise
428
429
Peter Astrand5f5e1412004-12-05 20:15:36 +0000430def call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000431 """Run command with arguments. Wait for command to complete, then
432 return the returncode attribute.
433
434 The arguments are the same as for the Popen constructor. Example:
435
436 retcode = call(["ls", "-l"])
437 """
Peter Astrand5f5e1412004-12-05 20:15:36 +0000438 return Popen(*popenargs, **kwargs).wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000439
440
Peter Astrand454f7672005-01-01 09:36:35 +0000441def check_call(*popenargs, **kwargs):
442 """Run command with arguments. Wait for command to complete. If
443 the exit code was zero then return, otherwise raise
444 CalledProcessError. The CalledProcessError object will have the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000445 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000446
447 The arguments are the same as for the Popen constructor. Example:
448
449 check_call(["ls", "-l"])
450 """
451 retcode = call(*popenargs, **kwargs)
Peter Astrand454f7672005-01-01 09:36:35 +0000452 if retcode:
Georg Brandlf9734072008-12-07 15:30:06 +0000453 cmd = kwargs.get("args")
454 if cmd is None:
455 cmd = popenargs[0]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000456 raise CalledProcessError(retcode, cmd)
Georg Brandlf9734072008-12-07 15:30:06 +0000457 return 0
458
459
460def check_output(*popenargs, **kwargs):
Georg Brandl2708f3a2009-12-20 14:38:23 +0000461 r"""Run command with arguments and return its output as a byte string.
Georg Brandlf9734072008-12-07 15:30:06 +0000462
463 If the exit code was non-zero it raises a CalledProcessError. The
464 CalledProcessError object will have the return code in the returncode
465 attribute and output in the output attribute.
466
467 The arguments are the same as for the Popen constructor. Example:
468
469 >>> check_output(["ls", "-l", "/dev/null"])
Georg Brandl2708f3a2009-12-20 14:38:23 +0000470 b'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000471
472 The stdout argument is not allowed as it is used internally.
Georg Brandl127d4702009-12-28 08:10:38 +0000473 To capture standard error in the result, use stderr=STDOUT.
Georg Brandlf9734072008-12-07 15:30:06 +0000474
475 >>> check_output(["/bin/sh", "-c",
Georg Brandl2708f3a2009-12-20 14:38:23 +0000476 ... "ls -l non_existent_file ; exit 0"],
Georg Brandl127d4702009-12-28 08:10:38 +0000477 ... stderr=STDOUT)
Georg Brandl2708f3a2009-12-20 14:38:23 +0000478 b'ls: non_existent_file: No such file or directory\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000479 """
480 if 'stdout' in kwargs:
481 raise ValueError('stdout argument not allowed, it will be overridden.')
482 process = Popen(*popenargs, stdout=PIPE, **kwargs)
483 output, unused_err = process.communicate()
484 retcode = process.poll()
485 if retcode:
486 cmd = kwargs.get("args")
487 if cmd is None:
488 cmd = popenargs[0]
489 raise CalledProcessError(retcode, cmd, output=output)
490 return output
Peter Astrand454f7672005-01-01 09:36:35 +0000491
492
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000493def list2cmdline(seq):
494 """
495 Translate a sequence of arguments into a command line
496 string, using the same rules as the MS C runtime:
497
498 1) Arguments are delimited by white space, which is either a
499 space or a tab.
500
501 2) A string surrounded by double quotation marks is
502 interpreted as a single argument, regardless of white space
Jean-Paul Calderone1ddd4072010-06-18 20:03:54 +0000503 contained within. A quoted string can be embedded in an
504 argument.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000505
506 3) A double quotation mark preceded by a backslash is
507 interpreted as a literal double quotation mark.
508
509 4) Backslashes are interpreted literally, unless they
510 immediately precede a double quotation mark.
511
512 5) If backslashes immediately precede a double quotation mark,
513 every pair of backslashes is interpreted as a literal
514 backslash. If the number of backslashes is odd, the last
515 backslash escapes the next double quotation mark as
516 described in rule 3.
517 """
518
519 # See
Eric Smith3c573af2009-11-09 15:23:15 +0000520 # http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
521 # or search http://msdn.microsoft.com for
522 # "Parsing C++ Command-Line Arguments"
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000523 result = []
524 needquote = False
525 for arg in seq:
526 bs_buf = []
527
528 # Add a space to separate this argument from the others
529 if result:
530 result.append(' ')
531
Jean-Paul Calderone1ddd4072010-06-18 20:03:54 +0000532 needquote = (" " in arg) or ("\t" in arg) or not arg
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000533 if needquote:
534 result.append('"')
535
536 for c in arg:
537 if c == '\\':
Tim Peterse718f612004-10-12 21:51:32 +0000538 # Don't know if we need to double yet.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000539 bs_buf.append(c)
540 elif c == '"':
Christian Heimesfdab48e2008-01-20 09:06:41 +0000541 # Double backslashes.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000542 result.append('\\' * len(bs_buf)*2)
543 bs_buf = []
544 result.append('\\"')
545 else:
546 # Normal char
547 if bs_buf:
548 result.extend(bs_buf)
549 bs_buf = []
550 result.append(c)
551
Christian Heimesfdab48e2008-01-20 09:06:41 +0000552 # Add remaining backslashes, if any.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000553 if bs_buf:
554 result.extend(bs_buf)
555
556 if needquote:
Peter Astrand7e78ade2005-03-03 21:10:23 +0000557 result.extend(bs_buf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000558 result.append('"')
559
560 return ''.join(result)
561
562
Brett Cannona23810f2008-05-26 19:04:21 +0000563# Various tools for executing commands and looking at their output and status.
564#
565# NB This only works (and is only relevant) for UNIX.
566
567def getstatusoutput(cmd):
568 """Return (status, output) of executing cmd in a shell.
569
570 Execute the string 'cmd' in a shell with os.popen() and return a 2-tuple
571 (status, output). cmd is actually run as '{ cmd ; } 2>&1', so that the
572 returned output will contain output or error messages. A trailing newline
573 is stripped from the output. The exit status for the command can be
574 interpreted according to the rules for the C function wait(). Example:
575
576 >>> import subprocess
577 >>> subprocess.getstatusoutput('ls /bin/ls')
578 (0, '/bin/ls')
579 >>> subprocess.getstatusoutput('cat /bin/junk')
580 (256, 'cat: /bin/junk: No such file or directory')
581 >>> subprocess.getstatusoutput('/bin/junk')
582 (256, 'sh: /bin/junk: not found')
583 """
584 pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
585 text = pipe.read()
586 sts = pipe.close()
587 if sts is None: sts = 0
588 if text[-1:] == '\n': text = text[:-1]
589 return sts, text
590
591
592def getoutput(cmd):
593 """Return output (stdout or stderr) of executing cmd in a shell.
594
595 Like getstatusoutput(), except the exit status is ignored and the return
596 value is a string containing the command's output. Example:
597
598 >>> import subprocess
599 >>> subprocess.getoutput('ls /bin/ls')
600 '/bin/ls'
601 """
602 return getstatusoutput(cmd)[1]
603
604
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000605class Popen(object):
606 def __init__(self, args, bufsize=0, executable=None,
607 stdin=None, stdout=None, stderr=None,
Gregory P. Smithd23047b2010-12-04 09:10:44 +0000608 preexec_fn=None, close_fds=None, shell=False,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000609 cwd=None, env=None, universal_newlines=False,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000610 startupinfo=None, creationflags=0,
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000611 restore_signals=True, start_new_session=False,
612 pass_fds=()):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000613 """Create new Popen instance."""
614 _cleanup()
615
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000616 self._child_created = False
Guido van Rossum46a05a72007-06-07 21:56:45 +0000617 if bufsize is None:
618 bufsize = 0 # Restore default
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000619 if not isinstance(bufsize, int):
Peter Astrand738131d2004-11-30 21:04:45 +0000620 raise TypeError("bufsize must be an integer")
621
Gregory P. Smithd23047b2010-12-04 09:10:44 +0000622 if close_fds is None:
623 # Notification for http://bugs.python.org/issue7213 & issue2320
624 warnings.warn(
625 'The close_fds parameter was not specified. Its default'
626 ' will change from False to True in a future Python'
627 ' version. Most users should set it to True. Please'
628 ' update your code explicitly set close_fds.',
629 DeprecationWarning)
630
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000631 if mswindows:
Tim Peterse8374a52004-10-13 03:15:00 +0000632 if preexec_fn is not None:
633 raise ValueError("preexec_fn is not supported on Windows "
634 "platforms")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000635 if close_fds and (stdin is not None or stdout is not None or
636 stderr is not None):
Tim Peterse8374a52004-10-13 03:15:00 +0000637 raise ValueError("close_fds is not supported on Windows "
Guido van Rossume7ba4952007-06-06 23:52:48 +0000638 "platforms if you redirect stdin/stdout/stderr")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000639 else:
640 # POSIX
Tim Peterse8374a52004-10-13 03:15:00 +0000641 if startupinfo is not None:
642 raise ValueError("startupinfo is only supported on Windows "
643 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000644 if creationflags != 0:
Tim Peterse8374a52004-10-13 03:15:00 +0000645 raise ValueError("creationflags is only supported on Windows "
646 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000647
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000648 if pass_fds and not close_fds:
649 raise ValueError("pass_fds requires close_fds=True.")
650
Tim Peterse718f612004-10-12 21:51:32 +0000651 self.stdin = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000652 self.stdout = None
653 self.stderr = None
654 self.pid = None
655 self.returncode = None
656 self.universal_newlines = universal_newlines
657
658 # Input and output objects. The general principle is like
659 # this:
660 #
661 # Parent Child
662 # ------ -----
663 # p2cwrite ---stdin---> p2cread
664 # c2pread <--stdout--- c2pwrite
665 # errread <--stderr--- errwrite
666 #
667 # On POSIX, the child objects are file descriptors. On
668 # Windows, these are Windows file handles. The parent objects
669 # are file descriptors on both platforms. The parent objects
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000670 # are -1 when not using PIPEs. The child objects are -1
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000671 # when not redirecting.
Tim Peterse718f612004-10-12 21:51:32 +0000672
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000673 (p2cread, p2cwrite,
674 c2pread, c2pwrite,
675 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
676
677 self._execute_child(args, executable, preexec_fn, close_fds,
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000678 pass_fds, cwd, env, universal_newlines,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000679 startupinfo, creationflags, shell,
680 p2cread, p2cwrite,
681 c2pread, c2pwrite,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000682 errread, errwrite,
683 restore_signals, start_new_session)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000684
Thomas Wouterscf297e42007-02-23 15:07:44 +0000685 if mswindows:
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000686 if p2cwrite != -1:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000687 p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000688 if c2pread != -1:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000689 c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000690 if errread != -1:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000691 errread = msvcrt.open_osfhandle(errread.Detach(), 0)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000692
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000693 if bufsize == 0:
694 bufsize = 1 # Nearly unbuffered (XXX for now)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000695 if p2cwrite != -1:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000696 self.stdin = io.open(p2cwrite, 'wb', bufsize)
697 if self.universal_newlines:
698 self.stdin = io.TextIOWrapper(self.stdin)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000699 if c2pread != -1:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000700 self.stdout = io.open(c2pread, 'rb', bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000701 if universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000702 self.stdout = io.TextIOWrapper(self.stdout)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000703 if errread != -1:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000704 self.stderr = io.open(errread, 'rb', bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000705 if universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000706 self.stderr = io.TextIOWrapper(self.stderr)
Tim Peterse718f612004-10-12 21:51:32 +0000707
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000708
Guido van Rossum98297ee2007-11-06 21:34:58 +0000709 def _translate_newlines(self, data, encoding):
710 data = data.replace(b"\r\n", b"\n").replace(b"\r", b"\n")
711 return data.decode(encoding)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000712
Brian Curtin79cdb662010-12-03 02:46:02 +0000713 def __enter__(self):
714 return self
715
716 def __exit__(self, type, value, traceback):
717 if self.stdout:
718 self.stdout.close()
719 if self.stderr:
720 self.stderr.close()
721 if self.stdin:
722 self.stdin.close()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000723
Brett Cannon84df1e62010-05-14 00:33:40 +0000724 def __del__(self, _maxsize=sys.maxsize, _active=_active):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000725 if not self._child_created:
726 # We didn't get to successfully create a child process.
727 return
728 # In case the child hasn't been waited on, check if it's done.
Brett Cannon84df1e62010-05-14 00:33:40 +0000729 self._internal_poll(_deadstate=_maxsize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000730 if self.returncode is None and _active is not None:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000731 # Child is still running, keep us alive until we can wait on it.
732 _active.append(self)
733
734
Peter Astrand23109f02005-03-03 20:28:59 +0000735 def communicate(self, input=None):
736 """Interact with process: Send data to stdin. Read data from
737 stdout and stderr, until end-of-file is reached. Wait for
738 process to terminate. The optional input argument should be a
739 string to be sent to the child process, or None, if no data
740 should be sent to the child.
Tim Peterseba28be2005-03-28 01:08:02 +0000741
Peter Astrand23109f02005-03-03 20:28:59 +0000742 communicate() returns a tuple (stdout, stderr)."""
743
744 # Optimization: If we are only using one pipe, or no pipe at
745 # all, using select() or threads is unnecessary.
746 if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
Tim Peterseba28be2005-03-28 01:08:02 +0000747 stdout = None
748 stderr = None
Peter Astrand23109f02005-03-03 20:28:59 +0000749 if self.stdin:
750 if input:
751 self.stdin.write(input)
752 self.stdin.close()
753 elif self.stdout:
754 stdout = self.stdout.read()
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000755 self.stdout.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000756 elif self.stderr:
757 stderr = self.stderr.read()
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000758 self.stderr.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000759 self.wait()
760 return (stdout, stderr)
Tim Peterseba28be2005-03-28 01:08:02 +0000761
Peter Astrand23109f02005-03-03 20:28:59 +0000762 return self._communicate(input)
763
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000764
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000765 def poll(self):
766 return self._internal_poll()
767
768
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000769 if mswindows:
770 #
771 # Windows methods
772 #
773 def _get_handles(self, stdin, stdout, stderr):
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +0000774 """Construct and return tuple with IO objects:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000775 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
776 """
Peter Astrandd38ddf42005-02-10 08:32:50 +0000777 if stdin is None and stdout is None and stderr is None:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000778 return (-1, -1, -1, -1, -1, -1)
Tim Peterse718f612004-10-12 21:51:32 +0000779
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000780 p2cread, p2cwrite = -1, -1
781 c2pread, c2pwrite = -1, -1
782 errread, errwrite = -1, -1
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000783
Peter Astrandd38ddf42005-02-10 08:32:50 +0000784 if stdin is None:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000785 p2cread = _subprocess.GetStdHandle(_subprocess.STD_INPUT_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000786 if p2cread is None:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000787 p2cread, _ = _subprocess.CreatePipe(None, 0)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000788 elif stdin == PIPE:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000789 p2cread, p2cwrite = _subprocess.CreatePipe(None, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000790 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000791 p2cread = msvcrt.get_osfhandle(stdin)
792 else:
793 # Assuming file-like object
794 p2cread = msvcrt.get_osfhandle(stdin.fileno())
795 p2cread = self._make_inheritable(p2cread)
796
Peter Astrandd38ddf42005-02-10 08:32:50 +0000797 if stdout is None:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000798 c2pwrite = _subprocess.GetStdHandle(_subprocess.STD_OUTPUT_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000799 if c2pwrite is None:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000800 _, c2pwrite = _subprocess.CreatePipe(None, 0)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000801 elif stdout == PIPE:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000802 c2pread, c2pwrite = _subprocess.CreatePipe(None, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000803 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000804 c2pwrite = msvcrt.get_osfhandle(stdout)
805 else:
806 # Assuming file-like object
807 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
808 c2pwrite = self._make_inheritable(c2pwrite)
809
Peter Astrandd38ddf42005-02-10 08:32:50 +0000810 if stderr is None:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000811 errwrite = _subprocess.GetStdHandle(_subprocess.STD_ERROR_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000812 if errwrite is None:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000813 _, errwrite = _subprocess.CreatePipe(None, 0)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000814 elif stderr == PIPE:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000815 errread, errwrite = _subprocess.CreatePipe(None, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000816 elif stderr == STDOUT:
817 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000818 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000819 errwrite = msvcrt.get_osfhandle(stderr)
820 else:
821 # Assuming file-like object
822 errwrite = msvcrt.get_osfhandle(stderr.fileno())
823 errwrite = self._make_inheritable(errwrite)
824
825 return (p2cread, p2cwrite,
826 c2pread, c2pwrite,
827 errread, errwrite)
828
829
830 def _make_inheritable(self, handle):
831 """Return a duplicate of handle, which is inheritable"""
Brian Curtin1ce6b582010-04-24 16:19:22 +0000832 return _subprocess.DuplicateHandle(_subprocess.GetCurrentProcess(),
833 handle, _subprocess.GetCurrentProcess(), 0, 1,
834 _subprocess.DUPLICATE_SAME_ACCESS)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000835
836
837 def _find_w9xpopen(self):
838 """Find and return absolut path to w9xpopen.exe"""
Brian Curtin1ce6b582010-04-24 16:19:22 +0000839 w9xpopen = os.path.join(
840 os.path.dirname(_subprocess.GetModuleFileName(0)),
Tim Peterse8374a52004-10-13 03:15:00 +0000841 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000842 if not os.path.exists(w9xpopen):
843 # Eeek - file-not-found - possibly an embedding
844 # situation - see if we can locate it in sys.exec_prefix
Tim Peterse8374a52004-10-13 03:15:00 +0000845 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
846 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000847 if not os.path.exists(w9xpopen):
Tim Peterse8374a52004-10-13 03:15:00 +0000848 raise RuntimeError("Cannot locate w9xpopen.exe, which is "
849 "needed for Popen to work with your "
850 "shell or platform.")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000851 return w9xpopen
852
Tim Peterse718f612004-10-12 21:51:32 +0000853
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000854 def _execute_child(self, args, executable, preexec_fn, close_fds,
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000855 pass_fds, cwd, env, universal_newlines,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000856 startupinfo, creationflags, shell,
857 p2cread, p2cwrite,
858 c2pread, c2pwrite,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000859 errread, errwrite,
860 unused_restore_signals, unused_start_new_session):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000861 """Execute program (MS Windows version)"""
862
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +0000863 assert not pass_fds, "pass_fds not yet supported on Windows"
864
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000865 if not isinstance(args, str):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000866 args = list2cmdline(args)
867
Peter Astrandc1d65362004-11-07 14:30:34 +0000868 # Process startup details
Peter Astrandd38ddf42005-02-10 08:32:50 +0000869 if startupinfo is None:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000870 startupinfo = STARTUPINFO()
Victor Stinnerb3693582010-05-21 20:13:12 +0000871 if -1 not in (p2cread, c2pwrite, errwrite):
Brian Curtin1ce6b582010-04-24 16:19:22 +0000872 startupinfo.dwFlags |= _subprocess.STARTF_USESTDHANDLES
Peter Astrandc1d65362004-11-07 14:30:34 +0000873 startupinfo.hStdInput = p2cread
874 startupinfo.hStdOutput = c2pwrite
875 startupinfo.hStdError = errwrite
876
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000877 if shell:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000878 startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW
879 startupinfo.wShowWindow = _subprocess.SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000880 comspec = os.environ.get("COMSPEC", "cmd.exe")
Tim Golden126c2962010-08-11 14:20:40 +0000881 args = '{} /c "{}"'.format (comspec, args)
Brian Curtin1ce6b582010-04-24 16:19:22 +0000882 if (_subprocess.GetVersion() >= 0x80000000 or
Tim Peterse8374a52004-10-13 03:15:00 +0000883 os.path.basename(comspec).lower() == "command.com"):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000884 # Win9x, or using command.com on NT. We need to
885 # use the w9xpopen intermediate program. For more
886 # information, see KB Q150956
887 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
888 w9xpopen = self._find_w9xpopen()
889 args = '"%s" %s' % (w9xpopen, args)
890 # Not passing CREATE_NEW_CONSOLE has been known to
891 # cause random failures on win9x. Specifically a
892 # dialog: "Your program accessed mem currently in
893 # use at xxx" and a hopeful warning about the
Mark Dickinson934896d2009-02-21 20:59:32 +0000894 # stability of your system. Cost is Ctrl+C won't
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000895 # kill children.
Brian Curtin1ce6b582010-04-24 16:19:22 +0000896 creationflags |= _subprocess.CREATE_NEW_CONSOLE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000897
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000898 # Start the process
899 try:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000900 hp, ht, pid, tid = _subprocess.CreateProcess(executable, args,
Tim Peterse8374a52004-10-13 03:15:00 +0000901 # no special security
902 None, None,
Guido van Rossume7ba4952007-06-06 23:52:48 +0000903 int(not close_fds),
Tim Peterse8374a52004-10-13 03:15:00 +0000904 creationflags,
905 env,
906 cwd,
907 startupinfo)
Guido van Rossumb940e112007-01-10 16:19:56 +0000908 except pywintypes.error as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000909 # Translate pywintypes.error to WindowsError, which is
910 # a subclass of OSError. FIXME: We should really
911 # translate errno using _sys_errlist (or simliar), but
912 # how can this be done from Python?
913 raise WindowsError(*e.args)
Tim Goldenad537f22010-08-08 11:18:16 +0000914 finally:
915 # Child is launched. Close the parent's copy of those pipe
916 # handles that only the child should have open. You need
917 # to make sure that no handles to the write end of the
918 # output pipe are maintained in this process or else the
919 # pipe will not close when the child process exits and the
920 # ReadFile will hang.
921 if p2cread != -1:
922 p2cread.Close()
923 if c2pwrite != -1:
924 c2pwrite.Close()
925 if errwrite != -1:
926 errwrite.Close()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000927
928 # Retain the process handle, but close the thread handle
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000929 self._child_created = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000930 self._handle = hp
931 self.pid = pid
932 ht.Close()
933
Brett Cannon84df1e62010-05-14 00:33:40 +0000934 def _internal_poll(self, _deadstate=None,
Victor Stinnerc807a612010-05-14 21:53:45 +0000935 _WaitForSingleObject=_subprocess.WaitForSingleObject,
936 _WAIT_OBJECT_0=_subprocess.WAIT_OBJECT_0,
937 _GetExitCodeProcess=_subprocess.GetExitCodeProcess):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000938 """Check if child process has terminated. Returns returncode
Brett Cannon84df1e62010-05-14 00:33:40 +0000939 attribute.
940
941 This method is called by __del__, so it can only refer to objects
942 in its local scope.
943
944 """
Peter Astrandd38ddf42005-02-10 08:32:50 +0000945 if self.returncode is None:
Brett Cannon84df1e62010-05-14 00:33:40 +0000946 if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
947 self.returncode = _GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000948 return self.returncode
949
950
951 def wait(self):
952 """Wait for child process to terminate. Returns returncode
953 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000954 if self.returncode is None:
Brian Curtin1ce6b582010-04-24 16:19:22 +0000955 _subprocess.WaitForSingleObject(self._handle,
956 _subprocess.INFINITE)
957 self.returncode = _subprocess.GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000958 return self.returncode
959
960
961 def _readerthread(self, fh, buffer):
962 buffer.append(fh.read())
963
964
Peter Astrand23109f02005-03-03 20:28:59 +0000965 def _communicate(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000966 stdout = None # Return
967 stderr = None # Return
968
969 if self.stdout:
970 stdout = []
Tim Peterse8374a52004-10-13 03:15:00 +0000971 stdout_thread = threading.Thread(target=self._readerthread,
972 args=(self.stdout, stdout))
Benjamin Peterson632e0362008-08-18 19:08:51 +0000973 stdout_thread.daemon = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000974 stdout_thread.start()
975 if self.stderr:
976 stderr = []
Tim Peterse8374a52004-10-13 03:15:00 +0000977 stderr_thread = threading.Thread(target=self._readerthread,
978 args=(self.stderr, stderr))
Benjamin Peterson632e0362008-08-18 19:08:51 +0000979 stderr_thread.daemon = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000980 stderr_thread.start()
981
982 if self.stdin:
Peter Astrandd38ddf42005-02-10 08:32:50 +0000983 if input is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000984 self.stdin.write(input)
985 self.stdin.close()
986
987 if self.stdout:
988 stdout_thread.join()
989 if self.stderr:
990 stderr_thread.join()
991
992 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000993 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000994 stdout = stdout[0]
Peter Astrandd38ddf42005-02-10 08:32:50 +0000995 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000996 stderr = stderr[0]
997
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000998 self.wait()
999 return (stdout, stderr)
1000
Christian Heimesa342c012008-04-20 21:01:16 +00001001 def send_signal(self, sig):
1002 """Send a signal to the process
1003 """
1004 if sig == signal.SIGTERM:
1005 self.terminate()
Brian Curtineb24d742010-04-12 17:16:38 +00001006 elif sig == signal.CTRL_C_EVENT:
1007 os.kill(self.pid, signal.CTRL_C_EVENT)
1008 elif sig == signal.CTRL_BREAK_EVENT:
1009 os.kill(self.pid, signal.CTRL_BREAK_EVENT)
Christian Heimesa342c012008-04-20 21:01:16 +00001010 else:
Brian Curtin19651362010-09-07 13:24:38 +00001011 raise ValueError("Unsupported signal: {}".format(sig))
Christian Heimesa342c012008-04-20 21:01:16 +00001012
1013 def terminate(self):
1014 """Terminates the process
1015 """
Brian Curtin1ce6b582010-04-24 16:19:22 +00001016 _subprocess.TerminateProcess(self._handle, 1)
Christian Heimesa342c012008-04-20 21:01:16 +00001017
1018 kill = terminate
1019
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001020 else:
1021 #
1022 # POSIX methods
1023 #
1024 def _get_handles(self, stdin, stdout, stderr):
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +00001025 """Construct and return tuple with IO objects:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001026 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
1027 """
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001028 p2cread, p2cwrite = -1, -1
1029 c2pread, c2pwrite = -1, -1
1030 errread, errwrite = -1, -1
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001031
Peter Astrandd38ddf42005-02-10 08:32:50 +00001032 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001033 pass
1034 elif stdin == PIPE:
1035 p2cread, p2cwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +00001036 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001037 p2cread = stdin
1038 else:
1039 # Assuming file-like object
1040 p2cread = stdin.fileno()
1041
Peter Astrandd38ddf42005-02-10 08:32:50 +00001042 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001043 pass
1044 elif stdout == PIPE:
1045 c2pread, c2pwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +00001046 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001047 c2pwrite = stdout
1048 else:
1049 # Assuming file-like object
Tim Peterse718f612004-10-12 21:51:32 +00001050 c2pwrite = stdout.fileno()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001051
Peter Astrandd38ddf42005-02-10 08:32:50 +00001052 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001053 pass
1054 elif stderr == PIPE:
1055 errread, errwrite = os.pipe()
1056 elif stderr == STDOUT:
1057 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +00001058 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001059 errwrite = stderr
1060 else:
1061 # Assuming file-like object
1062 errwrite = stderr.fileno()
1063
1064 return (p2cread, p2cwrite,
1065 c2pread, c2pwrite,
1066 errread, errwrite)
1067
1068
1069 def _set_cloexec_flag(self, fd):
1070 try:
1071 cloexec_flag = fcntl.FD_CLOEXEC
1072 except AttributeError:
1073 cloexec_flag = 1
1074
1075 old = fcntl.fcntl(fd, fcntl.F_GETFD)
1076 fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
1077
1078
1079 def _close_fds(self, but):
Christian Heimesfdab48e2008-01-20 09:06:41 +00001080 os.closerange(3, but)
1081 os.closerange(but + 1, MAXFD)
Tim Peterse718f612004-10-12 21:51:32 +00001082
1083
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +00001084 def _close_all_but_a_sorted_few_fds(self, fds_to_keep):
1085 # precondition: fds_to_keep must be sorted and unique
1086 start_fd = 3
1087 for fd in fds_to_keep:
1088 if fd > start_fd:
1089 os.closerange(start_fd, fd)
1090 start_fd = fd + 1
1091 if start_fd <= MAXFD:
1092 os.closerange(start_fd, MAXFD)
1093
1094
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001095 def _execute_child(self, args, executable, preexec_fn, close_fds,
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +00001096 pass_fds, cwd, env, universal_newlines,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001097 startupinfo, creationflags, shell,
1098 p2cread, p2cwrite,
1099 c2pread, c2pwrite,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001100 errread, errwrite,
1101 restore_signals, start_new_session):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001102 """Execute program (POSIX version)"""
1103
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001104 if isinstance(args, str):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001105 args = [args]
Thomas Wouters89f507f2006-12-13 04:49:30 +00001106 else:
1107 args = list(args)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001108
1109 if shell:
1110 args = ["/bin/sh", "-c"] + args
Stefan Krah9542cc62010-07-19 14:20:53 +00001111 if executable:
1112 args[0] = executable
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001113
Peter Astrandd38ddf42005-02-10 08:32:50 +00001114 if executable is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001115 executable = args[0]
1116
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001117 # For transferring possible exec failure from child to parent.
1118 # Data format: "exception name:hex errno:description"
1119 # Pickle is not used; it is complex and involves memory allocation.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001120 errpipe_read, errpipe_write = os.pipe()
Christian Heimesfdab48e2008-01-20 09:06:41 +00001121 try:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001122 try:
Facundo Batista10706e22009-06-19 20:34:30 +00001123 self._set_cloexec_flag(errpipe_write)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001124
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001125 if _posixsubprocess:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001126 # We must avoid complex work that could involve
1127 # malloc or free in the child process to avoid
1128 # potential deadlocks, thus we do all this here.
1129 # and pass it to fork_exec()
1130
1131 if env:
Victor Stinner449c4662010-05-08 11:10:09 +00001132 env_list = [os.fsencode(k) + b'=' + os.fsencode(v)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001133 for k, v in env.items()]
1134 else:
1135 env_list = None # Use execv instead of execve.
Victor Stinnerb745a742010-05-18 17:17:23 +00001136 executable = os.fsencode(executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001137 if os.path.dirname(executable):
Victor Stinnerb745a742010-05-18 17:17:23 +00001138 executable_list = (executable,)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001139 else:
1140 # This matches the behavior of os._execvpe().
Victor Stinnerb745a742010-05-18 17:17:23 +00001141 executable_list = tuple(
1142 os.path.join(os.fsencode(dir), executable)
1143 for dir in os.get_exec_path(env))
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +00001144 fds_to_keep = set(pass_fds)
1145 fds_to_keep.add(errpipe_write)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001146 self.pid = _posixsubprocess.fork_exec(
1147 args, executable_list,
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +00001148 close_fds, sorted(fds_to_keep), cwd, env_list,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001149 p2cread, p2cwrite, c2pread, c2pwrite,
1150 errread, errwrite,
1151 errpipe_read, errpipe_write,
1152 restore_signals, start_new_session, preexec_fn)
1153 else:
1154 # Pure Python implementation: It is not thread safe.
1155 # This implementation may deadlock in the child if your
1156 # parent process has any other threads running.
1157
1158 gc_was_enabled = gc.isenabled()
1159 # Disable gc to avoid bug where gc -> file_dealloc ->
1160 # write to stderr -> hang. See issue1336
1161 gc.disable()
1162 try:
1163 self.pid = os.fork()
1164 except:
1165 if gc_was_enabled:
1166 gc.enable()
1167 raise
1168 self._child_created = True
1169 if self.pid == 0:
1170 # Child
1171 try:
1172 # Close parent's pipe ends
1173 if p2cwrite != -1:
1174 os.close(p2cwrite)
1175 if c2pread != -1:
1176 os.close(c2pread)
1177 if errread != -1:
1178 os.close(errread)
1179 os.close(errpipe_read)
1180
1181 # Dup fds for child
1182 if p2cread != -1:
1183 os.dup2(p2cread, 0)
1184 if c2pwrite != -1:
1185 os.dup2(c2pwrite, 1)
1186 if errwrite != -1:
1187 os.dup2(errwrite, 2)
1188
1189 # Close pipe fds. Make sure we don't close the
1190 # same fd more than once, or standard fds.
1191 if p2cread != -1 and p2cread not in (0,):
1192 os.close(p2cread)
1193 if (c2pwrite != -1 and
1194 c2pwrite not in (p2cread, 1)):
1195 os.close(c2pwrite)
1196 if (errwrite != -1 and
1197 errwrite not in (p2cread, c2pwrite, 2)):
1198 os.close(errwrite)
1199
1200 # Close all other fds, if asked for
1201 if close_fds:
Gregory P. Smithd4cc7bf2010-12-04 11:22:11 +00001202 if pass_fds:
1203 fds_to_keep = set(pass_fds)
1204 fds_to_keep.add(errpipe_write)
1205 self._close_all_but_a_sorted_few_fds(
1206 sorted(fds_to_keep))
1207 else:
1208 self._close_fds(but=errpipe_write)
1209
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001210
1211 if cwd is not None:
1212 os.chdir(cwd)
1213
1214 # This is a copy of Python/pythonrun.c
1215 # _Py_RestoreSignals(). If that were exposed
1216 # as a sys._py_restoresignals func it would be
1217 # better.. but this pure python implementation
1218 # isn't likely to be used much anymore.
1219 if restore_signals:
1220 signals = ('SIGPIPE', 'SIGXFZ', 'SIGXFSZ')
1221 for sig in signals:
1222 if hasattr(signal, sig):
1223 signal.signal(getattr(signal, sig),
1224 signal.SIG_DFL)
1225
1226 if start_new_session and hasattr(os, 'setsid'):
1227 os.setsid()
1228
1229 if preexec_fn:
1230 preexec_fn()
1231
1232 if env is None:
1233 os.execvp(executable, args)
1234 else:
1235 os.execvpe(executable, args, env)
1236
1237 except:
1238 try:
1239 exc_type, exc_value = sys.exc_info()[:2]
1240 if isinstance(exc_value, OSError):
Benjamin Petersonb8bc4392010-11-20 18:24:54 +00001241 errno_num = exc_value.errno
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001242 else:
Benjamin Petersonb8bc4392010-11-20 18:24:54 +00001243 errno_num = 0
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001244 message = '%s:%x:%s' % (exc_type.__name__,
Benjamin Petersonb8bc4392010-11-20 18:24:54 +00001245 errno_num, exc_value)
Victor Stinner4d078042010-04-23 19:28:32 +00001246 message = message.encode(errors="surrogatepass")
1247 os.write(errpipe_write, message)
1248 except Exception:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001249 # We MUST not allow anything odd happening
1250 # above to prevent us from exiting below.
1251 pass
1252
1253 # This exitcode won't be reported to applications
1254 # so it really doesn't matter what we return.
1255 os._exit(255)
1256
1257 # Parent
Facundo Batista10706e22009-06-19 20:34:30 +00001258 if gc_was_enabled:
1259 gc.enable()
Facundo Batista10706e22009-06-19 20:34:30 +00001260 finally:
1261 # be sure the FD is closed no matter what
1262 os.close(errpipe_write)
1263
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001264 if p2cread != -1 and p2cwrite != -1:
Facundo Batista10706e22009-06-19 20:34:30 +00001265 os.close(p2cread)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001266 if c2pwrite != -1 and c2pread != -1:
Facundo Batista10706e22009-06-19 20:34:30 +00001267 os.close(c2pwrite)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001268 if errwrite != -1 and errread != -1:
Facundo Batista10706e22009-06-19 20:34:30 +00001269 os.close(errwrite)
1270
1271 # Wait for exec to fail or succeed; possibly raising an
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001272 # exception (limited in size)
1273 data = bytearray()
1274 while True:
1275 part = _eintr_retry_call(os.read, errpipe_read, 50000)
1276 data += part
1277 if not part or len(data) > 50000:
1278 break
Facundo Batista10706e22009-06-19 20:34:30 +00001279 finally:
1280 # be sure the FD is closed no matter what
1281 os.close(errpipe_read)
1282
Guido van Rossumaf2362a2007-05-15 22:32:02 +00001283 if data:
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001284 _eintr_retry_call(os.waitpid, self.pid, 0)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001285 try:
1286 exception_name, hex_errno, err_msg = data.split(b':', 2)
1287 except ValueError:
1288 print('Bad exception data:', repr(data))
1289 exception_name = b'RuntimeError'
1290 hex_errno = b'0'
1291 err_msg = b'Unknown'
1292 child_exception_type = getattr(
1293 builtins, exception_name.decode('ascii'),
1294 RuntimeError)
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001295 for fd in (p2cwrite, c2pread, errread):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001296 if fd != -1:
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001297 os.close(fd)
Victor Stinner4d078042010-04-23 19:28:32 +00001298 err_msg = err_msg.decode(errors="surrogatepass")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001299 if issubclass(child_exception_type, OSError) and hex_errno:
Benjamin Petersonb8bc4392010-11-20 18:24:54 +00001300 errno_num = int(hex_errno, 16)
1301 if errno_num != 0:
1302 err_msg = os.strerror(errno_num)
1303 if errno_num == errno.ENOENT:
Benjamin Peterson5f780402010-11-20 18:07:52 +00001304 err_msg += ': ' + repr(args[0])
Benjamin Petersonb8bc4392010-11-20 18:24:54 +00001305 raise child_exception_type(errno_num, err_msg)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001306 raise child_exception_type(err_msg)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001307
1308
Brett Cannon84df1e62010-05-14 00:33:40 +00001309 def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED,
1310 _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED,
1311 _WEXITSTATUS=os.WEXITSTATUS):
1312 # This method is called (indirectly) by __del__, so it cannot
1313 # refer to anything outside of its local scope."""
1314 if _WIFSIGNALED(sts):
1315 self.returncode = -_WTERMSIG(sts)
1316 elif _WIFEXITED(sts):
1317 self.returncode = _WEXITSTATUS(sts)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001318 else:
1319 # Should never happen
1320 raise RuntimeError("Unknown child exit status!")
1321
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001322
Brett Cannon84df1e62010-05-14 00:33:40 +00001323 def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid,
1324 _WNOHANG=os.WNOHANG, _os_error=os.error):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001325 """Check if child process has terminated. Returns returncode
Brett Cannon84df1e62010-05-14 00:33:40 +00001326 attribute.
1327
1328 This method is called by __del__, so it cannot reference anything
1329 outside of the local scope (nor can any methods it calls).
1330
1331 """
Peter Astrandd38ddf42005-02-10 08:32:50 +00001332 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001333 try:
Brett Cannon84df1e62010-05-14 00:33:40 +00001334 pid, sts = _waitpid(self.pid, _WNOHANG)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001335 if pid == self.pid:
1336 self._handle_exitstatus(sts)
Brett Cannon84df1e62010-05-14 00:33:40 +00001337 except _os_error:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001338 if _deadstate is not None:
1339 self.returncode = _deadstate
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001340 return self.returncode
1341
1342
1343 def wait(self):
1344 """Wait for child process to terminate. Returns returncode
1345 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001346 if self.returncode is None:
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001347 pid, sts = _eintr_retry_call(os.waitpid, self.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001348 self._handle_exitstatus(sts)
1349 return self.returncode
1350
1351
Peter Astrand23109f02005-03-03 20:28:59 +00001352 def _communicate(self, input):
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001353 if self.stdin:
1354 # Flush stdio buffer. This might block, if the user has
1355 # been writing to .stdin in an uncontrolled fashion.
1356 self.stdin.flush()
1357 if not input:
1358 self.stdin.close()
1359
1360 if _has_poll:
1361 stdout, stderr = self._communicate_with_poll(input)
1362 else:
1363 stdout, stderr = self._communicate_with_select(input)
1364
1365 # All data exchanged. Translate lists into strings.
1366 if stdout is not None:
1367 stdout = b''.join(stdout)
1368 if stderr is not None:
1369 stderr = b''.join(stderr)
1370
1371 # Translate newlines, if requested.
1372 # This also turns bytes into strings.
1373 if self.universal_newlines:
1374 if stdout is not None:
1375 stdout = self._translate_newlines(stdout,
1376 self.stdout.encoding)
1377 if stderr is not None:
1378 stderr = self._translate_newlines(stderr,
1379 self.stderr.encoding)
1380
1381 self.wait()
1382 return (stdout, stderr)
1383
1384
1385 def _communicate_with_poll(self, input):
1386 stdout = None # Return
1387 stderr = None # Return
1388 fd2file = {}
1389 fd2output = {}
1390
1391 poller = select.poll()
1392 def register_and_append(file_obj, eventmask):
1393 poller.register(file_obj.fileno(), eventmask)
1394 fd2file[file_obj.fileno()] = file_obj
1395
1396 def close_unregister_and_remove(fd):
1397 poller.unregister(fd)
1398 fd2file[fd].close()
1399 fd2file.pop(fd)
1400
1401 if self.stdin and input:
1402 register_and_append(self.stdin, select.POLLOUT)
1403
1404 select_POLLIN_POLLPRI = select.POLLIN | select.POLLPRI
1405 if self.stdout:
1406 register_and_append(self.stdout, select_POLLIN_POLLPRI)
1407 fd2output[self.stdout.fileno()] = stdout = []
1408 if self.stderr:
1409 register_and_append(self.stderr, select_POLLIN_POLLPRI)
1410 fd2output[self.stderr.fileno()] = stderr = []
1411
1412 input_offset = 0
1413 while fd2file:
1414 try:
1415 ready = poller.poll()
1416 except select.error as e:
1417 if e.args[0] == errno.EINTR:
1418 continue
1419 raise
1420
1421 # XXX Rewrite these to use non-blocking I/O on the
1422 # file objects; they are no longer using C stdio!
1423
1424 for fd, mode in ready:
1425 if mode & select.POLLOUT:
1426 chunk = input[input_offset : input_offset + _PIPE_BUF]
1427 input_offset += os.write(fd, chunk)
1428 if input_offset >= len(input):
1429 close_unregister_and_remove(fd)
1430 elif mode & select_POLLIN_POLLPRI:
1431 data = os.read(fd, 4096)
1432 if not data:
1433 close_unregister_and_remove(fd)
1434 fd2output[fd].append(data)
1435 else:
1436 # Ignore hang up or errors.
1437 close_unregister_and_remove(fd)
1438
1439 return (stdout, stderr)
1440
1441
1442 def _communicate_with_select(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001443 read_set = []
1444 write_set = []
1445 stdout = None # Return
1446 stderr = None # Return
1447
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001448 if self.stdin and input:
1449 write_set.append(self.stdin)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001450 if self.stdout:
1451 read_set.append(self.stdout)
Tim Peterse718f612004-10-12 21:51:32 +00001452 stdout = []
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001453 if self.stderr:
1454 read_set.append(self.stderr)
1455 stderr = []
1456
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001457 input_offset = 0
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001458 while read_set or write_set:
Georg Brandl86b2fb92008-07-16 03:43:04 +00001459 try:
1460 rlist, wlist, xlist = select.select(read_set, write_set, [])
1461 except select.error as e:
1462 if e.args[0] == errno.EINTR:
1463 continue
1464 raise
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001465
Guido van Rossum98297ee2007-11-06 21:34:58 +00001466 # XXX Rewrite these to use non-blocking I/O on the
1467 # file objects; they are no longer using C stdio!
1468
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001469 if self.stdin in wlist:
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001470 chunk = input[input_offset : input_offset + _PIPE_BUF]
Guido van Rossumbae07c92007-10-08 02:46:15 +00001471 bytes_written = os.write(self.stdin.fileno(), chunk)
Thomas Wouters9fe394c2007-02-05 01:24:16 +00001472 input_offset += bytes_written
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001473 if input_offset >= len(input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001474 self.stdin.close()
1475 write_set.remove(self.stdin)
1476
1477 if self.stdout in rlist:
1478 data = os.read(self.stdout.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001479 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001480 self.stdout.close()
1481 read_set.remove(self.stdout)
1482 stdout.append(data)
1483
1484 if self.stderr in rlist:
1485 data = os.read(self.stderr.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001486 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001487 self.stderr.close()
1488 read_set.remove(self.stderr)
1489 stderr.append(data)
1490
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001491 return (stdout, stderr)
1492
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001493
Christian Heimesa342c012008-04-20 21:01:16 +00001494 def send_signal(self, sig):
1495 """Send a signal to the process
1496 """
1497 os.kill(self.pid, sig)
1498
1499 def terminate(self):
1500 """Terminate the process with SIGTERM
1501 """
1502 self.send_signal(signal.SIGTERM)
1503
1504 def kill(self):
1505 """Kill the process with SIGKILL
1506 """
1507 self.send_signal(signal.SIGKILL)
1508
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001509
1510def _demo_posix():
1511 #
1512 # Example 1: Simple redirection: Get process list
1513 #
1514 plist = Popen(["ps"], stdout=PIPE).communicate()[0]
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001515 print("Process list:")
1516 print(plist)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001517
1518 #
1519 # Example 2: Change uid before executing child
1520 #
1521 if os.getuid() == 0:
1522 p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1523 p.wait()
1524
1525 #
1526 # Example 3: Connecting several subprocesses
1527 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001528 print("Looking for 'hda'...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001529 p1 = Popen(["dmesg"], stdout=PIPE)
1530 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001531 print(repr(p2.communicate()[0]))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001532
1533 #
1534 # Example 4: Catch execution error
1535 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001536 print()
1537 print("Trying a weird file...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001538 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001539 print(Popen(["/this/path/does/not/exist"]).communicate())
Guido van Rossumb940e112007-01-10 16:19:56 +00001540 except OSError as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001541 if e.errno == errno.ENOENT:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001542 print("The file didn't exist. I thought so...")
1543 print("Child traceback:")
1544 print(e.child_traceback)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001545 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001546 print("Error", e.errno)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001547 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001548 print("Gosh. No error.", file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001549
1550
1551def _demo_windows():
1552 #
1553 # Example 1: Connecting several subprocesses
1554 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001555 print("Looking for 'PROMPT' in set output...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001556 p1 = Popen("set", stdout=PIPE, shell=True)
1557 p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001558 print(repr(p2.communicate()[0]))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001559
1560 #
1561 # Example 2: Simple execution of program
1562 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001563 print("Executing calc...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001564 p = Popen("calc")
1565 p.wait()
1566
1567
1568if __name__ == "__main__":
1569 if mswindows:
1570 _demo_windows()
1571 else:
1572 _demo_posix()