blob: ec391cb475d05fbba2f25b83e9972482ea73b202 [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
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000342
Peter Astrand454f7672005-01-01 09:36:35 +0000343# Exception classes used by this module.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000344class CalledProcessError(Exception):
Georg Brandlf9734072008-12-07 15:30:06 +0000345 """This exception is raised when a process run by check_call() or
346 check_output() returns a non-zero exit status.
347 The exit status will be stored in the returncode attribute;
348 check_output() will also store the output in the output attribute.
349 """
350 def __init__(self, returncode, cmd, output=None):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000351 self.returncode = returncode
352 self.cmd = cmd
Georg Brandlf9734072008-12-07 15:30:06 +0000353 self.output = output
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000354 def __str__(self):
355 return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
356
Peter Astrand454f7672005-01-01 09:36:35 +0000357
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000358if mswindows:
359 import threading
360 import msvcrt
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000361 if 0: # <-- change this to use pywin32 instead of the _subprocess driver
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000362 import pywintypes
Tim Peterse8374a52004-10-13 03:15:00 +0000363 from win32api import GetStdHandle, STD_INPUT_HANDLE, \
364 STD_OUTPUT_HANDLE, STD_ERROR_HANDLE
365 from win32api import GetCurrentProcess, DuplicateHandle, \
366 GetModuleFileName, GetVersion
Peter Astrandc1d65362004-11-07 14:30:34 +0000367 from win32con import DUPLICATE_SAME_ACCESS, SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000368 from win32pipe import CreatePipe
Tim Peterse8374a52004-10-13 03:15:00 +0000369 from win32process import CreateProcess, STARTUPINFO, \
370 GetExitCodeProcess, STARTF_USESTDHANDLES, \
Peter Astrandc1d65362004-11-07 14:30:34 +0000371 STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE
Christian Heimesa342c012008-04-20 21:01:16 +0000372 from win32process import TerminateProcess
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000373 from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000374 else:
375 from _subprocess import *
376 class STARTUPINFO:
377 dwFlags = 0
378 hStdInput = None
379 hStdOutput = None
380 hStdError = None
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000381 wShowWindow = 0
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000382 class pywintypes:
383 error = IOError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000384else:
385 import select
Gregory P. Smithd06fa472009-07-04 02:46:54 +0000386 _has_poll = hasattr(select, 'poll')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000387 import errno
388 import fcntl
389 import pickle
390
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000391 try:
392 import _posixsubprocess
393 except ImportError:
394 _posixsubprocess = None
395 import warnings
396 warnings.warn("The _posixsubprocess module is not being used. "
397 "Child process reliability may suffer if your "
398 "program uses threads.", RuntimeWarning)
399
Amaury Forgeot d'Arcace31022009-07-09 22:44:11 +0000400 # When select or poll has indicated that the file is writable,
401 # we can write up to _PIPE_BUF bytes without risk of blocking.
402 # POSIX defines PIPE_BUF as >= 512.
403 _PIPE_BUF = getattr(select, 'PIPE_BUF', 512)
404
405
Brett Cannona23810f2008-05-26 19:04:21 +0000406__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "getstatusoutput",
Georg Brandlf9734072008-12-07 15:30:06 +0000407 "getoutput", "check_output", "CalledProcessError"]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000408
409try:
410 MAXFD = os.sysconf("SC_OPEN_MAX")
411except:
412 MAXFD = 256
413
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000414_active = []
415
416def _cleanup():
417 for inst in _active[:]:
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000418 res = inst._internal_poll(_deadstate=sys.maxsize)
Guido van Rossumb5d47ef2006-08-24 02:27:45 +0000419 if res is not None and res >= 0:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000420 try:
421 _active.remove(inst)
422 except ValueError:
423 # This can happen if two threads create a new Popen instance.
424 # It's harmless that it was already removed, so ignore.
425 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000426
427PIPE = -1
428STDOUT = -2
429
430
Gregory P. Smitha59c59f2010-03-01 00:17:40 +0000431def _eintr_retry_call(func, *args):
432 while True:
433 try:
434 return func(*args)
435 except OSError as e:
436 if e.errno == errno.EINTR:
437 continue
438 raise
439
440
Peter Astrand5f5e1412004-12-05 20:15:36 +0000441def call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000442 """Run command with arguments. Wait for command to complete, then
443 return the returncode attribute.
444
445 The arguments are the same as for the Popen constructor. Example:
446
447 retcode = call(["ls", "-l"])
448 """
Peter Astrand5f5e1412004-12-05 20:15:36 +0000449 return Popen(*popenargs, **kwargs).wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000450
451
Peter Astrand454f7672005-01-01 09:36:35 +0000452def check_call(*popenargs, **kwargs):
453 """Run command with arguments. Wait for command to complete. If
454 the exit code was zero then return, otherwise raise
455 CalledProcessError. The CalledProcessError object will have the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000456 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000457
458 The arguments are the same as for the Popen constructor. Example:
459
460 check_call(["ls", "-l"])
461 """
462 retcode = call(*popenargs, **kwargs)
Peter Astrand454f7672005-01-01 09:36:35 +0000463 if retcode:
Georg Brandlf9734072008-12-07 15:30:06 +0000464 cmd = kwargs.get("args")
465 if cmd is None:
466 cmd = popenargs[0]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000467 raise CalledProcessError(retcode, cmd)
Georg Brandlf9734072008-12-07 15:30:06 +0000468 return 0
469
470
471def check_output(*popenargs, **kwargs):
Georg Brandl2708f3a2009-12-20 14:38:23 +0000472 r"""Run command with arguments and return its output as a byte string.
Georg Brandlf9734072008-12-07 15:30:06 +0000473
474 If the exit code was non-zero it raises a CalledProcessError. The
475 CalledProcessError object will have the return code in the returncode
476 attribute and output in the output attribute.
477
478 The arguments are the same as for the Popen constructor. Example:
479
480 >>> check_output(["ls", "-l", "/dev/null"])
Georg Brandl2708f3a2009-12-20 14:38:23 +0000481 b'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000482
483 The stdout argument is not allowed as it is used internally.
Georg Brandl127d4702009-12-28 08:10:38 +0000484 To capture standard error in the result, use stderr=STDOUT.
Georg Brandlf9734072008-12-07 15:30:06 +0000485
486 >>> check_output(["/bin/sh", "-c",
Georg Brandl2708f3a2009-12-20 14:38:23 +0000487 ... "ls -l non_existent_file ; exit 0"],
Georg Brandl127d4702009-12-28 08:10:38 +0000488 ... stderr=STDOUT)
Georg Brandl2708f3a2009-12-20 14:38:23 +0000489 b'ls: non_existent_file: No such file or directory\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000490 """
491 if 'stdout' in kwargs:
492 raise ValueError('stdout argument not allowed, it will be overridden.')
493 process = Popen(*popenargs, stdout=PIPE, **kwargs)
494 output, unused_err = process.communicate()
495 retcode = process.poll()
496 if retcode:
497 cmd = kwargs.get("args")
498 if cmd is None:
499 cmd = popenargs[0]
500 raise CalledProcessError(retcode, cmd, output=output)
501 return output
Peter Astrand454f7672005-01-01 09:36:35 +0000502
503
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000504def list2cmdline(seq):
505 """
506 Translate a sequence of arguments into a command line
507 string, using the same rules as the MS C runtime:
508
509 1) Arguments are delimited by white space, which is either a
510 space or a tab.
511
512 2) A string surrounded by double quotation marks is
513 interpreted as a single argument, regardless of white space
Christian Heimesfdab48e2008-01-20 09:06:41 +0000514 or pipe characters contained within. A quoted string can be
515 embedded in an argument.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000516
517 3) A double quotation mark preceded by a backslash is
518 interpreted as a literal double quotation mark.
519
520 4) Backslashes are interpreted literally, unless they
521 immediately precede a double quotation mark.
522
523 5) If backslashes immediately precede a double quotation mark,
524 every pair of backslashes is interpreted as a literal
525 backslash. If the number of backslashes is odd, the last
526 backslash escapes the next double quotation mark as
527 described in rule 3.
528 """
529
530 # See
Eric Smith3c573af2009-11-09 15:23:15 +0000531 # http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
532 # or search http://msdn.microsoft.com for
533 # "Parsing C++ Command-Line Arguments"
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000534 result = []
535 needquote = False
536 for arg in seq:
537 bs_buf = []
538
539 # Add a space to separate this argument from the others
540 if result:
541 result.append(' ')
542
Christian Heimesfdab48e2008-01-20 09:06:41 +0000543 needquote = (" " in arg) or ("\t" in arg) or ("|" in arg) or not arg
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000544 if needquote:
545 result.append('"')
546
547 for c in arg:
548 if c == '\\':
Tim Peterse718f612004-10-12 21:51:32 +0000549 # Don't know if we need to double yet.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000550 bs_buf.append(c)
551 elif c == '"':
Christian Heimesfdab48e2008-01-20 09:06:41 +0000552 # Double backslashes.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000553 result.append('\\' * len(bs_buf)*2)
554 bs_buf = []
555 result.append('\\"')
556 else:
557 # Normal char
558 if bs_buf:
559 result.extend(bs_buf)
560 bs_buf = []
561 result.append(c)
562
Christian Heimesfdab48e2008-01-20 09:06:41 +0000563 # Add remaining backslashes, if any.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000564 if bs_buf:
565 result.extend(bs_buf)
566
567 if needquote:
Peter Astrand7e78ade2005-03-03 21:10:23 +0000568 result.extend(bs_buf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000569 result.append('"')
570
571 return ''.join(result)
572
573
Brett Cannona23810f2008-05-26 19:04:21 +0000574# Various tools for executing commands and looking at their output and status.
575#
576# NB This only works (and is only relevant) for UNIX.
577
578def getstatusoutput(cmd):
579 """Return (status, output) of executing cmd in a shell.
580
581 Execute the string 'cmd' in a shell with os.popen() and return a 2-tuple
582 (status, output). cmd is actually run as '{ cmd ; } 2>&1', so that the
583 returned output will contain output or error messages. A trailing newline
584 is stripped from the output. The exit status for the command can be
585 interpreted according to the rules for the C function wait(). Example:
586
587 >>> import subprocess
588 >>> subprocess.getstatusoutput('ls /bin/ls')
589 (0, '/bin/ls')
590 >>> subprocess.getstatusoutput('cat /bin/junk')
591 (256, 'cat: /bin/junk: No such file or directory')
592 >>> subprocess.getstatusoutput('/bin/junk')
593 (256, 'sh: /bin/junk: not found')
594 """
595 pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
596 text = pipe.read()
597 sts = pipe.close()
598 if sts is None: sts = 0
599 if text[-1:] == '\n': text = text[:-1]
600 return sts, text
601
602
603def getoutput(cmd):
604 """Return output (stdout or stderr) of executing cmd in a shell.
605
606 Like getstatusoutput(), except the exit status is ignored and the return
607 value is a string containing the command's output. Example:
608
609 >>> import subprocess
610 >>> subprocess.getoutput('ls /bin/ls')
611 '/bin/ls'
612 """
613 return getstatusoutput(cmd)[1]
614
615
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000616class Popen(object):
617 def __init__(self, args, bufsize=0, executable=None,
618 stdin=None, stdout=None, stderr=None,
619 preexec_fn=None, close_fds=False, shell=False,
620 cwd=None, env=None, universal_newlines=False,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000621 startupinfo=None, creationflags=0,
622 restore_signals=True, start_new_session=False):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000623 """Create new Popen instance."""
624 _cleanup()
625
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000626 self._child_created = False
Guido van Rossum46a05a72007-06-07 21:56:45 +0000627 if bufsize is None:
628 bufsize = 0 # Restore default
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000629 if not isinstance(bufsize, int):
Peter Astrand738131d2004-11-30 21:04:45 +0000630 raise TypeError("bufsize must be an integer")
631
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000632 if mswindows:
Tim Peterse8374a52004-10-13 03:15:00 +0000633 if preexec_fn is not None:
634 raise ValueError("preexec_fn is not supported on Windows "
635 "platforms")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000636 if close_fds and (stdin is not None or stdout is not None or
637 stderr is not None):
Tim Peterse8374a52004-10-13 03:15:00 +0000638 raise ValueError("close_fds is not supported on Windows "
Guido van Rossume7ba4952007-06-06 23:52:48 +0000639 "platforms if you redirect stdin/stdout/stderr")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000640 else:
641 # POSIX
Tim Peterse8374a52004-10-13 03:15:00 +0000642 if startupinfo is not None:
643 raise ValueError("startupinfo is only supported on Windows "
644 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000645 if creationflags != 0:
Tim Peterse8374a52004-10-13 03:15:00 +0000646 raise ValueError("creationflags is only supported on Windows "
647 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000648
Tim Peterse718f612004-10-12 21:51:32 +0000649 self.stdin = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000650 self.stdout = None
651 self.stderr = None
652 self.pid = None
653 self.returncode = None
654 self.universal_newlines = universal_newlines
655
656 # Input and output objects. The general principle is like
657 # this:
658 #
659 # Parent Child
660 # ------ -----
661 # p2cwrite ---stdin---> p2cread
662 # c2pread <--stdout--- c2pwrite
663 # errread <--stderr--- errwrite
664 #
665 # On POSIX, the child objects are file descriptors. On
666 # Windows, these are Windows file handles. The parent objects
667 # are file descriptors on both platforms. The parent objects
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000668 # are -1 when not using PIPEs. The child objects are -1
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000669 # when not redirecting.
Tim Peterse718f612004-10-12 21:51:32 +0000670
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000671 (p2cread, p2cwrite,
672 c2pread, c2pwrite,
673 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
674
675 self._execute_child(args, executable, preexec_fn, close_fds,
676 cwd, env, universal_newlines,
677 startupinfo, creationflags, shell,
678 p2cread, p2cwrite,
679 c2pread, c2pwrite,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000680 errread, errwrite,
681 restore_signals, start_new_session)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000682
Thomas Wouterscf297e42007-02-23 15:07:44 +0000683 if mswindows:
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000684 if p2cwrite != -1:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000685 p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000686 if c2pread != -1:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000687 c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000688 if errread != -1:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000689 errread = msvcrt.open_osfhandle(errread.Detach(), 0)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000690
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000691 if bufsize == 0:
692 bufsize = 1 # Nearly unbuffered (XXX for now)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000693 if p2cwrite != -1:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000694 self.stdin = io.open(p2cwrite, 'wb', bufsize)
695 if self.universal_newlines:
696 self.stdin = io.TextIOWrapper(self.stdin)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000697 if c2pread != -1:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000698 self.stdout = io.open(c2pread, 'rb', bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000699 if universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000700 self.stdout = io.TextIOWrapper(self.stdout)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000701 if errread != -1:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000702 self.stderr = io.open(errread, 'rb', bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000703 if universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000704 self.stderr = io.TextIOWrapper(self.stderr)
Tim Peterse718f612004-10-12 21:51:32 +0000705
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000706
Guido van Rossum98297ee2007-11-06 21:34:58 +0000707 def _translate_newlines(self, data, encoding):
708 data = data.replace(b"\r\n", b"\n").replace(b"\r", b"\n")
709 return data.decode(encoding)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000710
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000711
Guido van Rossumd8faa362007-04-27 19:54:29 +0000712 def __del__(self, sys=sys):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000713 if not self._child_created:
714 # We didn't get to successfully create a child process.
715 return
716 # In case the child hasn't been waited on, check if it's done.
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000717 self._internal_poll(_deadstate=sys.maxsize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000718 if self.returncode is None and _active is not None:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000719 # Child is still running, keep us alive until we can wait on it.
720 _active.append(self)
721
722
Peter Astrand23109f02005-03-03 20:28:59 +0000723 def communicate(self, input=None):
724 """Interact with process: Send data to stdin. Read data from
725 stdout and stderr, until end-of-file is reached. Wait for
726 process to terminate. The optional input argument should be a
727 string to be sent to the child process, or None, if no data
728 should be sent to the child.
Tim Peterseba28be2005-03-28 01:08:02 +0000729
Peter Astrand23109f02005-03-03 20:28:59 +0000730 communicate() returns a tuple (stdout, stderr)."""
731
732 # Optimization: If we are only using one pipe, or no pipe at
733 # all, using select() or threads is unnecessary.
734 if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
Tim Peterseba28be2005-03-28 01:08:02 +0000735 stdout = None
736 stderr = None
Peter Astrand23109f02005-03-03 20:28:59 +0000737 if self.stdin:
738 if input:
739 self.stdin.write(input)
740 self.stdin.close()
741 elif self.stdout:
742 stdout = self.stdout.read()
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000743 self.stdout.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000744 elif self.stderr:
745 stderr = self.stderr.read()
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000746 self.stderr.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000747 self.wait()
748 return (stdout, stderr)
Tim Peterseba28be2005-03-28 01:08:02 +0000749
Peter Astrand23109f02005-03-03 20:28:59 +0000750 return self._communicate(input)
751
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000752
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000753 def poll(self):
754 return self._internal_poll()
755
756
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000757 if mswindows:
758 #
759 # Windows methods
760 #
761 def _get_handles(self, stdin, stdout, stderr):
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +0000762 """Construct and return tuple with IO objects:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000763 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
764 """
Peter Astrandd38ddf42005-02-10 08:32:50 +0000765 if stdin is None and stdout is None and stderr is None:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000766 return (-1, -1, -1, -1, -1, -1)
Tim Peterse718f612004-10-12 21:51:32 +0000767
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000768 p2cread, p2cwrite = -1, -1
769 c2pread, c2pwrite = -1, -1
770 errread, errwrite = -1, -1
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000771
Peter Astrandd38ddf42005-02-10 08:32:50 +0000772 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000773 p2cread = GetStdHandle(STD_INPUT_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000774 if p2cread is None:
775 p2cread, _ = CreatePipe(None, 0)
776 elif stdin == PIPE:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000777 p2cread, p2cwrite = CreatePipe(None, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000778 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000779 p2cread = msvcrt.get_osfhandle(stdin)
780 else:
781 # Assuming file-like object
782 p2cread = msvcrt.get_osfhandle(stdin.fileno())
783 p2cread = self._make_inheritable(p2cread)
784
Peter Astrandd38ddf42005-02-10 08:32:50 +0000785 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000786 c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000787 if c2pwrite is None:
788 _, c2pwrite = CreatePipe(None, 0)
789 elif stdout == PIPE:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000790 c2pread, c2pwrite = CreatePipe(None, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000791 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000792 c2pwrite = msvcrt.get_osfhandle(stdout)
793 else:
794 # Assuming file-like object
795 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
796 c2pwrite = self._make_inheritable(c2pwrite)
797
Peter Astrandd38ddf42005-02-10 08:32:50 +0000798 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000799 errwrite = GetStdHandle(STD_ERROR_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000800 if errwrite is None:
801 _, errwrite = CreatePipe(None, 0)
802 elif stderr == PIPE:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000803 errread, errwrite = CreatePipe(None, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000804 elif stderr == STDOUT:
805 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000806 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000807 errwrite = msvcrt.get_osfhandle(stderr)
808 else:
809 # Assuming file-like object
810 errwrite = msvcrt.get_osfhandle(stderr.fileno())
811 errwrite = self._make_inheritable(errwrite)
812
813 return (p2cread, p2cwrite,
814 c2pread, c2pwrite,
815 errread, errwrite)
816
817
818 def _make_inheritable(self, handle):
819 """Return a duplicate of handle, which is inheritable"""
820 return DuplicateHandle(GetCurrentProcess(), handle,
821 GetCurrentProcess(), 0, 1,
822 DUPLICATE_SAME_ACCESS)
823
824
825 def _find_w9xpopen(self):
826 """Find and return absolut path to w9xpopen.exe"""
Tim Peterse8374a52004-10-13 03:15:00 +0000827 w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)),
828 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000829 if not os.path.exists(w9xpopen):
830 # Eeek - file-not-found - possibly an embedding
831 # situation - see if we can locate it in sys.exec_prefix
Tim Peterse8374a52004-10-13 03:15:00 +0000832 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
833 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000834 if not os.path.exists(w9xpopen):
Tim Peterse8374a52004-10-13 03:15:00 +0000835 raise RuntimeError("Cannot locate w9xpopen.exe, which is "
836 "needed for Popen to work with your "
837 "shell or platform.")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000838 return w9xpopen
839
Tim Peterse718f612004-10-12 21:51:32 +0000840
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000841 def _execute_child(self, args, executable, preexec_fn, close_fds,
842 cwd, env, universal_newlines,
843 startupinfo, creationflags, shell,
844 p2cread, p2cwrite,
845 c2pread, c2pwrite,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000846 errread, errwrite,
847 unused_restore_signals, unused_start_new_session):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000848 """Execute program (MS Windows version)"""
849
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000850 if not isinstance(args, str):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000851 args = list2cmdline(args)
852
Peter Astrandc1d65362004-11-07 14:30:34 +0000853 # Process startup details
Peter Astrandd38ddf42005-02-10 08:32:50 +0000854 if startupinfo is None:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000855 startupinfo = STARTUPINFO()
856 if None not in (p2cread, c2pwrite, errwrite):
Peter Astrandc1d65362004-11-07 14:30:34 +0000857 startupinfo.dwFlags |= STARTF_USESTDHANDLES
858 startupinfo.hStdInput = p2cread
859 startupinfo.hStdOutput = c2pwrite
860 startupinfo.hStdError = errwrite
861
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000862 if shell:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000863 startupinfo.dwFlags |= STARTF_USESHOWWINDOW
864 startupinfo.wShowWindow = SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000865 comspec = os.environ.get("COMSPEC", "cmd.exe")
866 args = comspec + " /c " + args
Guido van Rossume2a383d2007-01-15 16:59:06 +0000867 if (GetVersion() >= 0x80000000 or
Tim Peterse8374a52004-10-13 03:15:00 +0000868 os.path.basename(comspec).lower() == "command.com"):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000869 # Win9x, or using command.com on NT. We need to
870 # use the w9xpopen intermediate program. For more
871 # information, see KB Q150956
872 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
873 w9xpopen = self._find_w9xpopen()
874 args = '"%s" %s' % (w9xpopen, args)
875 # Not passing CREATE_NEW_CONSOLE has been known to
876 # cause random failures on win9x. Specifically a
877 # dialog: "Your program accessed mem currently in
878 # use at xxx" and a hopeful warning about the
Mark Dickinson934896d2009-02-21 20:59:32 +0000879 # stability of your system. Cost is Ctrl+C won't
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000880 # kill children.
881 creationflags |= CREATE_NEW_CONSOLE
882
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000883 # Start the process
884 try:
885 hp, ht, pid, tid = CreateProcess(executable, args,
Tim Peterse8374a52004-10-13 03:15:00 +0000886 # no special security
887 None, None,
Guido van Rossume7ba4952007-06-06 23:52:48 +0000888 int(not close_fds),
Tim Peterse8374a52004-10-13 03:15:00 +0000889 creationflags,
890 env,
891 cwd,
892 startupinfo)
Guido van Rossumb940e112007-01-10 16:19:56 +0000893 except pywintypes.error as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000894 # Translate pywintypes.error to WindowsError, which is
895 # a subclass of OSError. FIXME: We should really
896 # translate errno using _sys_errlist (or simliar), but
897 # how can this be done from Python?
898 raise WindowsError(*e.args)
899
900 # Retain the process handle, but close the thread handle
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000901 self._child_created = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000902 self._handle = hp
903 self.pid = pid
904 ht.Close()
905
Andrew M. Kuchling51ee66e2004-10-12 16:38:42 +0000906 # Child is launched. Close the parent's copy of those pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000907 # handles that only the child should have open. You need
908 # to make sure that no handles to the write end of the
909 # output pipe are maintained in this process or else the
910 # pipe will not close when the child process exits and the
911 # ReadFile will hang.
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000912 if p2cread != -1:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000913 p2cread.Close()
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000914 if c2pwrite != -1:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000915 c2pwrite.Close()
Florent Xicluna3b8bfef2010-03-14 12:31:06 +0000916 if errwrite != -1:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000917 errwrite.Close()
918
Tim Peterse718f612004-10-12 21:51:32 +0000919
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000920 def _internal_poll(self, _deadstate=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000921 """Check if child process has terminated. Returns returncode
922 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000923 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000924 if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
925 self.returncode = GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000926 return self.returncode
927
928
929 def wait(self):
930 """Wait for child process to terminate. Returns returncode
931 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000932 if self.returncode is None:
Georg Brandl89fad142010-03-14 10:23:39 +0000933 WaitForSingleObject(self._handle, INFINITE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000934 self.returncode = GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000935 return self.returncode
936
937
938 def _readerthread(self, fh, buffer):
939 buffer.append(fh.read())
940
941
Peter Astrand23109f02005-03-03 20:28:59 +0000942 def _communicate(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000943 stdout = None # Return
944 stderr = None # Return
945
946 if self.stdout:
947 stdout = []
Tim Peterse8374a52004-10-13 03:15:00 +0000948 stdout_thread = threading.Thread(target=self._readerthread,
949 args=(self.stdout, stdout))
Benjamin Peterson632e0362008-08-18 19:08:51 +0000950 stdout_thread.daemon = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000951 stdout_thread.start()
952 if self.stderr:
953 stderr = []
Tim Peterse8374a52004-10-13 03:15:00 +0000954 stderr_thread = threading.Thread(target=self._readerthread,
955 args=(self.stderr, stderr))
Benjamin Peterson632e0362008-08-18 19:08:51 +0000956 stderr_thread.daemon = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000957 stderr_thread.start()
958
959 if self.stdin:
Peter Astrandd38ddf42005-02-10 08:32:50 +0000960 if input is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000961 self.stdin.write(input)
962 self.stdin.close()
963
964 if self.stdout:
965 stdout_thread.join()
966 if self.stderr:
967 stderr_thread.join()
968
969 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000970 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000971 stdout = stdout[0]
Peter Astrandd38ddf42005-02-10 08:32:50 +0000972 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000973 stderr = stderr[0]
974
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000975 self.wait()
976 return (stdout, stderr)
977
Christian Heimesa342c012008-04-20 21:01:16 +0000978 def send_signal(self, sig):
979 """Send a signal to the process
980 """
981 if sig == signal.SIGTERM:
982 self.terminate()
Brian Curtineb24d742010-04-12 17:16:38 +0000983 elif sig == signal.CTRL_C_EVENT:
984 os.kill(self.pid, signal.CTRL_C_EVENT)
985 elif sig == signal.CTRL_BREAK_EVENT:
986 os.kill(self.pid, signal.CTRL_BREAK_EVENT)
Christian Heimesa342c012008-04-20 21:01:16 +0000987 else:
988 raise ValueError("Only SIGTERM is supported on Windows")
989
990 def terminate(self):
991 """Terminates the process
992 """
993 TerminateProcess(self._handle, 1)
994
995 kill = terminate
996
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000997 else:
998 #
999 # POSIX methods
1000 #
1001 def _get_handles(self, stdin, stdout, stderr):
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +00001002 """Construct and return tuple with IO objects:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001003 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
1004 """
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001005 p2cread, p2cwrite = -1, -1
1006 c2pread, c2pwrite = -1, -1
1007 errread, errwrite = -1, -1
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001008
Peter Astrandd38ddf42005-02-10 08:32:50 +00001009 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001010 pass
1011 elif stdin == PIPE:
1012 p2cread, p2cwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +00001013 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001014 p2cread = stdin
1015 else:
1016 # Assuming file-like object
1017 p2cread = stdin.fileno()
1018
Peter Astrandd38ddf42005-02-10 08:32:50 +00001019 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001020 pass
1021 elif stdout == PIPE:
1022 c2pread, c2pwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +00001023 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001024 c2pwrite = stdout
1025 else:
1026 # Assuming file-like object
Tim Peterse718f612004-10-12 21:51:32 +00001027 c2pwrite = stdout.fileno()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001028
Peter Astrandd38ddf42005-02-10 08:32:50 +00001029 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001030 pass
1031 elif stderr == PIPE:
1032 errread, errwrite = os.pipe()
1033 elif stderr == STDOUT:
1034 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +00001035 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001036 errwrite = stderr
1037 else:
1038 # Assuming file-like object
1039 errwrite = stderr.fileno()
1040
1041 return (p2cread, p2cwrite,
1042 c2pread, c2pwrite,
1043 errread, errwrite)
1044
1045
1046 def _set_cloexec_flag(self, fd):
1047 try:
1048 cloexec_flag = fcntl.FD_CLOEXEC
1049 except AttributeError:
1050 cloexec_flag = 1
1051
1052 old = fcntl.fcntl(fd, fcntl.F_GETFD)
1053 fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
1054
1055
1056 def _close_fds(self, but):
Christian Heimesfdab48e2008-01-20 09:06:41 +00001057 os.closerange(3, but)
1058 os.closerange(but + 1, MAXFD)
Tim Peterse718f612004-10-12 21:51:32 +00001059
1060
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001061 def _execute_child(self, args, executable, preexec_fn, close_fds,
1062 cwd, env, universal_newlines,
1063 startupinfo, creationflags, shell,
1064 p2cread, p2cwrite,
1065 c2pread, c2pwrite,
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001066 errread, errwrite,
1067 restore_signals, start_new_session):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001068 """Execute program (POSIX version)"""
1069
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001070 if isinstance(args, str):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001071 args = [args]
Thomas Wouters89f507f2006-12-13 04:49:30 +00001072 else:
1073 args = list(args)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001074
1075 if shell:
1076 args = ["/bin/sh", "-c"] + args
1077
Peter Astrandd38ddf42005-02-10 08:32:50 +00001078 if executable is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001079 executable = args[0]
1080
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001081 # For transferring possible exec failure from child to parent.
1082 # Data format: "exception name:hex errno:description"
1083 # Pickle is not used; it is complex and involves memory allocation.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001084 errpipe_read, errpipe_write = os.pipe()
Christian Heimesfdab48e2008-01-20 09:06:41 +00001085 try:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001086 try:
Facundo Batista10706e22009-06-19 20:34:30 +00001087 self._set_cloexec_flag(errpipe_write)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001088
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001089 if _posixsubprocess:
1090 fs_encoding = sys.getfilesystemencoding()
1091 def fs_encode(s):
1092 """Encode s for use in the env, fs or cmdline."""
1093 return s.encode(fs_encoding, 'surrogateescape')
1094
1095 # We must avoid complex work that could involve
1096 # malloc or free in the child process to avoid
1097 # potential deadlocks, thus we do all this here.
1098 # and pass it to fork_exec()
1099
1100 if env:
1101 env_list = [fs_encode(k) + b'=' + fs_encode(v)
1102 for k, v in env.items()]
1103 else:
1104 env_list = None # Use execv instead of execve.
1105 if os.path.dirname(executable):
1106 executable_list = (fs_encode(executable),)
1107 else:
1108 # This matches the behavior of os._execvpe().
1109 path_list = os.get_exec_path(env)
1110 executable_list = (os.path.join(dir, executable)
1111 for dir in path_list)
1112 executable_list = tuple(fs_encode(exe)
1113 for exe in executable_list)
1114 self.pid = _posixsubprocess.fork_exec(
1115 args, executable_list,
1116 close_fds, cwd, env_list,
1117 p2cread, p2cwrite, c2pread, c2pwrite,
1118 errread, errwrite,
1119 errpipe_read, errpipe_write,
1120 restore_signals, start_new_session, preexec_fn)
1121 else:
1122 # Pure Python implementation: It is not thread safe.
1123 # This implementation may deadlock in the child if your
1124 # parent process has any other threads running.
1125
1126 gc_was_enabled = gc.isenabled()
1127 # Disable gc to avoid bug where gc -> file_dealloc ->
1128 # write to stderr -> hang. See issue1336
1129 gc.disable()
1130 try:
1131 self.pid = os.fork()
1132 except:
1133 if gc_was_enabled:
1134 gc.enable()
1135 raise
1136 self._child_created = True
1137 if self.pid == 0:
1138 # Child
1139 try:
1140 # Close parent's pipe ends
1141 if p2cwrite != -1:
1142 os.close(p2cwrite)
1143 if c2pread != -1:
1144 os.close(c2pread)
1145 if errread != -1:
1146 os.close(errread)
1147 os.close(errpipe_read)
1148
1149 # Dup fds for child
1150 if p2cread != -1:
1151 os.dup2(p2cread, 0)
1152 if c2pwrite != -1:
1153 os.dup2(c2pwrite, 1)
1154 if errwrite != -1:
1155 os.dup2(errwrite, 2)
1156
1157 # Close pipe fds. Make sure we don't close the
1158 # same fd more than once, or standard fds.
1159 if p2cread != -1 and p2cread not in (0,):
1160 os.close(p2cread)
1161 if (c2pwrite != -1 and
1162 c2pwrite not in (p2cread, 1)):
1163 os.close(c2pwrite)
1164 if (errwrite != -1 and
1165 errwrite not in (p2cread, c2pwrite, 2)):
1166 os.close(errwrite)
1167
1168 # Close all other fds, if asked for
1169 if close_fds:
1170 self._close_fds(but=errpipe_write)
1171
1172 if cwd is not None:
1173 os.chdir(cwd)
1174
1175 # This is a copy of Python/pythonrun.c
1176 # _Py_RestoreSignals(). If that were exposed
1177 # as a sys._py_restoresignals func it would be
1178 # better.. but this pure python implementation
1179 # isn't likely to be used much anymore.
1180 if restore_signals:
1181 signals = ('SIGPIPE', 'SIGXFZ', 'SIGXFSZ')
1182 for sig in signals:
1183 if hasattr(signal, sig):
1184 signal.signal(getattr(signal, sig),
1185 signal.SIG_DFL)
1186
1187 if start_new_session and hasattr(os, 'setsid'):
1188 os.setsid()
1189
1190 if preexec_fn:
1191 preexec_fn()
1192
1193 if env is None:
1194 os.execvp(executable, args)
1195 else:
1196 os.execvpe(executable, args, env)
1197
1198 except:
1199 try:
1200 exc_type, exc_value = sys.exc_info()[:2]
1201 if isinstance(exc_value, OSError):
1202 errno = exc_value.errno
1203 else:
1204 errno = 0
1205 message = '%s:%x:%s' % (exc_type.__name__,
1206 errno, exc_value)
1207 os.write(errpipe_write, message.encode())
1208 except:
1209 # We MUST not allow anything odd happening
1210 # above to prevent us from exiting below.
1211 pass
1212
1213 # This exitcode won't be reported to applications
1214 # so it really doesn't matter what we return.
1215 os._exit(255)
1216
1217 # Parent
Facundo Batista10706e22009-06-19 20:34:30 +00001218 if gc_was_enabled:
1219 gc.enable()
Facundo Batista10706e22009-06-19 20:34:30 +00001220 finally:
1221 # be sure the FD is closed no matter what
1222 os.close(errpipe_write)
1223
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001224 if p2cread != -1 and p2cwrite != -1:
Facundo Batista10706e22009-06-19 20:34:30 +00001225 os.close(p2cread)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001226 if c2pwrite != -1 and c2pread != -1:
Facundo Batista10706e22009-06-19 20:34:30 +00001227 os.close(c2pwrite)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001228 if errwrite != -1 and errread != -1:
Facundo Batista10706e22009-06-19 20:34:30 +00001229 os.close(errwrite)
1230
1231 # Wait for exec to fail or succeed; possibly raising an
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001232 # exception (limited in size)
1233 data = bytearray()
1234 while True:
1235 part = _eintr_retry_call(os.read, errpipe_read, 50000)
1236 data += part
1237 if not part or len(data) > 50000:
1238 break
Facundo Batista10706e22009-06-19 20:34:30 +00001239 finally:
1240 # be sure the FD is closed no matter what
1241 os.close(errpipe_read)
1242
Guido van Rossumaf2362a2007-05-15 22:32:02 +00001243 if data:
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001244 _eintr_retry_call(os.waitpid, self.pid, 0)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001245 try:
1246 exception_name, hex_errno, err_msg = data.split(b':', 2)
1247 except ValueError:
1248 print('Bad exception data:', repr(data))
1249 exception_name = b'RuntimeError'
1250 hex_errno = b'0'
1251 err_msg = b'Unknown'
1252 child_exception_type = getattr(
1253 builtins, exception_name.decode('ascii'),
1254 RuntimeError)
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001255 for fd in (p2cwrite, c2pread, errread):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001256 if fd != -1:
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001257 os.close(fd)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001258 err_msg = err_msg.decode()
1259 if issubclass(child_exception_type, OSError) and hex_errno:
1260 errno = int(hex_errno, 16)
1261 if errno != 0:
1262 err_msg = os.strerror(errno)
1263 raise child_exception_type(errno, err_msg)
1264 raise child_exception_type(err_msg)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001265
1266
1267 def _handle_exitstatus(self, sts):
1268 if os.WIFSIGNALED(sts):
1269 self.returncode = -os.WTERMSIG(sts)
1270 elif os.WIFEXITED(sts):
1271 self.returncode = os.WEXITSTATUS(sts)
1272 else:
1273 # Should never happen
1274 raise RuntimeError("Unknown child exit status!")
1275
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001276
Georg Brandl6aa2d1f2008-08-12 08:35:52 +00001277 def _internal_poll(self, _deadstate=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001278 """Check if child process has terminated. Returns returncode
1279 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001280 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001281 try:
1282 pid, sts = os.waitpid(self.pid, os.WNOHANG)
1283 if pid == self.pid:
1284 self._handle_exitstatus(sts)
1285 except os.error:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001286 if _deadstate is not None:
1287 self.returncode = _deadstate
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001288 return self.returncode
1289
1290
1291 def wait(self):
1292 """Wait for child process to terminate. Returns returncode
1293 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001294 if self.returncode is None:
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001295 pid, sts = _eintr_retry_call(os.waitpid, self.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001296 self._handle_exitstatus(sts)
1297 return self.returncode
1298
1299
Peter Astrand23109f02005-03-03 20:28:59 +00001300 def _communicate(self, input):
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001301 if self.stdin:
1302 # Flush stdio buffer. This might block, if the user has
1303 # been writing to .stdin in an uncontrolled fashion.
1304 self.stdin.flush()
1305 if not input:
1306 self.stdin.close()
1307
1308 if _has_poll:
1309 stdout, stderr = self._communicate_with_poll(input)
1310 else:
1311 stdout, stderr = self._communicate_with_select(input)
1312
1313 # All data exchanged. Translate lists into strings.
1314 if stdout is not None:
1315 stdout = b''.join(stdout)
1316 if stderr is not None:
1317 stderr = b''.join(stderr)
1318
1319 # Translate newlines, if requested.
1320 # This also turns bytes into strings.
1321 if self.universal_newlines:
1322 if stdout is not None:
1323 stdout = self._translate_newlines(stdout,
1324 self.stdout.encoding)
1325 if stderr is not None:
1326 stderr = self._translate_newlines(stderr,
1327 self.stderr.encoding)
1328
1329 self.wait()
1330 return (stdout, stderr)
1331
1332
1333 def _communicate_with_poll(self, input):
1334 stdout = None # Return
1335 stderr = None # Return
1336 fd2file = {}
1337 fd2output = {}
1338
1339 poller = select.poll()
1340 def register_and_append(file_obj, eventmask):
1341 poller.register(file_obj.fileno(), eventmask)
1342 fd2file[file_obj.fileno()] = file_obj
1343
1344 def close_unregister_and_remove(fd):
1345 poller.unregister(fd)
1346 fd2file[fd].close()
1347 fd2file.pop(fd)
1348
1349 if self.stdin and input:
1350 register_and_append(self.stdin, select.POLLOUT)
1351
1352 select_POLLIN_POLLPRI = select.POLLIN | select.POLLPRI
1353 if self.stdout:
1354 register_and_append(self.stdout, select_POLLIN_POLLPRI)
1355 fd2output[self.stdout.fileno()] = stdout = []
1356 if self.stderr:
1357 register_and_append(self.stderr, select_POLLIN_POLLPRI)
1358 fd2output[self.stderr.fileno()] = stderr = []
1359
1360 input_offset = 0
1361 while fd2file:
1362 try:
1363 ready = poller.poll()
1364 except select.error as e:
1365 if e.args[0] == errno.EINTR:
1366 continue
1367 raise
1368
1369 # XXX Rewrite these to use non-blocking I/O on the
1370 # file objects; they are no longer using C stdio!
1371
1372 for fd, mode in ready:
1373 if mode & select.POLLOUT:
1374 chunk = input[input_offset : input_offset + _PIPE_BUF]
1375 input_offset += os.write(fd, chunk)
1376 if input_offset >= len(input):
1377 close_unregister_and_remove(fd)
1378 elif mode & select_POLLIN_POLLPRI:
1379 data = os.read(fd, 4096)
1380 if not data:
1381 close_unregister_and_remove(fd)
1382 fd2output[fd].append(data)
1383 else:
1384 # Ignore hang up or errors.
1385 close_unregister_and_remove(fd)
1386
1387 return (stdout, stderr)
1388
1389
1390 def _communicate_with_select(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001391 read_set = []
1392 write_set = []
1393 stdout = None # Return
1394 stderr = None # Return
1395
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001396 if self.stdin and input:
1397 write_set.append(self.stdin)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001398 if self.stdout:
1399 read_set.append(self.stdout)
Tim Peterse718f612004-10-12 21:51:32 +00001400 stdout = []
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001401 if self.stderr:
1402 read_set.append(self.stderr)
1403 stderr = []
1404
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001405 input_offset = 0
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001406 while read_set or write_set:
Georg Brandl86b2fb92008-07-16 03:43:04 +00001407 try:
1408 rlist, wlist, xlist = select.select(read_set, write_set, [])
1409 except select.error as e:
1410 if e.args[0] == errno.EINTR:
1411 continue
1412 raise
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001413
Guido van Rossum98297ee2007-11-06 21:34:58 +00001414 # XXX Rewrite these to use non-blocking I/O on the
1415 # file objects; they are no longer using C stdio!
1416
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001417 if self.stdin in wlist:
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001418 chunk = input[input_offset : input_offset + _PIPE_BUF]
Guido van Rossumbae07c92007-10-08 02:46:15 +00001419 bytes_written = os.write(self.stdin.fileno(), chunk)
Thomas Wouters9fe394c2007-02-05 01:24:16 +00001420 input_offset += bytes_written
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001421 if input_offset >= len(input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001422 self.stdin.close()
1423 write_set.remove(self.stdin)
1424
1425 if self.stdout in rlist:
1426 data = os.read(self.stdout.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001427 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001428 self.stdout.close()
1429 read_set.remove(self.stdout)
1430 stdout.append(data)
1431
1432 if self.stderr in rlist:
1433 data = os.read(self.stderr.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001434 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001435 self.stderr.close()
1436 read_set.remove(self.stderr)
1437 stderr.append(data)
1438
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001439 return (stdout, stderr)
1440
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001441
Christian Heimesa342c012008-04-20 21:01:16 +00001442 def send_signal(self, sig):
1443 """Send a signal to the process
1444 """
1445 os.kill(self.pid, sig)
1446
1447 def terminate(self):
1448 """Terminate the process with SIGTERM
1449 """
1450 self.send_signal(signal.SIGTERM)
1451
1452 def kill(self):
1453 """Kill the process with SIGKILL
1454 """
1455 self.send_signal(signal.SIGKILL)
1456
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001457
1458def _demo_posix():
1459 #
1460 # Example 1: Simple redirection: Get process list
1461 #
1462 plist = Popen(["ps"], stdout=PIPE).communicate()[0]
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001463 print("Process list:")
1464 print(plist)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001465
1466 #
1467 # Example 2: Change uid before executing child
1468 #
1469 if os.getuid() == 0:
1470 p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1471 p.wait()
1472
1473 #
1474 # Example 3: Connecting several subprocesses
1475 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001476 print("Looking for 'hda'...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001477 p1 = Popen(["dmesg"], stdout=PIPE)
1478 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001479 print(repr(p2.communicate()[0]))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001480
1481 #
1482 # Example 4: Catch execution error
1483 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001484 print()
1485 print("Trying a weird file...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001486 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001487 print(Popen(["/this/path/does/not/exist"]).communicate())
Guido van Rossumb940e112007-01-10 16:19:56 +00001488 except OSError as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001489 if e.errno == errno.ENOENT:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001490 print("The file didn't exist. I thought so...")
1491 print("Child traceback:")
1492 print(e.child_traceback)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001493 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001494 print("Error", e.errno)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001495 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001496 print("Gosh. No error.", file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001497
1498
1499def _demo_windows():
1500 #
1501 # Example 1: Connecting several subprocesses
1502 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001503 print("Looking for 'PROMPT' in set output...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001504 p1 = Popen("set", stdout=PIPE, shell=True)
1505 p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001506 print(repr(p2.communicate()[0]))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001507
1508 #
1509 # Example 2: Simple execution of program
1510 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001511 print("Executing calc...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001512 p = Popen("calc")
1513 p.wait()
1514
1515
1516if __name__ == "__main__":
1517 if mswindows:
1518 _demo_windows()
1519 else:
1520 _demo_posix()