blob: 5aee34df5424b4753abe1f19612cfcedc0fa06de [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 Astrandc26516b2005-02-21 08:13:02 +00005# This module should remain compatible with Python 2.2, see PEP 291.
6#
Peter Astrand3a708df2005-09-23 17:37:29 +00007# Copyright (c) 2003-2005 by Peter Astrand <astrand@lysator.liu.se>
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00008#
Peter Astrand69bf13f2005-02-14 08:56:32 +00009# Licensed to PSF under a Contributor Agreement.
Peter Astrand3a708df2005-09-23 17:37:29 +000010# See http://www.python.org/2.4/license for licensing details.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000011
Raymond Hettinger837dd932004-10-17 16:36:53 +000012r"""subprocess - Subprocesses with accessible I/O streams
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000013
Fredrik Lundh15aaacc2004-10-17 14:47:05 +000014This module allows you to spawn processes, connect to their
15input/output/error pipes, and obtain their return codes. This module
16intends to replace several other, older modules and functions, like:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000017
18os.system
19os.spawn*
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000020commands.*
21
22Information about how the subprocess module can be used to replace these
23modules and functions can be found below.
24
25
26
27Using the subprocess module
28===========================
29This module defines one class called Popen:
30
31class Popen(args, bufsize=0, executable=None,
32 stdin=None, stdout=None, stderr=None,
33 preexec_fn=None, close_fds=False, shell=False,
34 cwd=None, env=None, universal_newlines=False,
35 startupinfo=None, creationflags=0):
36
37
38Arguments are:
39
40args should be a string, or a sequence of program arguments. The
41program to execute is normally the first item in the args sequence or
42string, but can be explicitly set by using the executable argument.
43
44On UNIX, with shell=False (default): In this case, the Popen class
45uses os.execvp() to execute the child program. args should normally
46be a sequence. A string will be treated as a sequence with the string
47as the only item (the program to execute).
48
49On UNIX, with shell=True: If args is a string, it specifies the
50command string to execute through the shell. If args is a sequence,
51the first item specifies the command string, and any additional items
52will be treated as additional shell arguments.
53
54On Windows: the Popen class uses CreateProcess() to execute the child
55program, which operates on strings. If args is a sequence, it will be
56converted to a string using the list2cmdline method. Please note that
57not all MS Windows applications interpret the command line the same
58way: The list2cmdline is designed for applications using the same
59rules as the MS C runtime.
60
61bufsize, if given, has the same meaning as the corresponding argument
62to the built-in open() function: 0 means unbuffered, 1 means line
63buffered, any other positive value means use a buffer of
64(approximately) that size. A negative bufsize means to use the system
65default, which usually means fully buffered. The default value for
66bufsize is 0 (unbuffered).
67
68stdin, stdout and stderr specify the executed programs' standard
69input, standard output and standard error file handles, respectively.
70Valid values are PIPE, an existing file descriptor (a positive
71integer), an existing file object, and None. PIPE indicates that a
72new pipe to the child should be created. With None, no redirection
73will occur; the child's file handles will be inherited from the
74parent. Additionally, stderr can be STDOUT, which indicates that the
75stderr data from the applications should be captured into the same
76file handle as for stdout.
77
78If preexec_fn is set to a callable object, this object will be called
79in the child process just before the child is executed.
80
81If close_fds is true, all file descriptors except 0, 1 and 2 will be
82closed before the child process is executed.
83
84if shell is true, the specified command will be executed through the
85shell.
86
87If cwd is not None, the current directory will be changed to cwd
88before the child is executed.
89
90If env is not None, it defines the environment variables for the new
91process.
92
93If universal_newlines is true, the file objects stdout and stderr are
94opened as a text files, but lines may be terminated by any of '\n',
95the Unix end-of-line convention, '\r', the Macintosh convention or
96'\r\n', the Windows convention. All of these external representations
97are seen as '\n' by the Python program. Note: This feature is only
98available if Python is built with universal newline support (the
99default). Also, the newlines attribute of the file objects stdout,
100stdin and stderr are not updated by the communicate() method.
101
102The startupinfo and creationflags, if given, will be passed to the
103underlying CreateProcess() function. They can specify things such as
104appearance of the main window and priority for the new process.
105(Windows only)
106
107
108This module also defines two shortcut functions:
109
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
Thomas Wouters0e3f5912006-08-11 14:57:12 +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
128Exceptions
129----------
130Exceptions raised in the child process, before the new program has
131started to execute, will be re-raised in the parent. Additionally,
132the exception object will have one extra attribute called
133'child_traceback', which is a string containing traceback information
134from the childs point of view.
135
136The most common exception raised is OSError. This occurs, for
137example, when trying to execute a non-existent file. Applications
138should prepare for OSErrors.
139
140A ValueError will be raised if Popen is called with invalid arguments.
141
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000142check_call() will raise CalledProcessError, if the called process
143returns a non-zero return code.
Peter Astrand454f7672005-01-01 09:36:35 +0000144
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000145
146Security
147--------
148Unlike some other popen functions, this implementation will never call
149/bin/sh implicitly. This means that all characters, including shell
150metacharacters, can safely be passed to child processes.
151
152
153Popen objects
154=============
155Instances of the Popen class have the following methods:
156
157poll()
158 Check if child process has terminated. Returns returncode
159 attribute.
160
161wait()
162 Wait for child process to terminate. Returns returncode attribute.
163
164communicate(input=None)
165 Interact with process: Send data to stdin. Read data from stdout
166 and stderr, until end-of-file is reached. Wait for process to
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000167 terminate. The optional input argument should be a string to be
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000168 sent to the child process, or None, if no data should be sent to
169 the child.
Tim Peterse718f612004-10-12 21:51:32 +0000170
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000171 communicate() returns a tuple (stdout, stderr).
172
173 Note: The data read is buffered in memory, so do not use this
174 method if the data size is large or unlimited.
175
176The following attributes are also available:
177
178stdin
179 If the stdin argument is PIPE, this attribute is a file object
180 that provides input to the child process. Otherwise, it is None.
181
182stdout
183 If the stdout argument is PIPE, this attribute is a file object
184 that provides output from the child process. Otherwise, it is
185 None.
186
187stderr
188 If the stderr argument is PIPE, this attribute is file object that
189 provides error output from the child process. Otherwise, it is
190 None.
191
192pid
193 The process ID of the child process.
194
195returncode
196 The child return code. A None value indicates that the process
197 hasn't terminated yet. A negative value -N indicates that the
198 child was terminated by signal N (UNIX only).
199
200
201Replacing older functions with the subprocess module
202====================================================
203In this section, "a ==> b" means that b can be used as a replacement
204for a.
205
206Note: All functions in this section fail (more or less) silently if
207the executed program cannot be found; this module raises an OSError
208exception.
209
210In the following examples, we assume that the subprocess module is
211imported with "from subprocess import *".
212
213
214Replacing /bin/sh shell backquote
215---------------------------------
216output=`mycmd myarg`
217==>
218output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
219
220
221Replacing shell pipe line
222-------------------------
223output=`dmesg | grep hda`
224==>
225p1 = Popen(["dmesg"], stdout=PIPE)
Peter Astrand6fdf3cb2004-11-30 18:06:42 +0000226p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000227output = p2.communicate()[0]
228
229
230Replacing os.system()
231---------------------
232sts = os.system("mycmd" + " myarg")
233==>
234p = Popen("mycmd" + " myarg", shell=True)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000235pid, sts = os.waitpid(p.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000236
237Note:
238
239* Calling the program through the shell is usually not required.
240
241* It's easier to look at the returncode attribute than the
242 exitstatus.
243
244A more real-world example would look like this:
245
246try:
247 retcode = call("mycmd" + " myarg", shell=True)
248 if retcode < 0:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000249 print("Child was terminated by signal", -retcode, file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000250 else:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000251 print("Child returned", retcode, file=sys.stderr)
252except OSError as e:
253 print("Execution failed:", e, file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000254
255
256Replacing os.spawn*
257-------------------
Tim Peterse718f612004-10-12 21:51:32 +0000258P_NOWAIT example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000259
260pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
261==>
262pid = Popen(["/bin/mycmd", "myarg"]).pid
263
264
265P_WAIT example:
266
267retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
268==>
269retcode = call(["/bin/mycmd", "myarg"])
270
271
Tim Peterse718f612004-10-12 21:51:32 +0000272Vector example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000273
274os.spawnvp(os.P_NOWAIT, path, args)
275==>
276Popen([path] + args[1:])
277
278
Tim Peterse718f612004-10-12 21:51:32 +0000279Environment example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000280
281os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
282==>
283Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000284"""
285
286import sys
287mswindows = (sys.platform == "win32")
288
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000289import io
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000290import os
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000291import traceback
Christian Heimesfdab48e2008-01-20 09:06:41 +0000292import gc
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000293
Peter Astrand454f7672005-01-01 09:36:35 +0000294# Exception classes used by this module.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000295class CalledProcessError(Exception):
Peter Astrand454f7672005-01-01 09:36:35 +0000296 """This exception is raised when a process run by check_call() returns
297 a non-zero exit status. The exit status will be stored in the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000298 returncode attribute."""
299 def __init__(self, returncode, cmd):
300 self.returncode = returncode
301 self.cmd = cmd
302 def __str__(self):
303 return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
304
Peter Astrand454f7672005-01-01 09:36:35 +0000305
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000306if mswindows:
307 import threading
308 import msvcrt
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000309 if 0: # <-- change this to use pywin32 instead of the _subprocess driver
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000310 import pywintypes
Tim Peterse8374a52004-10-13 03:15:00 +0000311 from win32api import GetStdHandle, STD_INPUT_HANDLE, \
312 STD_OUTPUT_HANDLE, STD_ERROR_HANDLE
313 from win32api import GetCurrentProcess, DuplicateHandle, \
314 GetModuleFileName, GetVersion
Peter Astrandc1d65362004-11-07 14:30:34 +0000315 from win32con import DUPLICATE_SAME_ACCESS, SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000316 from win32pipe import CreatePipe
Tim Peterse8374a52004-10-13 03:15:00 +0000317 from win32process import CreateProcess, STARTUPINFO, \
318 GetExitCodeProcess, STARTF_USESTDHANDLES, \
Peter Astrandc1d65362004-11-07 14:30:34 +0000319 STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000320 from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000321 else:
322 from _subprocess import *
323 class STARTUPINFO:
324 dwFlags = 0
325 hStdInput = None
326 hStdOutput = None
327 hStdError = None
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000328 wShowWindow = 0
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000329 class pywintypes:
330 error = IOError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000331else:
332 import select
333 import errno
334 import fcntl
335 import pickle
336
Peter Astrand454f7672005-01-01 09:36:35 +0000337__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "CalledProcessError"]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000338
339try:
340 MAXFD = os.sysconf("SC_OPEN_MAX")
341except:
342 MAXFD = 256
343
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000344_active = []
345
346def _cleanup():
347 for inst in _active[:]:
Christian Heimesa37d4c62007-12-04 23:02:19 +0000348 res = inst.poll(_deadstate=sys.maxsize)
Guido van Rossumb5d47ef2006-08-24 02:27:45 +0000349 if res is not None and res >= 0:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000350 try:
351 _active.remove(inst)
352 except ValueError:
353 # This can happen if two threads create a new Popen instance.
354 # It's harmless that it was already removed, so ignore.
355 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000356
357PIPE = -1
358STDOUT = -2
359
360
Peter Astrand5f5e1412004-12-05 20:15:36 +0000361def call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000362 """Run command with arguments. Wait for command to complete, then
363 return the returncode attribute.
364
365 The arguments are the same as for the Popen constructor. Example:
366
367 retcode = call(["ls", "-l"])
368 """
Peter Astrand5f5e1412004-12-05 20:15:36 +0000369 return Popen(*popenargs, **kwargs).wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000370
371
Peter Astrand454f7672005-01-01 09:36:35 +0000372def check_call(*popenargs, **kwargs):
373 """Run command with arguments. Wait for command to complete. If
374 the exit code was zero then return, otherwise raise
375 CalledProcessError. The CalledProcessError object will have the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000376 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000377
378 The arguments are the same as for the Popen constructor. Example:
379
380 check_call(["ls", "-l"])
381 """
382 retcode = call(*popenargs, **kwargs)
383 cmd = kwargs.get("args")
384 if cmd is None:
385 cmd = popenargs[0]
386 if retcode:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000387 raise CalledProcessError(retcode, cmd)
Peter Astrand454f7672005-01-01 09:36:35 +0000388 return retcode
389
390
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000391def list2cmdline(seq):
392 """
393 Translate a sequence of arguments into a command line
394 string, using the same rules as the MS C runtime:
395
396 1) Arguments are delimited by white space, which is either a
397 space or a tab.
398
399 2) A string surrounded by double quotation marks is
400 interpreted as a single argument, regardless of white space
Christian Heimesfdab48e2008-01-20 09:06:41 +0000401 or pipe characters contained within. A quoted string can be
402 embedded in an argument.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000403
404 3) A double quotation mark preceded by a backslash is
405 interpreted as a literal double quotation mark.
406
407 4) Backslashes are interpreted literally, unless they
408 immediately precede a double quotation mark.
409
410 5) If backslashes immediately precede a double quotation mark,
411 every pair of backslashes is interpreted as a literal
412 backslash. If the number of backslashes is odd, the last
413 backslash escapes the next double quotation mark as
414 described in rule 3.
415 """
416
417 # See
418 # http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp
419 result = []
420 needquote = False
421 for arg in seq:
422 bs_buf = []
423
424 # Add a space to separate this argument from the others
425 if result:
426 result.append(' ')
427
Christian Heimesfdab48e2008-01-20 09:06:41 +0000428 needquote = (" " in arg) or ("\t" in arg) or ("|" in arg) or not arg
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000429 if needquote:
430 result.append('"')
431
432 for c in arg:
433 if c == '\\':
Tim Peterse718f612004-10-12 21:51:32 +0000434 # Don't know if we need to double yet.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000435 bs_buf.append(c)
436 elif c == '"':
Christian Heimesfdab48e2008-01-20 09:06:41 +0000437 # Double backslashes.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000438 result.append('\\' * len(bs_buf)*2)
439 bs_buf = []
440 result.append('\\"')
441 else:
442 # Normal char
443 if bs_buf:
444 result.extend(bs_buf)
445 bs_buf = []
446 result.append(c)
447
Christian Heimesfdab48e2008-01-20 09:06:41 +0000448 # Add remaining backslashes, if any.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000449 if bs_buf:
450 result.extend(bs_buf)
451
452 if needquote:
Peter Astrand7e78ade2005-03-03 21:10:23 +0000453 result.extend(bs_buf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000454 result.append('"')
455
456 return ''.join(result)
457
458
459class Popen(object):
460 def __init__(self, args, bufsize=0, executable=None,
461 stdin=None, stdout=None, stderr=None,
462 preexec_fn=None, close_fds=False, shell=False,
463 cwd=None, env=None, universal_newlines=False,
464 startupinfo=None, creationflags=0):
465 """Create new Popen instance."""
466 _cleanup()
467
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000468 self._child_created = False
Guido van Rossum46a05a72007-06-07 21:56:45 +0000469 if bufsize is None:
470 bufsize = 0 # Restore default
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000471 if not isinstance(bufsize, int):
Peter Astrand738131d2004-11-30 21:04:45 +0000472 raise TypeError("bufsize must be an integer")
473
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000474 if mswindows:
Tim Peterse8374a52004-10-13 03:15:00 +0000475 if preexec_fn is not None:
476 raise ValueError("preexec_fn is not supported on Windows "
477 "platforms")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000478 if close_fds and (stdin is not None or stdout is not None or
479 stderr is not None):
Tim Peterse8374a52004-10-13 03:15:00 +0000480 raise ValueError("close_fds is not supported on Windows "
Guido van Rossume7ba4952007-06-06 23:52:48 +0000481 "platforms if you redirect stdin/stdout/stderr")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000482 else:
483 # POSIX
Tim Peterse8374a52004-10-13 03:15:00 +0000484 if startupinfo is not None:
485 raise ValueError("startupinfo is only supported on Windows "
486 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000487 if creationflags != 0:
Tim Peterse8374a52004-10-13 03:15:00 +0000488 raise ValueError("creationflags is only supported on Windows "
489 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000490
Tim Peterse718f612004-10-12 21:51:32 +0000491 self.stdin = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000492 self.stdout = None
493 self.stderr = None
494 self.pid = None
495 self.returncode = None
496 self.universal_newlines = universal_newlines
497
498 # Input and output objects. The general principle is like
499 # this:
500 #
501 # Parent Child
502 # ------ -----
503 # p2cwrite ---stdin---> p2cread
504 # c2pread <--stdout--- c2pwrite
505 # errread <--stderr--- errwrite
506 #
507 # On POSIX, the child objects are file descriptors. On
508 # Windows, these are Windows file handles. The parent objects
509 # are file descriptors on both platforms. The parent objects
510 # are None when not using PIPEs. The child objects are None
511 # when not redirecting.
Tim Peterse718f612004-10-12 21:51:32 +0000512
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000513 (p2cread, p2cwrite,
514 c2pread, c2pwrite,
515 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
516
517 self._execute_child(args, executable, preexec_fn, close_fds,
518 cwd, env, universal_newlines,
519 startupinfo, creationflags, shell,
520 p2cread, p2cwrite,
521 c2pread, c2pwrite,
522 errread, errwrite)
523
Thomas Wouterscf297e42007-02-23 15:07:44 +0000524 # On Windows, you cannot just redirect one or two handles: You
525 # either have to redirect all three or none. If the subprocess
526 # user has only redirected one or two handles, we are
527 # automatically creating PIPEs for the rest. We should close
Guido van Rossumd8faa362007-04-27 19:54:29 +0000528 # these after the process is started. See bug #1124861.
Thomas Wouterscf297e42007-02-23 15:07:44 +0000529 if mswindows:
530 if stdin is None and p2cwrite is not None:
531 os.close(p2cwrite)
532 p2cwrite = None
533 if stdout is None and c2pread is not None:
534 os.close(c2pread)
535 c2pread = None
536 if stderr is None and errread is not None:
537 os.close(errread)
538 errread = None
539
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000540 if bufsize == 0:
541 bufsize = 1 # Nearly unbuffered (XXX for now)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000542 if p2cwrite is not None:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000543 self.stdin = io.open(p2cwrite, 'wb', bufsize)
544 if self.universal_newlines:
545 self.stdin = io.TextIOWrapper(self.stdin)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000546 if c2pread is not None:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000547 self.stdout = io.open(c2pread, 'rb', bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000548 if universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000549 self.stdout = io.TextIOWrapper(self.stdout)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000550 if errread is not None:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000551 self.stderr = io.open(errread, 'rb', bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000552 if universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000553 self.stderr = io.TextIOWrapper(self.stderr)
Tim Peterse718f612004-10-12 21:51:32 +0000554
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000555
Guido van Rossum98297ee2007-11-06 21:34:58 +0000556 def _translate_newlines(self, data, encoding):
557 data = data.replace(b"\r\n", b"\n").replace(b"\r", b"\n")
558 return data.decode(encoding)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000559
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000560
Guido van Rossumd8faa362007-04-27 19:54:29 +0000561 def __del__(self, sys=sys):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000562 if not self._child_created:
563 # We didn't get to successfully create a child process.
564 return
565 # In case the child hasn't been waited on, check if it's done.
Christian Heimesa37d4c62007-12-04 23:02:19 +0000566 self.poll(_deadstate=sys.maxsize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000567 if self.returncode is None and _active is not None:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000568 # Child is still running, keep us alive until we can wait on it.
569 _active.append(self)
570
571
Peter Astrand23109f02005-03-03 20:28:59 +0000572 def communicate(self, input=None):
573 """Interact with process: Send data to stdin. Read data from
574 stdout and stderr, until end-of-file is reached. Wait for
575 process to terminate. The optional input argument should be a
576 string to be sent to the child process, or None, if no data
577 should be sent to the child.
Tim Peterseba28be2005-03-28 01:08:02 +0000578
Peter Astrand23109f02005-03-03 20:28:59 +0000579 communicate() returns a tuple (stdout, stderr)."""
580
581 # Optimization: If we are only using one pipe, or no pipe at
582 # all, using select() or threads is unnecessary.
583 if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
Tim Peterseba28be2005-03-28 01:08:02 +0000584 stdout = None
585 stderr = None
Peter Astrand23109f02005-03-03 20:28:59 +0000586 if self.stdin:
587 if input:
588 self.stdin.write(input)
589 self.stdin.close()
590 elif self.stdout:
591 stdout = self.stdout.read()
592 elif self.stderr:
593 stderr = self.stderr.read()
594 self.wait()
595 return (stdout, stderr)
Tim Peterseba28be2005-03-28 01:08:02 +0000596
Peter Astrand23109f02005-03-03 20:28:59 +0000597 return self._communicate(input)
598
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000599
600 if mswindows:
601 #
602 # Windows methods
603 #
604 def _get_handles(self, stdin, stdout, stderr):
605 """Construct and return tupel with IO objects:
606 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
607 """
Peter Astrandd38ddf42005-02-10 08:32:50 +0000608 if stdin is None and stdout is None and stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000609 return (None, None, None, None, None, None)
Tim Peterse718f612004-10-12 21:51:32 +0000610
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000611 p2cread, p2cwrite = None, None
612 c2pread, c2pwrite = None, None
613 errread, errwrite = None, None
614
Peter Astrandd38ddf42005-02-10 08:32:50 +0000615 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000616 p2cread = GetStdHandle(STD_INPUT_HANDLE)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000617 if p2cread is not None:
618 pass
619 elif stdin is None or stdin == PIPE:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000620 p2cread, p2cwrite = CreatePipe(None, 0)
621 # Detach and turn into fd
622 p2cwrite = p2cwrite.Detach()
623 p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000624 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000625 p2cread = msvcrt.get_osfhandle(stdin)
626 else:
627 # Assuming file-like object
628 p2cread = msvcrt.get_osfhandle(stdin.fileno())
629 p2cread = self._make_inheritable(p2cread)
630
Peter Astrandd38ddf42005-02-10 08:32:50 +0000631 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000632 c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000633 if c2pwrite is not None:
634 pass
635 elif stdout is None or stdout == PIPE:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000636 c2pread, c2pwrite = CreatePipe(None, 0)
637 # Detach and turn into fd
638 c2pread = c2pread.Detach()
639 c2pread = msvcrt.open_osfhandle(c2pread, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000640 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000641 c2pwrite = msvcrt.get_osfhandle(stdout)
642 else:
643 # Assuming file-like object
644 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
645 c2pwrite = self._make_inheritable(c2pwrite)
646
Peter Astrandd38ddf42005-02-10 08:32:50 +0000647 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000648 errwrite = GetStdHandle(STD_ERROR_HANDLE)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000649 if errwrite is not None:
650 pass
651 elif stderr is None or stderr == PIPE:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000652 errread, errwrite = CreatePipe(None, 0)
653 # Detach and turn into fd
654 errread = errread.Detach()
655 errread = msvcrt.open_osfhandle(errread, 0)
656 elif stderr == STDOUT:
657 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000658 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000659 errwrite = msvcrt.get_osfhandle(stderr)
660 else:
661 # Assuming file-like object
662 errwrite = msvcrt.get_osfhandle(stderr.fileno())
663 errwrite = self._make_inheritable(errwrite)
664
665 return (p2cread, p2cwrite,
666 c2pread, c2pwrite,
667 errread, errwrite)
668
669
670 def _make_inheritable(self, handle):
671 """Return a duplicate of handle, which is inheritable"""
672 return DuplicateHandle(GetCurrentProcess(), handle,
673 GetCurrentProcess(), 0, 1,
674 DUPLICATE_SAME_ACCESS)
675
676
677 def _find_w9xpopen(self):
678 """Find and return absolut path to w9xpopen.exe"""
Tim Peterse8374a52004-10-13 03:15:00 +0000679 w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)),
680 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000681 if not os.path.exists(w9xpopen):
682 # Eeek - file-not-found - possibly an embedding
683 # situation - see if we can locate it in sys.exec_prefix
Tim Peterse8374a52004-10-13 03:15:00 +0000684 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
685 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000686 if not os.path.exists(w9xpopen):
Tim Peterse8374a52004-10-13 03:15:00 +0000687 raise RuntimeError("Cannot locate w9xpopen.exe, which is "
688 "needed for Popen to work with your "
689 "shell or platform.")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000690 return w9xpopen
691
Tim Peterse718f612004-10-12 21:51:32 +0000692
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000693 def _execute_child(self, args, executable, preexec_fn, close_fds,
694 cwd, env, universal_newlines,
695 startupinfo, creationflags, shell,
696 p2cread, p2cwrite,
697 c2pread, c2pwrite,
698 errread, errwrite):
699 """Execute program (MS Windows version)"""
700
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000701 if not isinstance(args, str):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000702 args = list2cmdline(args)
703
Peter Astrandc1d65362004-11-07 14:30:34 +0000704 # Process startup details
Peter Astrandd38ddf42005-02-10 08:32:50 +0000705 if startupinfo is None:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000706 startupinfo = STARTUPINFO()
707 if None not in (p2cread, c2pwrite, errwrite):
Peter Astrandc1d65362004-11-07 14:30:34 +0000708 startupinfo.dwFlags |= STARTF_USESTDHANDLES
709 startupinfo.hStdInput = p2cread
710 startupinfo.hStdOutput = c2pwrite
711 startupinfo.hStdError = errwrite
712
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000713 if shell:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000714 startupinfo.dwFlags |= STARTF_USESHOWWINDOW
715 startupinfo.wShowWindow = SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000716 comspec = os.environ.get("COMSPEC", "cmd.exe")
717 args = comspec + " /c " + args
Guido van Rossume2a383d2007-01-15 16:59:06 +0000718 if (GetVersion() >= 0x80000000 or
Tim Peterse8374a52004-10-13 03:15:00 +0000719 os.path.basename(comspec).lower() == "command.com"):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000720 # Win9x, or using command.com on NT. We need to
721 # use the w9xpopen intermediate program. For more
722 # information, see KB Q150956
723 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
724 w9xpopen = self._find_w9xpopen()
725 args = '"%s" %s' % (w9xpopen, args)
726 # Not passing CREATE_NEW_CONSOLE has been known to
727 # cause random failures on win9x. Specifically a
728 # dialog: "Your program accessed mem currently in
729 # use at xxx" and a hopeful warning about the
730 # stability of your system. Cost is Ctrl+C wont
731 # kill children.
732 creationflags |= CREATE_NEW_CONSOLE
733
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000734 # Start the process
735 try:
736 hp, ht, pid, tid = CreateProcess(executable, args,
Tim Peterse8374a52004-10-13 03:15:00 +0000737 # no special security
738 None, None,
Guido van Rossume7ba4952007-06-06 23:52:48 +0000739 int(not close_fds),
Tim Peterse8374a52004-10-13 03:15:00 +0000740 creationflags,
741 env,
742 cwd,
743 startupinfo)
Guido van Rossumb940e112007-01-10 16:19:56 +0000744 except pywintypes.error as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000745 # Translate pywintypes.error to WindowsError, which is
746 # a subclass of OSError. FIXME: We should really
747 # translate errno using _sys_errlist (or simliar), but
748 # how can this be done from Python?
749 raise WindowsError(*e.args)
750
751 # Retain the process handle, but close the thread handle
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000752 self._child_created = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000753 self._handle = hp
754 self.pid = pid
755 ht.Close()
756
Andrew M. Kuchling51ee66e2004-10-12 16:38:42 +0000757 # Child is launched. Close the parent's copy of those pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000758 # handles that only the child should have open. You need
759 # to make sure that no handles to the write end of the
760 # output pipe are maintained in this process or else the
761 # pipe will not close when the child process exits and the
762 # ReadFile will hang.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000763 if p2cread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000764 p2cread.Close()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000765 if c2pwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000766 c2pwrite.Close()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000767 if errwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000768 errwrite.Close()
769
Tim Peterse718f612004-10-12 21:51:32 +0000770
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000771 def poll(self, _deadstate=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000772 """Check if child process has terminated. Returns returncode
773 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000774 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000775 if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
776 self.returncode = GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000777 return self.returncode
778
779
780 def wait(self):
781 """Wait for child process to terminate. Returns returncode
782 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000783 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000784 obj = WaitForSingleObject(self._handle, INFINITE)
785 self.returncode = GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000786 return self.returncode
787
788
789 def _readerthread(self, fh, buffer):
790 buffer.append(fh.read())
791
792
Peter Astrand23109f02005-03-03 20:28:59 +0000793 def _communicate(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000794 stdout = None # Return
795 stderr = None # Return
796
797 if self.stdout:
798 stdout = []
Tim Peterse8374a52004-10-13 03:15:00 +0000799 stdout_thread = threading.Thread(target=self._readerthread,
800 args=(self.stdout, stdout))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000801 stdout_thread.setDaemon(True)
802 stdout_thread.start()
803 if self.stderr:
804 stderr = []
Tim Peterse8374a52004-10-13 03:15:00 +0000805 stderr_thread = threading.Thread(target=self._readerthread,
806 args=(self.stderr, stderr))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000807 stderr_thread.setDaemon(True)
808 stderr_thread.start()
809
810 if self.stdin:
Peter Astrandd38ddf42005-02-10 08:32:50 +0000811 if input is not None:
Guido van Rossumc12a8132007-10-26 04:29:23 +0000812 if isinstance(input, str):
813 input = input.encode()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000814 self.stdin.write(input)
815 self.stdin.close()
816
817 if self.stdout:
818 stdout_thread.join()
819 if self.stderr:
820 stderr_thread.join()
821
822 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000823 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000824 stdout = stdout[0]
Peter Astrandd38ddf42005-02-10 08:32:50 +0000825 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000826 stderr = stderr[0]
827
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000828 self.wait()
829 return (stdout, stderr)
830
831 else:
832 #
833 # POSIX methods
834 #
835 def _get_handles(self, stdin, stdout, stderr):
836 """Construct and return tupel with IO objects:
837 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
838 """
839 p2cread, p2cwrite = None, None
840 c2pread, c2pwrite = None, None
841 errread, errwrite = None, None
842
Peter Astrandd38ddf42005-02-10 08:32:50 +0000843 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000844 pass
845 elif stdin == PIPE:
846 p2cread, p2cwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000847 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000848 p2cread = stdin
849 else:
850 # Assuming file-like object
851 p2cread = stdin.fileno()
852
Peter Astrandd38ddf42005-02-10 08:32:50 +0000853 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000854 pass
855 elif stdout == PIPE:
856 c2pread, c2pwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000857 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000858 c2pwrite = stdout
859 else:
860 # Assuming file-like object
Tim Peterse718f612004-10-12 21:51:32 +0000861 c2pwrite = stdout.fileno()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000862
Peter Astrandd38ddf42005-02-10 08:32:50 +0000863 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000864 pass
865 elif stderr == PIPE:
866 errread, errwrite = os.pipe()
867 elif stderr == STDOUT:
868 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000869 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000870 errwrite = stderr
871 else:
872 # Assuming file-like object
873 errwrite = stderr.fileno()
874
875 return (p2cread, p2cwrite,
876 c2pread, c2pwrite,
877 errread, errwrite)
878
879
880 def _set_cloexec_flag(self, fd):
881 try:
882 cloexec_flag = fcntl.FD_CLOEXEC
883 except AttributeError:
884 cloexec_flag = 1
885
886 old = fcntl.fcntl(fd, fcntl.F_GETFD)
887 fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
888
889
890 def _close_fds(self, but):
Christian Heimesfdab48e2008-01-20 09:06:41 +0000891 os.closerange(3, but)
892 os.closerange(but + 1, MAXFD)
Tim Peterse718f612004-10-12 21:51:32 +0000893
894
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000895 def _execute_child(self, args, executable, preexec_fn, close_fds,
896 cwd, env, universal_newlines,
897 startupinfo, creationflags, shell,
898 p2cread, p2cwrite,
899 c2pread, c2pwrite,
900 errread, errwrite):
901 """Execute program (POSIX version)"""
902
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000903 if isinstance(args, str):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000904 args = [args]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000905 else:
906 args = list(args)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000907
908 if shell:
909 args = ["/bin/sh", "-c"] + args
910
Peter Astrandd38ddf42005-02-10 08:32:50 +0000911 if executable is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000912 executable = args[0]
913
914 # For transferring possible exec failure from child to parent
915 # The first char specifies the exception type: 0 means
916 # OSError, 1 means some other error.
917 errpipe_read, errpipe_write = os.pipe()
918 self._set_cloexec_flag(errpipe_write)
919
Christian Heimesfdab48e2008-01-20 09:06:41 +0000920 gc_was_enabled = gc.isenabled()
921 # Disable gc to avoid bug where gc -> file_dealloc ->
922 # write to stderr -> hang. http://bugs.python.org/issue1336
923 gc.disable()
924 try:
925 self.pid = os.fork()
926 except:
927 if gc_was_enabled:
928 gc.enable()
929 raise
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000930 self._child_created = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000931 if self.pid == 0:
932 # Child
933 try:
934 # Close parent's pipe ends
Thomas Wouterscf297e42007-02-23 15:07:44 +0000935 if p2cwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000936 os.close(p2cwrite)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000937 if c2pread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000938 os.close(c2pread)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000939 if errread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000940 os.close(errread)
941 os.close(errpipe_read)
942
943 # Dup fds for child
Thomas Wouterscf297e42007-02-23 15:07:44 +0000944 if p2cread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000945 os.dup2(p2cread, 0)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000946 if c2pwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000947 os.dup2(c2pwrite, 1)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000948 if errwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000949 os.dup2(errwrite, 2)
950
Thomas Wouters89f507f2006-12-13 04:49:30 +0000951 # Close pipe fds. Make sure we don't close the same
952 # fd more than once, or standard fds.
Thomas Wouterscf297e42007-02-23 15:07:44 +0000953 if p2cread is not None and p2cread not in (0,):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000954 os.close(p2cread)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000955 if c2pwrite is not None and c2pwrite not in (p2cread, 1):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000956 os.close(c2pwrite)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000957 if (errwrite is not None and
958 errwrite not in (p2cread, c2pwrite, 2)):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000959 os.close(errwrite)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000960
961 # Close all other fds, if asked for
962 if close_fds:
963 self._close_fds(but=errpipe_write)
964
Peter Astrandd38ddf42005-02-10 08:32:50 +0000965 if cwd is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000966 os.chdir(cwd)
967
968 if preexec_fn:
Neal Norwitzd9108552006-03-17 08:00:19 +0000969 preexec_fn()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000970
Peter Astrandd38ddf42005-02-10 08:32:50 +0000971 if env is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000972 os.execvp(executable, args)
973 else:
974 os.execvpe(executable, args, env)
975
976 except:
977 exc_type, exc_value, tb = sys.exc_info()
978 # Save the traceback and attach it to the exception object
Tim Peterse8374a52004-10-13 03:15:00 +0000979 exc_lines = traceback.format_exception(exc_type,
980 exc_value,
981 tb)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000982 exc_value.child_traceback = ''.join(exc_lines)
983 os.write(errpipe_write, pickle.dumps(exc_value))
984
985 # This exitcode won't be reported to applications, so it
986 # really doesn't matter what we return.
987 os._exit(255)
988
989 # Parent
Christian Heimesfdab48e2008-01-20 09:06:41 +0000990 if gc_was_enabled:
991 gc.enable()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000992 os.close(errpipe_write)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000993 if p2cread is not None and p2cwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000994 os.close(p2cread)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000995 if c2pwrite is not None and c2pread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000996 os.close(c2pwrite)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000997 if errwrite is not None and errread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000998 os.close(errwrite)
999
1000 # Wait for exec to fail or succeed; possibly raising exception
1001 data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB
1002 os.close(errpipe_read)
Guido van Rossumaf2362a2007-05-15 22:32:02 +00001003 if data:
Peter Astrandf791d7a2005-01-01 09:38:57 +00001004 os.waitpid(self.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001005 child_exception = pickle.loads(data)
1006 raise child_exception
1007
1008
1009 def _handle_exitstatus(self, sts):
1010 if os.WIFSIGNALED(sts):
1011 self.returncode = -os.WTERMSIG(sts)
1012 elif os.WIFEXITED(sts):
1013 self.returncode = os.WEXITSTATUS(sts)
1014 else:
1015 # Should never happen
1016 raise RuntimeError("Unknown child exit status!")
1017
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001018
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001019 def poll(self, _deadstate=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001020 """Check if child process has terminated. Returns returncode
1021 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001022 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001023 try:
1024 pid, sts = os.waitpid(self.pid, os.WNOHANG)
1025 if pid == self.pid:
1026 self._handle_exitstatus(sts)
1027 except os.error:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001028 if _deadstate is not None:
1029 self.returncode = _deadstate
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001030 return self.returncode
1031
1032
1033 def wait(self):
1034 """Wait for child process to terminate. Returns returncode
1035 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001036 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001037 pid, sts = os.waitpid(self.pid, 0)
1038 self._handle_exitstatus(sts)
1039 return self.returncode
1040
1041
Peter Astrand23109f02005-03-03 20:28:59 +00001042 def _communicate(self, input):
Guido van Rossumbae07c92007-10-08 02:46:15 +00001043 if self.stdin:
1044 if isinstance(input, str): # Unicode
1045 input = input.encode("utf-8") # XXX What else?
Guido van Rossum98297ee2007-11-06 21:34:58 +00001046 input = bytes(input)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001047 read_set = []
1048 write_set = []
1049 stdout = None # Return
1050 stderr = None # Return
1051
1052 if self.stdin:
1053 # Flush stdio buffer. This might block, if the user has
1054 # been writing to .stdin in an uncontrolled fashion.
1055 self.stdin.flush()
1056 if input:
1057 write_set.append(self.stdin)
1058 else:
1059 self.stdin.close()
1060 if self.stdout:
1061 read_set.append(self.stdout)
Tim Peterse718f612004-10-12 21:51:32 +00001062 stdout = []
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001063 if self.stderr:
1064 read_set.append(self.stderr)
1065 stderr = []
1066
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001067 input_offset = 0
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001068 while read_set or write_set:
1069 rlist, wlist, xlist = select.select(read_set, write_set, [])
1070
Guido van Rossum98297ee2007-11-06 21:34:58 +00001071 # XXX Rewrite these to use non-blocking I/O on the
1072 # file objects; they are no longer using C stdio!
1073
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001074 if self.stdin in wlist:
1075 # When select has indicated that the file is writable,
1076 # we can write up to PIPE_BUF bytes without risk
1077 # blocking. POSIX defines PIPE_BUF >= 512
Guido van Rossumbae07c92007-10-08 02:46:15 +00001078 chunk = input[input_offset : input_offset + 512]
1079 bytes_written = os.write(self.stdin.fileno(), chunk)
Thomas Wouters9fe394c2007-02-05 01:24:16 +00001080 input_offset += bytes_written
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001081 if input_offset >= len(input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001082 self.stdin.close()
1083 write_set.remove(self.stdin)
1084
1085 if self.stdout in rlist:
1086 data = os.read(self.stdout.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001087 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001088 self.stdout.close()
1089 read_set.remove(self.stdout)
1090 stdout.append(data)
1091
1092 if self.stderr in rlist:
1093 data = os.read(self.stderr.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001094 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001095 self.stderr.close()
1096 read_set.remove(self.stderr)
1097 stderr.append(data)
1098
1099 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +00001100 if stdout is not None:
Guido van Rossum98297ee2007-11-06 21:34:58 +00001101 stdout = b"".join(stdout)
Peter Astrandd38ddf42005-02-10 08:32:50 +00001102 if stderr is not None:
Guido van Rossum98297ee2007-11-06 21:34:58 +00001103 stderr = b"".join(stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001104
Guido van Rossum98297ee2007-11-06 21:34:58 +00001105 # Translate newlines, if requested.
1106 # This also turns bytes into strings.
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001107 if self.universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +00001108 if stdout is not None:
Guido van Rossum98297ee2007-11-06 21:34:58 +00001109 stdout = self._translate_newlines(stdout,
1110 self.stdout.encoding)
Guido van Rossumfa0054a2007-05-24 04:05:35 +00001111 if stderr is not None:
Guido van Rossum98297ee2007-11-06 21:34:58 +00001112 stderr = self._translate_newlines(stderr,
1113 self.stderr.encoding)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001114
1115 self.wait()
1116 return (stdout, stderr)
1117
1118
1119def _demo_posix():
1120 #
1121 # Example 1: Simple redirection: Get process list
1122 #
1123 plist = Popen(["ps"], stdout=PIPE).communicate()[0]
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001124 print("Process list:")
1125 print(plist)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001126
1127 #
1128 # Example 2: Change uid before executing child
1129 #
1130 if os.getuid() == 0:
1131 p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1132 p.wait()
1133
1134 #
1135 # Example 3: Connecting several subprocesses
1136 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001137 print("Looking for 'hda'...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001138 p1 = Popen(["dmesg"], stdout=PIPE)
1139 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001140 print(repr(p2.communicate()[0]))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001141
1142 #
1143 # Example 4: Catch execution error
1144 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001145 print()
1146 print("Trying a weird file...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001147 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001148 print(Popen(["/this/path/does/not/exist"]).communicate())
Guido van Rossumb940e112007-01-10 16:19:56 +00001149 except OSError as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001150 if e.errno == errno.ENOENT:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001151 print("The file didn't exist. I thought so...")
1152 print("Child traceback:")
1153 print(e.child_traceback)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001154 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001155 print("Error", e.errno)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001156 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001157 print("Gosh. No error.", file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001158
1159
1160def _demo_windows():
1161 #
1162 # Example 1: Connecting several subprocesses
1163 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001164 print("Looking for 'PROMPT' in set output...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001165 p1 = Popen("set", stdout=PIPE, shell=True)
1166 p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001167 print(repr(p2.communicate()[0]))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001168
1169 #
1170 # Example 2: Simple execution of program
1171 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001172 print("Executing calc...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001173 p = Popen("calc")
1174 p.wait()
1175
1176
1177if __name__ == "__main__":
1178 if mswindows:
1179 _demo_windows()
1180 else:
1181 _demo_posix()