blob: d9c76d8ad58b5c8160f62767d73e5cdc7cc3e687 [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 +000020
21Information about how the subprocess module can be used to replace these
22modules and functions can be found below.
23
24
25
26Using the subprocess module
27===========================
28This module defines one class called Popen:
29
30class Popen(args, bufsize=0, executable=None,
31 stdin=None, stdout=None, stderr=None,
32 preexec_fn=None, close_fds=False, shell=False,
33 cwd=None, env=None, universal_newlines=False,
34 startupinfo=None, creationflags=0):
35
36
37Arguments are:
38
39args should be a string, or a sequence of program arguments. The
40program to execute is normally the first item in the args sequence or
41string, but can be explicitly set by using the executable argument.
42
43On UNIX, with shell=False (default): In this case, the Popen class
44uses os.execvp() to execute the child program. args should normally
45be a sequence. A string will be treated as a sequence with the string
46as the only item (the program to execute).
47
48On UNIX, with shell=True: If args is a string, it specifies the
49command string to execute through the shell. If args is a sequence,
50the first item specifies the command string, and any additional items
51will be treated as additional shell arguments.
52
53On Windows: the Popen class uses CreateProcess() to execute the child
54program, which operates on strings. If args is a sequence, it will be
55converted to a string using the list2cmdline method. Please note that
56not all MS Windows applications interpret the command line the same
57way: The list2cmdline is designed for applications using the same
58rules as the MS C runtime.
59
60bufsize, if given, has the same meaning as the corresponding argument
61to the built-in open() function: 0 means unbuffered, 1 means line
62buffered, any other positive value means use a buffer of
63(approximately) that size. A negative bufsize means to use the system
64default, which usually means fully buffered. The default value for
65bufsize is 0 (unbuffered).
66
67stdin, stdout and stderr specify the executed programs' standard
68input, standard output and standard error file handles, respectively.
69Valid values are PIPE, an existing file descriptor (a positive
70integer), an existing file object, and None. PIPE indicates that a
71new pipe to the child should be created. With None, no redirection
72will occur; the child's file handles will be inherited from the
73parent. Additionally, stderr can be STDOUT, which indicates that the
74stderr data from the applications should be captured into the same
75file handle as for stdout.
76
77If preexec_fn is set to a callable object, this object will be called
78in the child process just before the child is executed.
79
80If close_fds is true, all file descriptors except 0, 1 and 2 will be
81closed before the child process is executed.
82
83if shell is true, the specified command will be executed through the
84shell.
85
86If cwd is not None, the current directory will be changed to cwd
87before the child is executed.
88
89If env is not None, it defines the environment variables for the new
90process.
91
92If universal_newlines is true, the file objects stdout and stderr are
93opened as a text files, but lines may be terminated by any of '\n',
94the Unix end-of-line convention, '\r', the Macintosh convention or
95'\r\n', the Windows convention. All of these external representations
96are seen as '\n' by the Python program. Note: This feature is only
97available if Python is built with universal newline support (the
98default). Also, the newlines attribute of the file objects stdout,
99stdin and stderr are not updated by the communicate() method.
100
101The startupinfo and creationflags, if given, will be passed to the
102underlying CreateProcess() function. They can specify things such as
103appearance of the main window and priority for the new process.
104(Windows only)
105
106
Brett Cannona23810f2008-05-26 19:04:21 +0000107This module also defines four shortcut functions:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000108
Peter Astrand5f5e1412004-12-05 20:15:36 +0000109call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000110 Run command with arguments. Wait for command to complete, then
111 return the returncode attribute.
112
113 The arguments are the same as for the Popen constructor. Example:
114
115 retcode = call(["ls", "-l"])
116
Peter Astrand454f7672005-01-01 09:36:35 +0000117check_call(*popenargs, **kwargs):
118 Run command with arguments. Wait for command to complete. If the
119 exit code was zero then return, otherwise raise
120 CalledProcessError. The CalledProcessError object will have the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000121 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000122
123 The arguments are the same as for the Popen constructor. Example:
124
125 check_call(["ls", "-l"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000126
Brett Cannona23810f2008-05-26 19:04:21 +0000127getstatusoutput(cmd):
128 Return (status, output) of executing cmd in a shell.
129
130 Execute the string 'cmd' in a shell with os.popen() and return a 2-tuple
131 (status, output). cmd is actually run as '{ cmd ; } 2>&1', so that the
132 returned output will contain output or error messages. A trailing newline
133 is stripped from the output. The exit status for the command can be
134 interpreted according to the rules for the C function wait(). Example:
135
136 >>> import subprocess
137 >>> subprocess.getstatusoutput('ls /bin/ls')
138 (0, '/bin/ls')
139 >>> subprocess.getstatusoutput('cat /bin/junk')
140 (256, 'cat: /bin/junk: No such file or directory')
141 >>> subprocess.getstatusoutput('/bin/junk')
142 (256, 'sh: /bin/junk: not found')
143
144getoutput(cmd):
145 Return output (stdout or stderr) of executing cmd in a shell.
146
147 Like getstatusoutput(), except the exit status is ignored and the return
148 value is a string containing the command's output. Example:
149
150 >>> import subprocess
151 >>> subprocess.getoutput('ls /bin/ls')
152 '/bin/ls'
153
154
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000155Exceptions
156----------
157Exceptions raised in the child process, before the new program has
158started to execute, will be re-raised in the parent. Additionally,
159the exception object will have one extra attribute called
160'child_traceback', which is a string containing traceback information
161from the childs point of view.
162
163The most common exception raised is OSError. This occurs, for
164example, when trying to execute a non-existent file. Applications
165should prepare for OSErrors.
166
167A ValueError will be raised if Popen is called with invalid arguments.
168
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000169check_call() will raise CalledProcessError, if the called process
170returns a non-zero return code.
Peter Astrand454f7672005-01-01 09:36:35 +0000171
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000172
173Security
174--------
175Unlike some other popen functions, this implementation will never call
176/bin/sh implicitly. This means that all characters, including shell
177metacharacters, can safely be passed to child processes.
178
179
180Popen objects
181=============
182Instances of the Popen class have the following methods:
183
184poll()
185 Check if child process has terminated. Returns returncode
186 attribute.
187
188wait()
189 Wait for child process to terminate. Returns returncode attribute.
190
191communicate(input=None)
192 Interact with process: Send data to stdin. Read data from stdout
193 and stderr, until end-of-file is reached. Wait for process to
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000194 terminate. The optional input argument should be a string to be
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000195 sent to the child process, or None, if no data should be sent to
196 the child.
Tim Peterse718f612004-10-12 21:51:32 +0000197
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000198 communicate() returns a tuple (stdout, stderr).
199
200 Note: The data read is buffered in memory, so do not use this
201 method if the data size is large or unlimited.
202
203The following attributes are also available:
204
205stdin
206 If the stdin argument is PIPE, this attribute is a file object
207 that provides input to the child process. Otherwise, it is None.
208
209stdout
210 If the stdout argument is PIPE, this attribute is a file object
211 that provides output from the child process. Otherwise, it is
212 None.
213
214stderr
215 If the stderr argument is PIPE, this attribute is file object that
216 provides error output from the child process. Otherwise, it is
217 None.
218
219pid
220 The process ID of the child process.
221
222returncode
223 The child return code. A None value indicates that the process
224 hasn't terminated yet. A negative value -N indicates that the
225 child was terminated by signal N (UNIX only).
226
227
228Replacing older functions with the subprocess module
229====================================================
230In this section, "a ==> b" means that b can be used as a replacement
231for a.
232
233Note: All functions in this section fail (more or less) silently if
234the executed program cannot be found; this module raises an OSError
235exception.
236
237In the following examples, we assume that the subprocess module is
238imported with "from subprocess import *".
239
240
241Replacing /bin/sh shell backquote
242---------------------------------
243output=`mycmd myarg`
244==>
245output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
246
247
248Replacing shell pipe line
249-------------------------
250output=`dmesg | grep hda`
251==>
252p1 = Popen(["dmesg"], stdout=PIPE)
Peter Astrand6fdf3cb2004-11-30 18:06:42 +0000253p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000254output = p2.communicate()[0]
255
256
257Replacing os.system()
258---------------------
259sts = os.system("mycmd" + " myarg")
260==>
261p = Popen("mycmd" + " myarg", shell=True)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000262pid, sts = os.waitpid(p.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000263
264Note:
265
266* Calling the program through the shell is usually not required.
267
268* It's easier to look at the returncode attribute than the
269 exitstatus.
270
271A more real-world example would look like this:
272
273try:
274 retcode = call("mycmd" + " myarg", shell=True)
275 if retcode < 0:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000276 print("Child was terminated by signal", -retcode, file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000277 else:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000278 print("Child returned", retcode, file=sys.stderr)
279except OSError as e:
280 print("Execution failed:", e, file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000281
282
283Replacing os.spawn*
284-------------------
Tim Peterse718f612004-10-12 21:51:32 +0000285P_NOWAIT example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000286
287pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
288==>
289pid = Popen(["/bin/mycmd", "myarg"]).pid
290
291
292P_WAIT example:
293
294retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
295==>
296retcode = call(["/bin/mycmd", "myarg"])
297
298
Tim Peterse718f612004-10-12 21:51:32 +0000299Vector example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000300
301os.spawnvp(os.P_NOWAIT, path, args)
302==>
303Popen([path] + args[1:])
304
305
Tim Peterse718f612004-10-12 21:51:32 +0000306Environment example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000307
308os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
309==>
310Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000311"""
312
313import sys
314mswindows = (sys.platform == "win32")
315
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000316import io
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000317import os
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000318import traceback
Christian Heimesfdab48e2008-01-20 09:06:41 +0000319import gc
Christian Heimesa342c012008-04-20 21:01:16 +0000320import signal
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000321
Peter Astrand454f7672005-01-01 09:36:35 +0000322# Exception classes used by this module.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000323class CalledProcessError(Exception):
Peter Astrand454f7672005-01-01 09:36:35 +0000324 """This exception is raised when a process run by check_call() returns
325 a non-zero exit status. The exit status will be stored in the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000326 returncode attribute."""
327 def __init__(self, returncode, cmd):
328 self.returncode = returncode
329 self.cmd = cmd
330 def __str__(self):
331 return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
332
Peter Astrand454f7672005-01-01 09:36:35 +0000333
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000334if mswindows:
335 import threading
336 import msvcrt
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000337 if 0: # <-- change this to use pywin32 instead of the _subprocess driver
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000338 import pywintypes
Tim Peterse8374a52004-10-13 03:15:00 +0000339 from win32api import GetStdHandle, STD_INPUT_HANDLE, \
340 STD_OUTPUT_HANDLE, STD_ERROR_HANDLE
341 from win32api import GetCurrentProcess, DuplicateHandle, \
342 GetModuleFileName, GetVersion
Peter Astrandc1d65362004-11-07 14:30:34 +0000343 from win32con import DUPLICATE_SAME_ACCESS, SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000344 from win32pipe import CreatePipe
Tim Peterse8374a52004-10-13 03:15:00 +0000345 from win32process import CreateProcess, STARTUPINFO, \
346 GetExitCodeProcess, STARTF_USESTDHANDLES, \
Peter Astrandc1d65362004-11-07 14:30:34 +0000347 STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE
Christian Heimesa342c012008-04-20 21:01:16 +0000348 from win32process import TerminateProcess
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000349 from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000350 else:
351 from _subprocess import *
352 class STARTUPINFO:
353 dwFlags = 0
354 hStdInput = None
355 hStdOutput = None
356 hStdError = None
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000357 wShowWindow = 0
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000358 class pywintypes:
359 error = IOError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000360else:
361 import select
362 import errno
363 import fcntl
364 import pickle
365
Brett Cannona23810f2008-05-26 19:04:21 +0000366__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "getstatusoutput",
367 "getoutput", "CalledProcessError"]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000368
369try:
370 MAXFD = os.sysconf("SC_OPEN_MAX")
371except:
372 MAXFD = 256
373
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000374_active = []
375
376def _cleanup():
377 for inst in _active[:]:
Christian Heimesa37d4c62007-12-04 23:02:19 +0000378 res = inst.poll(_deadstate=sys.maxsize)
Guido van Rossumb5d47ef2006-08-24 02:27:45 +0000379 if res is not None and res >= 0:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000380 try:
381 _active.remove(inst)
382 except ValueError:
383 # This can happen if two threads create a new Popen instance.
384 # It's harmless that it was already removed, so ignore.
385 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000386
387PIPE = -1
388STDOUT = -2
389
390
Peter Astrand5f5e1412004-12-05 20:15:36 +0000391def call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000392 """Run command with arguments. Wait for command to complete, then
393 return the returncode attribute.
394
395 The arguments are the same as for the Popen constructor. Example:
396
397 retcode = call(["ls", "-l"])
398 """
Peter Astrand5f5e1412004-12-05 20:15:36 +0000399 return Popen(*popenargs, **kwargs).wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000400
401
Peter Astrand454f7672005-01-01 09:36:35 +0000402def check_call(*popenargs, **kwargs):
403 """Run command with arguments. Wait for command to complete. If
404 the exit code was zero then return, otherwise raise
405 CalledProcessError. The CalledProcessError object will have the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000406 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000407
408 The arguments are the same as for the Popen constructor. Example:
409
410 check_call(["ls", "-l"])
411 """
412 retcode = call(*popenargs, **kwargs)
413 cmd = kwargs.get("args")
414 if cmd is None:
415 cmd = popenargs[0]
416 if retcode:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000417 raise CalledProcessError(retcode, cmd)
Peter Astrand454f7672005-01-01 09:36:35 +0000418 return retcode
419
420
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000421def list2cmdline(seq):
422 """
423 Translate a sequence of arguments into a command line
424 string, using the same rules as the MS C runtime:
425
426 1) Arguments are delimited by white space, which is either a
427 space or a tab.
428
429 2) A string surrounded by double quotation marks is
430 interpreted as a single argument, regardless of white space
Christian Heimesfdab48e2008-01-20 09:06:41 +0000431 or pipe characters contained within. A quoted string can be
432 embedded in an argument.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000433
434 3) A double quotation mark preceded by a backslash is
435 interpreted as a literal double quotation mark.
436
437 4) Backslashes are interpreted literally, unless they
438 immediately precede a double quotation mark.
439
440 5) If backslashes immediately precede a double quotation mark,
441 every pair of backslashes is interpreted as a literal
442 backslash. If the number of backslashes is odd, the last
443 backslash escapes the next double quotation mark as
444 described in rule 3.
445 """
446
447 # See
448 # http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp
449 result = []
450 needquote = False
451 for arg in seq:
452 bs_buf = []
453
454 # Add a space to separate this argument from the others
455 if result:
456 result.append(' ')
457
Christian Heimesfdab48e2008-01-20 09:06:41 +0000458 needquote = (" " in arg) or ("\t" in arg) or ("|" in arg) or not arg
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000459 if needquote:
460 result.append('"')
461
462 for c in arg:
463 if c == '\\':
Tim Peterse718f612004-10-12 21:51:32 +0000464 # Don't know if we need to double yet.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000465 bs_buf.append(c)
466 elif c == '"':
Christian Heimesfdab48e2008-01-20 09:06:41 +0000467 # Double backslashes.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000468 result.append('\\' * len(bs_buf)*2)
469 bs_buf = []
470 result.append('\\"')
471 else:
472 # Normal char
473 if bs_buf:
474 result.extend(bs_buf)
475 bs_buf = []
476 result.append(c)
477
Christian Heimesfdab48e2008-01-20 09:06:41 +0000478 # Add remaining backslashes, if any.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000479 if bs_buf:
480 result.extend(bs_buf)
481
482 if needquote:
Peter Astrand7e78ade2005-03-03 21:10:23 +0000483 result.extend(bs_buf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000484 result.append('"')
485
486 return ''.join(result)
487
488
Brett Cannona23810f2008-05-26 19:04:21 +0000489# Various tools for executing commands and looking at their output and status.
490#
491# NB This only works (and is only relevant) for UNIX.
492
493def getstatusoutput(cmd):
494 """Return (status, output) of executing cmd in a shell.
495
496 Execute the string 'cmd' in a shell with os.popen() and return a 2-tuple
497 (status, output). cmd is actually run as '{ cmd ; } 2>&1', so that the
498 returned output will contain output or error messages. A trailing newline
499 is stripped from the output. The exit status for the command can be
500 interpreted according to the rules for the C function wait(). Example:
501
502 >>> import subprocess
503 >>> subprocess.getstatusoutput('ls /bin/ls')
504 (0, '/bin/ls')
505 >>> subprocess.getstatusoutput('cat /bin/junk')
506 (256, 'cat: /bin/junk: No such file or directory')
507 >>> subprocess.getstatusoutput('/bin/junk')
508 (256, 'sh: /bin/junk: not found')
509 """
510 pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
511 text = pipe.read()
512 sts = pipe.close()
513 if sts is None: sts = 0
514 if text[-1:] == '\n': text = text[:-1]
515 return sts, text
516
517
518def getoutput(cmd):
519 """Return output (stdout or stderr) of executing cmd in a shell.
520
521 Like getstatusoutput(), except the exit status is ignored and the return
522 value is a string containing the command's output. Example:
523
524 >>> import subprocess
525 >>> subprocess.getoutput('ls /bin/ls')
526 '/bin/ls'
527 """
528 return getstatusoutput(cmd)[1]
529
530
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000531class Popen(object):
532 def __init__(self, args, bufsize=0, executable=None,
533 stdin=None, stdout=None, stderr=None,
534 preexec_fn=None, close_fds=False, shell=False,
535 cwd=None, env=None, universal_newlines=False,
536 startupinfo=None, creationflags=0):
537 """Create new Popen instance."""
538 _cleanup()
539
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000540 self._child_created = False
Guido van Rossum46a05a72007-06-07 21:56:45 +0000541 if bufsize is None:
542 bufsize = 0 # Restore default
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000543 if not isinstance(bufsize, int):
Peter Astrand738131d2004-11-30 21:04:45 +0000544 raise TypeError("bufsize must be an integer")
545
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000546 if mswindows:
Tim Peterse8374a52004-10-13 03:15:00 +0000547 if preexec_fn is not None:
548 raise ValueError("preexec_fn is not supported on Windows "
549 "platforms")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000550 if close_fds and (stdin is not None or stdout is not None or
551 stderr is not None):
Tim Peterse8374a52004-10-13 03:15:00 +0000552 raise ValueError("close_fds is not supported on Windows "
Guido van Rossume7ba4952007-06-06 23:52:48 +0000553 "platforms if you redirect stdin/stdout/stderr")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000554 else:
555 # POSIX
Tim Peterse8374a52004-10-13 03:15:00 +0000556 if startupinfo is not None:
557 raise ValueError("startupinfo is only supported on Windows "
558 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000559 if creationflags != 0:
Tim Peterse8374a52004-10-13 03:15:00 +0000560 raise ValueError("creationflags is only supported on Windows "
561 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000562
Tim Peterse718f612004-10-12 21:51:32 +0000563 self.stdin = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000564 self.stdout = None
565 self.stderr = None
566 self.pid = None
567 self.returncode = None
568 self.universal_newlines = universal_newlines
569
570 # Input and output objects. The general principle is like
571 # this:
572 #
573 # Parent Child
574 # ------ -----
575 # p2cwrite ---stdin---> p2cread
576 # c2pread <--stdout--- c2pwrite
577 # errread <--stderr--- errwrite
578 #
579 # On POSIX, the child objects are file descriptors. On
580 # Windows, these are Windows file handles. The parent objects
581 # are file descriptors on both platforms. The parent objects
582 # are None when not using PIPEs. The child objects are None
583 # when not redirecting.
Tim Peterse718f612004-10-12 21:51:32 +0000584
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000585 (p2cread, p2cwrite,
586 c2pread, c2pwrite,
587 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
588
589 self._execute_child(args, executable, preexec_fn, close_fds,
590 cwd, env, universal_newlines,
591 startupinfo, creationflags, shell,
592 p2cread, p2cwrite,
593 c2pread, c2pwrite,
594 errread, errwrite)
595
Thomas Wouterscf297e42007-02-23 15:07:44 +0000596 # On Windows, you cannot just redirect one or two handles: You
597 # either have to redirect all three or none. If the subprocess
598 # user has only redirected one or two handles, we are
599 # automatically creating PIPEs for the rest. We should close
Guido van Rossumd8faa362007-04-27 19:54:29 +0000600 # these after the process is started. See bug #1124861.
Thomas Wouterscf297e42007-02-23 15:07:44 +0000601 if mswindows:
602 if stdin is None and p2cwrite is not None:
603 os.close(p2cwrite)
604 p2cwrite = None
605 if stdout is None and c2pread is not None:
606 os.close(c2pread)
607 c2pread = None
608 if stderr is None and errread is not None:
609 os.close(errread)
610 errread = None
611
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000612 if bufsize == 0:
613 bufsize = 1 # Nearly unbuffered (XXX for now)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000614 if p2cwrite is not None:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000615 self.stdin = io.open(p2cwrite, 'wb', bufsize)
616 if self.universal_newlines:
617 self.stdin = io.TextIOWrapper(self.stdin)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000618 if c2pread is not None:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000619 self.stdout = io.open(c2pread, 'rb', bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000620 if universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000621 self.stdout = io.TextIOWrapper(self.stdout)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000622 if errread is not None:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000623 self.stderr = io.open(errread, 'rb', bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000624 if universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000625 self.stderr = io.TextIOWrapper(self.stderr)
Tim Peterse718f612004-10-12 21:51:32 +0000626
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000627
Guido van Rossum98297ee2007-11-06 21:34:58 +0000628 def _translate_newlines(self, data, encoding):
629 data = data.replace(b"\r\n", b"\n").replace(b"\r", b"\n")
630 return data.decode(encoding)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000631
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000632
Guido van Rossumd8faa362007-04-27 19:54:29 +0000633 def __del__(self, sys=sys):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000634 if not self._child_created:
635 # We didn't get to successfully create a child process.
636 return
637 # In case the child hasn't been waited on, check if it's done.
Christian Heimesa37d4c62007-12-04 23:02:19 +0000638 self.poll(_deadstate=sys.maxsize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000639 if self.returncode is None and _active is not None:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000640 # Child is still running, keep us alive until we can wait on it.
641 _active.append(self)
642
643
Peter Astrand23109f02005-03-03 20:28:59 +0000644 def communicate(self, input=None):
645 """Interact with process: Send data to stdin. Read data from
646 stdout and stderr, until end-of-file is reached. Wait for
647 process to terminate. The optional input argument should be a
648 string to be sent to the child process, or None, if no data
649 should be sent to the child.
Tim Peterseba28be2005-03-28 01:08:02 +0000650
Peter Astrand23109f02005-03-03 20:28:59 +0000651 communicate() returns a tuple (stdout, stderr)."""
652
653 # Optimization: If we are only using one pipe, or no pipe at
654 # all, using select() or threads is unnecessary.
655 if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
Tim Peterseba28be2005-03-28 01:08:02 +0000656 stdout = None
657 stderr = None
Peter Astrand23109f02005-03-03 20:28:59 +0000658 if self.stdin:
659 if input:
660 self.stdin.write(input)
661 self.stdin.close()
662 elif self.stdout:
663 stdout = self.stdout.read()
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000664 self.stdout.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000665 elif self.stderr:
666 stderr = self.stderr.read()
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000667 self.stderr.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000668 self.wait()
669 return (stdout, stderr)
Tim Peterseba28be2005-03-28 01:08:02 +0000670
Peter Astrand23109f02005-03-03 20:28:59 +0000671 return self._communicate(input)
672
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000673
674 if mswindows:
675 #
676 # Windows methods
677 #
678 def _get_handles(self, stdin, stdout, stderr):
679 """Construct and return tupel with IO objects:
680 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
681 """
Peter Astrandd38ddf42005-02-10 08:32:50 +0000682 if stdin is None and stdout is None and stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000683 return (None, None, None, None, None, None)
Tim Peterse718f612004-10-12 21:51:32 +0000684
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000685 p2cread, p2cwrite = None, None
686 c2pread, c2pwrite = None, None
687 errread, errwrite = None, None
688
Peter Astrandd38ddf42005-02-10 08:32:50 +0000689 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000690 p2cread = GetStdHandle(STD_INPUT_HANDLE)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000691 if p2cread is not None:
692 pass
693 elif stdin is None or stdin == PIPE:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000694 p2cread, p2cwrite = CreatePipe(None, 0)
695 # Detach and turn into fd
696 p2cwrite = p2cwrite.Detach()
697 p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000698 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000699 p2cread = msvcrt.get_osfhandle(stdin)
700 else:
701 # Assuming file-like object
702 p2cread = msvcrt.get_osfhandle(stdin.fileno())
703 p2cread = self._make_inheritable(p2cread)
704
Peter Astrandd38ddf42005-02-10 08:32:50 +0000705 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000706 c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000707 if c2pwrite is not None:
708 pass
709 elif stdout is None or stdout == PIPE:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000710 c2pread, c2pwrite = CreatePipe(None, 0)
711 # Detach and turn into fd
712 c2pread = c2pread.Detach()
713 c2pread = msvcrt.open_osfhandle(c2pread, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000714 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000715 c2pwrite = msvcrt.get_osfhandle(stdout)
716 else:
717 # Assuming file-like object
718 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
719 c2pwrite = self._make_inheritable(c2pwrite)
720
Peter Astrandd38ddf42005-02-10 08:32:50 +0000721 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000722 errwrite = GetStdHandle(STD_ERROR_HANDLE)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000723 if errwrite is not None:
724 pass
725 elif stderr is None or stderr == PIPE:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000726 errread, errwrite = CreatePipe(None, 0)
727 # Detach and turn into fd
728 errread = errread.Detach()
729 errread = msvcrt.open_osfhandle(errread, 0)
730 elif stderr == STDOUT:
731 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000732 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000733 errwrite = msvcrt.get_osfhandle(stderr)
734 else:
735 # Assuming file-like object
736 errwrite = msvcrt.get_osfhandle(stderr.fileno())
737 errwrite = self._make_inheritable(errwrite)
738
739 return (p2cread, p2cwrite,
740 c2pread, c2pwrite,
741 errread, errwrite)
742
743
744 def _make_inheritable(self, handle):
745 """Return a duplicate of handle, which is inheritable"""
746 return DuplicateHandle(GetCurrentProcess(), handle,
747 GetCurrentProcess(), 0, 1,
748 DUPLICATE_SAME_ACCESS)
749
750
751 def _find_w9xpopen(self):
752 """Find and return absolut path to w9xpopen.exe"""
Tim Peterse8374a52004-10-13 03:15:00 +0000753 w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)),
754 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000755 if not os.path.exists(w9xpopen):
756 # Eeek - file-not-found - possibly an embedding
757 # situation - see if we can locate it in sys.exec_prefix
Tim Peterse8374a52004-10-13 03:15:00 +0000758 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
759 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000760 if not os.path.exists(w9xpopen):
Tim Peterse8374a52004-10-13 03:15:00 +0000761 raise RuntimeError("Cannot locate w9xpopen.exe, which is "
762 "needed for Popen to work with your "
763 "shell or platform.")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000764 return w9xpopen
765
Tim Peterse718f612004-10-12 21:51:32 +0000766
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000767 def _execute_child(self, args, executable, preexec_fn, close_fds,
768 cwd, env, universal_newlines,
769 startupinfo, creationflags, shell,
770 p2cread, p2cwrite,
771 c2pread, c2pwrite,
772 errread, errwrite):
773 """Execute program (MS Windows version)"""
774
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000775 if not isinstance(args, str):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000776 args = list2cmdline(args)
777
Peter Astrandc1d65362004-11-07 14:30:34 +0000778 # Process startup details
Peter Astrandd38ddf42005-02-10 08:32:50 +0000779 if startupinfo is None:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000780 startupinfo = STARTUPINFO()
781 if None not in (p2cread, c2pwrite, errwrite):
Peter Astrandc1d65362004-11-07 14:30:34 +0000782 startupinfo.dwFlags |= STARTF_USESTDHANDLES
783 startupinfo.hStdInput = p2cread
784 startupinfo.hStdOutput = c2pwrite
785 startupinfo.hStdError = errwrite
786
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000787 if shell:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000788 startupinfo.dwFlags |= STARTF_USESHOWWINDOW
789 startupinfo.wShowWindow = SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000790 comspec = os.environ.get("COMSPEC", "cmd.exe")
791 args = comspec + " /c " + args
Guido van Rossume2a383d2007-01-15 16:59:06 +0000792 if (GetVersion() >= 0x80000000 or
Tim Peterse8374a52004-10-13 03:15:00 +0000793 os.path.basename(comspec).lower() == "command.com"):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000794 # Win9x, or using command.com on NT. We need to
795 # use the w9xpopen intermediate program. For more
796 # information, see KB Q150956
797 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
798 w9xpopen = self._find_w9xpopen()
799 args = '"%s" %s' % (w9xpopen, args)
800 # Not passing CREATE_NEW_CONSOLE has been known to
801 # cause random failures on win9x. Specifically a
802 # dialog: "Your program accessed mem currently in
803 # use at xxx" and a hopeful warning about the
804 # stability of your system. Cost is Ctrl+C wont
805 # kill children.
806 creationflags |= CREATE_NEW_CONSOLE
807
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000808 # Start the process
809 try:
810 hp, ht, pid, tid = CreateProcess(executable, args,
Tim Peterse8374a52004-10-13 03:15:00 +0000811 # no special security
812 None, None,
Guido van Rossume7ba4952007-06-06 23:52:48 +0000813 int(not close_fds),
Tim Peterse8374a52004-10-13 03:15:00 +0000814 creationflags,
815 env,
816 cwd,
817 startupinfo)
Guido van Rossumb940e112007-01-10 16:19:56 +0000818 except pywintypes.error as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000819 # Translate pywintypes.error to WindowsError, which is
820 # a subclass of OSError. FIXME: We should really
821 # translate errno using _sys_errlist (or simliar), but
822 # how can this be done from Python?
823 raise WindowsError(*e.args)
824
825 # Retain the process handle, but close the thread handle
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000826 self._child_created = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000827 self._handle = hp
828 self.pid = pid
829 ht.Close()
830
Andrew M. Kuchling51ee66e2004-10-12 16:38:42 +0000831 # Child is launched. Close the parent's copy of those pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000832 # handles that only the child should have open. You need
833 # to make sure that no handles to the write end of the
834 # output pipe are maintained in this process or else the
835 # pipe will not close when the child process exits and the
836 # ReadFile will hang.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000837 if p2cread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000838 p2cread.Close()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000839 if c2pwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000840 c2pwrite.Close()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000841 if errwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000842 errwrite.Close()
843
Tim Peterse718f612004-10-12 21:51:32 +0000844
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000845 def poll(self, _deadstate=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000846 """Check if child process has terminated. Returns returncode
847 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000848 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000849 if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
850 self.returncode = GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000851 return self.returncode
852
853
854 def wait(self):
855 """Wait for child process to terminate. Returns returncode
856 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000857 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000858 obj = WaitForSingleObject(self._handle, INFINITE)
859 self.returncode = GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000860 return self.returncode
861
862
863 def _readerthread(self, fh, buffer):
864 buffer.append(fh.read())
865
866
Peter Astrand23109f02005-03-03 20:28:59 +0000867 def _communicate(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000868 stdout = None # Return
869 stderr = None # Return
870
871 if self.stdout:
872 stdout = []
Tim Peterse8374a52004-10-13 03:15:00 +0000873 stdout_thread = threading.Thread(target=self._readerthread,
874 args=(self.stdout, stdout))
Benjamin Peterson2d9a0862008-06-13 01:31:43 +0000875 stdout_thread.set_daemon(True)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000876 stdout_thread.start()
877 if self.stderr:
878 stderr = []
Tim Peterse8374a52004-10-13 03:15:00 +0000879 stderr_thread = threading.Thread(target=self._readerthread,
880 args=(self.stderr, stderr))
Benjamin Peterson2d9a0862008-06-13 01:31:43 +0000881 stderr_thread.set_daemon(True)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000882 stderr_thread.start()
883
884 if self.stdin:
Peter Astrandd38ddf42005-02-10 08:32:50 +0000885 if input is not None:
Guido van Rossumc12a8132007-10-26 04:29:23 +0000886 if isinstance(input, str):
887 input = input.encode()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000888 self.stdin.write(input)
889 self.stdin.close()
890
891 if self.stdout:
892 stdout_thread.join()
893 if self.stderr:
894 stderr_thread.join()
895
896 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000897 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000898 stdout = stdout[0]
Peter Astrandd38ddf42005-02-10 08:32:50 +0000899 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000900 stderr = stderr[0]
901
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000902 self.wait()
903 return (stdout, stderr)
904
Christian Heimesa342c012008-04-20 21:01:16 +0000905 def send_signal(self, sig):
906 """Send a signal to the process
907 """
908 if sig == signal.SIGTERM:
909 self.terminate()
910 else:
911 raise ValueError("Only SIGTERM is supported on Windows")
912
913 def terminate(self):
914 """Terminates the process
915 """
916 TerminateProcess(self._handle, 1)
917
918 kill = terminate
919
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000920 else:
921 #
922 # POSIX methods
923 #
924 def _get_handles(self, stdin, stdout, stderr):
925 """Construct and return tupel with IO objects:
926 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
927 """
928 p2cread, p2cwrite = None, None
929 c2pread, c2pwrite = None, None
930 errread, errwrite = None, None
931
Peter Astrandd38ddf42005-02-10 08:32:50 +0000932 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000933 pass
934 elif stdin == PIPE:
935 p2cread, p2cwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000936 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000937 p2cread = stdin
938 else:
939 # Assuming file-like object
940 p2cread = stdin.fileno()
941
Peter Astrandd38ddf42005-02-10 08:32:50 +0000942 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000943 pass
944 elif stdout == PIPE:
945 c2pread, c2pwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000946 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000947 c2pwrite = stdout
948 else:
949 # Assuming file-like object
Tim Peterse718f612004-10-12 21:51:32 +0000950 c2pwrite = stdout.fileno()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000951
Peter Astrandd38ddf42005-02-10 08:32:50 +0000952 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000953 pass
954 elif stderr == PIPE:
955 errread, errwrite = os.pipe()
956 elif stderr == STDOUT:
957 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000958 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000959 errwrite = stderr
960 else:
961 # Assuming file-like object
962 errwrite = stderr.fileno()
963
964 return (p2cread, p2cwrite,
965 c2pread, c2pwrite,
966 errread, errwrite)
967
968
969 def _set_cloexec_flag(self, fd):
970 try:
971 cloexec_flag = fcntl.FD_CLOEXEC
972 except AttributeError:
973 cloexec_flag = 1
974
975 old = fcntl.fcntl(fd, fcntl.F_GETFD)
976 fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
977
978
979 def _close_fds(self, but):
Christian Heimesfdab48e2008-01-20 09:06:41 +0000980 os.closerange(3, but)
981 os.closerange(but + 1, MAXFD)
Tim Peterse718f612004-10-12 21:51:32 +0000982
983
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000984 def _execute_child(self, args, executable, preexec_fn, close_fds,
985 cwd, env, universal_newlines,
986 startupinfo, creationflags, shell,
987 p2cread, p2cwrite,
988 c2pread, c2pwrite,
989 errread, errwrite):
990 """Execute program (POSIX version)"""
991
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000992 if isinstance(args, str):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000993 args = [args]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000994 else:
995 args = list(args)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000996
997 if shell:
998 args = ["/bin/sh", "-c"] + args
999
Peter Astrandd38ddf42005-02-10 08:32:50 +00001000 if executable is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001001 executable = args[0]
1002
1003 # For transferring possible exec failure from child to parent
1004 # The first char specifies the exception type: 0 means
1005 # OSError, 1 means some other error.
1006 errpipe_read, errpipe_write = os.pipe()
1007 self._set_cloexec_flag(errpipe_write)
1008
Christian Heimesfdab48e2008-01-20 09:06:41 +00001009 gc_was_enabled = gc.isenabled()
1010 # Disable gc to avoid bug where gc -> file_dealloc ->
1011 # write to stderr -> hang. http://bugs.python.org/issue1336
1012 gc.disable()
1013 try:
1014 self.pid = os.fork()
1015 except:
1016 if gc_was_enabled:
1017 gc.enable()
1018 raise
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001019 self._child_created = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001020 if self.pid == 0:
1021 # Child
1022 try:
1023 # Close parent's pipe ends
Thomas Wouterscf297e42007-02-23 15:07:44 +00001024 if p2cwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001025 os.close(p2cwrite)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001026 if c2pread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001027 os.close(c2pread)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001028 if errread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001029 os.close(errread)
1030 os.close(errpipe_read)
1031
1032 # Dup fds for child
Thomas Wouterscf297e42007-02-23 15:07:44 +00001033 if p2cread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001034 os.dup2(p2cread, 0)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001035 if c2pwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001036 os.dup2(c2pwrite, 1)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001037 if errwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001038 os.dup2(errwrite, 2)
1039
Thomas Wouters89f507f2006-12-13 04:49:30 +00001040 # Close pipe fds. Make sure we don't close the same
1041 # fd more than once, or standard fds.
Thomas Wouterscf297e42007-02-23 15:07:44 +00001042 if p2cread is not None and p2cread not in (0,):
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001043 os.close(p2cread)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001044 if c2pwrite is not None and c2pwrite not in (p2cread, 1):
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001045 os.close(c2pwrite)
Guido van Rossum98297ee2007-11-06 21:34:58 +00001046 if (errwrite is not None and
1047 errwrite not in (p2cread, c2pwrite, 2)):
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001048 os.close(errwrite)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001049
1050 # Close all other fds, if asked for
1051 if close_fds:
1052 self._close_fds(but=errpipe_write)
1053
Peter Astrandd38ddf42005-02-10 08:32:50 +00001054 if cwd is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001055 os.chdir(cwd)
1056
1057 if preexec_fn:
Neal Norwitzd9108552006-03-17 08:00:19 +00001058 preexec_fn()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001059
Peter Astrandd38ddf42005-02-10 08:32:50 +00001060 if env is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001061 os.execvp(executable, args)
1062 else:
1063 os.execvpe(executable, args, env)
1064
1065 except:
1066 exc_type, exc_value, tb = sys.exc_info()
1067 # Save the traceback and attach it to the exception object
Tim Peterse8374a52004-10-13 03:15:00 +00001068 exc_lines = traceback.format_exception(exc_type,
1069 exc_value,
1070 tb)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001071 exc_value.child_traceback = ''.join(exc_lines)
1072 os.write(errpipe_write, pickle.dumps(exc_value))
1073
1074 # This exitcode won't be reported to applications, so it
1075 # really doesn't matter what we return.
1076 os._exit(255)
1077
1078 # Parent
Christian Heimesfdab48e2008-01-20 09:06:41 +00001079 if gc_was_enabled:
1080 gc.enable()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001081 os.close(errpipe_write)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001082 if p2cread is not None and p2cwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001083 os.close(p2cread)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001084 if c2pwrite is not None and c2pread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001085 os.close(c2pwrite)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001086 if errwrite is not None and errread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001087 os.close(errwrite)
1088
1089 # Wait for exec to fail or succeed; possibly raising exception
1090 data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB
1091 os.close(errpipe_read)
Guido van Rossumaf2362a2007-05-15 22:32:02 +00001092 if data:
Peter Astrandf791d7a2005-01-01 09:38:57 +00001093 os.waitpid(self.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001094 child_exception = pickle.loads(data)
1095 raise child_exception
1096
1097
1098 def _handle_exitstatus(self, sts):
1099 if os.WIFSIGNALED(sts):
1100 self.returncode = -os.WTERMSIG(sts)
1101 elif os.WIFEXITED(sts):
1102 self.returncode = os.WEXITSTATUS(sts)
1103 else:
1104 # Should never happen
1105 raise RuntimeError("Unknown child exit status!")
1106
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001107
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001108 def poll(self, _deadstate=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001109 """Check if child process has terminated. Returns returncode
1110 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001111 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001112 try:
1113 pid, sts = os.waitpid(self.pid, os.WNOHANG)
1114 if pid == self.pid:
1115 self._handle_exitstatus(sts)
1116 except os.error:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001117 if _deadstate is not None:
1118 self.returncode = _deadstate
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001119 return self.returncode
1120
1121
1122 def wait(self):
1123 """Wait for child process to terminate. Returns returncode
1124 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001125 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001126 pid, sts = os.waitpid(self.pid, 0)
1127 self._handle_exitstatus(sts)
1128 return self.returncode
1129
1130
Peter Astrand23109f02005-03-03 20:28:59 +00001131 def _communicate(self, input):
Guido van Rossumbae07c92007-10-08 02:46:15 +00001132 if self.stdin:
1133 if isinstance(input, str): # Unicode
1134 input = input.encode("utf-8") # XXX What else?
Guido van Rossum98297ee2007-11-06 21:34:58 +00001135 input = bytes(input)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001136 read_set = []
1137 write_set = []
1138 stdout = None # Return
1139 stderr = None # Return
1140
1141 if self.stdin:
1142 # Flush stdio buffer. This might block, if the user has
1143 # been writing to .stdin in an uncontrolled fashion.
1144 self.stdin.flush()
1145 if input:
1146 write_set.append(self.stdin)
1147 else:
1148 self.stdin.close()
1149 if self.stdout:
1150 read_set.append(self.stdout)
Tim Peterse718f612004-10-12 21:51:32 +00001151 stdout = []
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001152 if self.stderr:
1153 read_set.append(self.stderr)
1154 stderr = []
1155
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001156 input_offset = 0
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001157 while read_set or write_set:
1158 rlist, wlist, xlist = select.select(read_set, write_set, [])
1159
Guido van Rossum98297ee2007-11-06 21:34:58 +00001160 # XXX Rewrite these to use non-blocking I/O on the
1161 # file objects; they are no longer using C stdio!
1162
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001163 if self.stdin in wlist:
1164 # When select has indicated that the file is writable,
1165 # we can write up to PIPE_BUF bytes without risk
1166 # blocking. POSIX defines PIPE_BUF >= 512
Guido van Rossumbae07c92007-10-08 02:46:15 +00001167 chunk = input[input_offset : input_offset + 512]
1168 bytes_written = os.write(self.stdin.fileno(), chunk)
Thomas Wouters9fe394c2007-02-05 01:24:16 +00001169 input_offset += bytes_written
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001170 if input_offset >= len(input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001171 self.stdin.close()
1172 write_set.remove(self.stdin)
1173
1174 if self.stdout in rlist:
1175 data = os.read(self.stdout.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001176 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001177 self.stdout.close()
1178 read_set.remove(self.stdout)
1179 stdout.append(data)
1180
1181 if self.stderr in rlist:
1182 data = os.read(self.stderr.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001183 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001184 self.stderr.close()
1185 read_set.remove(self.stderr)
1186 stderr.append(data)
1187
1188 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +00001189 if stdout is not None:
Guido van Rossum98297ee2007-11-06 21:34:58 +00001190 stdout = b"".join(stdout)
Peter Astrandd38ddf42005-02-10 08:32:50 +00001191 if stderr is not None:
Guido van Rossum98297ee2007-11-06 21:34:58 +00001192 stderr = b"".join(stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001193
Guido van Rossum98297ee2007-11-06 21:34:58 +00001194 # Translate newlines, if requested.
1195 # This also turns bytes into strings.
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001196 if self.universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +00001197 if stdout is not None:
Guido van Rossum98297ee2007-11-06 21:34:58 +00001198 stdout = self._translate_newlines(stdout,
1199 self.stdout.encoding)
Guido van Rossumfa0054a2007-05-24 04:05:35 +00001200 if stderr is not None:
Guido van Rossum98297ee2007-11-06 21:34:58 +00001201 stderr = self._translate_newlines(stderr,
1202 self.stderr.encoding)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001203
1204 self.wait()
1205 return (stdout, stderr)
1206
Christian Heimesa342c012008-04-20 21:01:16 +00001207 def send_signal(self, sig):
1208 """Send a signal to the process
1209 """
1210 os.kill(self.pid, sig)
1211
1212 def terminate(self):
1213 """Terminate the process with SIGTERM
1214 """
1215 self.send_signal(signal.SIGTERM)
1216
1217 def kill(self):
1218 """Kill the process with SIGKILL
1219 """
1220 self.send_signal(signal.SIGKILL)
1221
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001222
1223def _demo_posix():
1224 #
1225 # Example 1: Simple redirection: Get process list
1226 #
1227 plist = Popen(["ps"], stdout=PIPE).communicate()[0]
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001228 print("Process list:")
1229 print(plist)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001230
1231 #
1232 # Example 2: Change uid before executing child
1233 #
1234 if os.getuid() == 0:
1235 p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1236 p.wait()
1237
1238 #
1239 # Example 3: Connecting several subprocesses
1240 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001241 print("Looking for 'hda'...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001242 p1 = Popen(["dmesg"], stdout=PIPE)
1243 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001244 print(repr(p2.communicate()[0]))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001245
1246 #
1247 # Example 4: Catch execution error
1248 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001249 print()
1250 print("Trying a weird file...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001251 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001252 print(Popen(["/this/path/does/not/exist"]).communicate())
Guido van Rossumb940e112007-01-10 16:19:56 +00001253 except OSError as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001254 if e.errno == errno.ENOENT:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001255 print("The file didn't exist. I thought so...")
1256 print("Child traceback:")
1257 print(e.child_traceback)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001258 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001259 print("Error", e.errno)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001260 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001261 print("Gosh. No error.", file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001262
1263
1264def _demo_windows():
1265 #
1266 # Example 1: Connecting several subprocesses
1267 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001268 print("Looking for 'PROMPT' in set output...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001269 p1 = Popen("set", stdout=PIPE, shell=True)
1270 p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001271 print(repr(p2.communicate()[0]))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001272
1273 #
1274 # Example 2: Simple execution of program
1275 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001276 print("Executing calc...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001277 p = Popen("calc")
1278 p.wait()
1279
1280
1281if __name__ == "__main__":
1282 if mswindows:
1283 _demo_windows()
1284 else:
1285 _demo_posix()