blob: ac92185b6f5d770af547d9e86f54b871da4539ee [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[:]:
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000378 res = inst._internal_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.
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000638 self._internal_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
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000674 def poll(self):
675 return self._internal_poll()
676
677
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000678 if mswindows:
679 #
680 # Windows methods
681 #
682 def _get_handles(self, stdin, stdout, stderr):
683 """Construct and return tupel with IO objects:
684 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
685 """
Peter Astrandd38ddf42005-02-10 08:32:50 +0000686 if stdin is None and stdout is None and stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000687 return (None, None, None, None, None, None)
Tim Peterse718f612004-10-12 21:51:32 +0000688
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000689 p2cread, p2cwrite = None, None
690 c2pread, c2pwrite = None, None
691 errread, errwrite = None, None
692
Peter Astrandd38ddf42005-02-10 08:32:50 +0000693 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000694 p2cread = GetStdHandle(STD_INPUT_HANDLE)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000695 if p2cread is not None:
696 pass
697 elif stdin is None or stdin == PIPE:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000698 p2cread, p2cwrite = CreatePipe(None, 0)
699 # Detach and turn into fd
700 p2cwrite = p2cwrite.Detach()
701 p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000702 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000703 p2cread = msvcrt.get_osfhandle(stdin)
704 else:
705 # Assuming file-like object
706 p2cread = msvcrt.get_osfhandle(stdin.fileno())
707 p2cread = self._make_inheritable(p2cread)
708
Peter Astrandd38ddf42005-02-10 08:32:50 +0000709 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000710 c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000711 if c2pwrite is not None:
712 pass
713 elif stdout is None or stdout == PIPE:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000714 c2pread, c2pwrite = CreatePipe(None, 0)
715 # Detach and turn into fd
716 c2pread = c2pread.Detach()
717 c2pread = msvcrt.open_osfhandle(c2pread, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000718 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000719 c2pwrite = msvcrt.get_osfhandle(stdout)
720 else:
721 # Assuming file-like object
722 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
723 c2pwrite = self._make_inheritable(c2pwrite)
724
Peter Astrandd38ddf42005-02-10 08:32:50 +0000725 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000726 errwrite = GetStdHandle(STD_ERROR_HANDLE)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000727 if errwrite is not None:
728 pass
729 elif stderr is None or stderr == PIPE:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000730 errread, errwrite = CreatePipe(None, 0)
731 # Detach and turn into fd
732 errread = errread.Detach()
733 errread = msvcrt.open_osfhandle(errread, 0)
734 elif stderr == STDOUT:
735 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000736 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000737 errwrite = msvcrt.get_osfhandle(stderr)
738 else:
739 # Assuming file-like object
740 errwrite = msvcrt.get_osfhandle(stderr.fileno())
741 errwrite = self._make_inheritable(errwrite)
742
743 return (p2cread, p2cwrite,
744 c2pread, c2pwrite,
745 errread, errwrite)
746
747
748 def _make_inheritable(self, handle):
749 """Return a duplicate of handle, which is inheritable"""
750 return DuplicateHandle(GetCurrentProcess(), handle,
751 GetCurrentProcess(), 0, 1,
752 DUPLICATE_SAME_ACCESS)
753
754
755 def _find_w9xpopen(self):
756 """Find and return absolut path to w9xpopen.exe"""
Tim Peterse8374a52004-10-13 03:15:00 +0000757 w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)),
758 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000759 if not os.path.exists(w9xpopen):
760 # Eeek - file-not-found - possibly an embedding
761 # situation - see if we can locate it in sys.exec_prefix
Tim Peterse8374a52004-10-13 03:15:00 +0000762 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
763 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000764 if not os.path.exists(w9xpopen):
Tim Peterse8374a52004-10-13 03:15:00 +0000765 raise RuntimeError("Cannot locate w9xpopen.exe, which is "
766 "needed for Popen to work with your "
767 "shell or platform.")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000768 return w9xpopen
769
Tim Peterse718f612004-10-12 21:51:32 +0000770
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000771 def _execute_child(self, args, executable, preexec_fn, close_fds,
772 cwd, env, universal_newlines,
773 startupinfo, creationflags, shell,
774 p2cread, p2cwrite,
775 c2pread, c2pwrite,
776 errread, errwrite):
777 """Execute program (MS Windows version)"""
778
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000779 if not isinstance(args, str):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000780 args = list2cmdline(args)
781
Peter Astrandc1d65362004-11-07 14:30:34 +0000782 # Process startup details
Peter Astrandd38ddf42005-02-10 08:32:50 +0000783 if startupinfo is None:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000784 startupinfo = STARTUPINFO()
785 if None not in (p2cread, c2pwrite, errwrite):
Peter Astrandc1d65362004-11-07 14:30:34 +0000786 startupinfo.dwFlags |= STARTF_USESTDHANDLES
787 startupinfo.hStdInput = p2cread
788 startupinfo.hStdOutput = c2pwrite
789 startupinfo.hStdError = errwrite
790
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000791 if shell:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000792 startupinfo.dwFlags |= STARTF_USESHOWWINDOW
793 startupinfo.wShowWindow = SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000794 comspec = os.environ.get("COMSPEC", "cmd.exe")
795 args = comspec + " /c " + args
Guido van Rossume2a383d2007-01-15 16:59:06 +0000796 if (GetVersion() >= 0x80000000 or
Tim Peterse8374a52004-10-13 03:15:00 +0000797 os.path.basename(comspec).lower() == "command.com"):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000798 # Win9x, or using command.com on NT. We need to
799 # use the w9xpopen intermediate program. For more
800 # information, see KB Q150956
801 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
802 w9xpopen = self._find_w9xpopen()
803 args = '"%s" %s' % (w9xpopen, args)
804 # Not passing CREATE_NEW_CONSOLE has been known to
805 # cause random failures on win9x. Specifically a
806 # dialog: "Your program accessed mem currently in
807 # use at xxx" and a hopeful warning about the
808 # stability of your system. Cost is Ctrl+C wont
809 # kill children.
810 creationflags |= CREATE_NEW_CONSOLE
811
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000812 # Start the process
813 try:
814 hp, ht, pid, tid = CreateProcess(executable, args,
Tim Peterse8374a52004-10-13 03:15:00 +0000815 # no special security
816 None, None,
Guido van Rossume7ba4952007-06-06 23:52:48 +0000817 int(not close_fds),
Tim Peterse8374a52004-10-13 03:15:00 +0000818 creationflags,
819 env,
820 cwd,
821 startupinfo)
Guido van Rossumb940e112007-01-10 16:19:56 +0000822 except pywintypes.error as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000823 # Translate pywintypes.error to WindowsError, which is
824 # a subclass of OSError. FIXME: We should really
825 # translate errno using _sys_errlist (or simliar), but
826 # how can this be done from Python?
827 raise WindowsError(*e.args)
828
829 # Retain the process handle, but close the thread handle
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000830 self._child_created = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000831 self._handle = hp
832 self.pid = pid
833 ht.Close()
834
Andrew M. Kuchling51ee66e2004-10-12 16:38:42 +0000835 # Child is launched. Close the parent's copy of those pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000836 # handles that only the child should have open. You need
837 # to make sure that no handles to the write end of the
838 # output pipe are maintained in this process or else the
839 # pipe will not close when the child process exits and the
840 # ReadFile will hang.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000841 if p2cread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000842 p2cread.Close()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000843 if c2pwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000844 c2pwrite.Close()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000845 if errwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000846 errwrite.Close()
847
Tim Peterse718f612004-10-12 21:51:32 +0000848
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000849 def _internal_poll(self, _deadstate=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000850 """Check if child process has terminated. Returns returncode
851 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000852 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000853 if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
854 self.returncode = GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000855 return self.returncode
856
857
858 def wait(self):
859 """Wait for child process to terminate. Returns returncode
860 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000861 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000862 obj = WaitForSingleObject(self._handle, INFINITE)
863 self.returncode = GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000864 return self.returncode
865
866
867 def _readerthread(self, fh, buffer):
868 buffer.append(fh.read())
869
870
Peter Astrand23109f02005-03-03 20:28:59 +0000871 def _communicate(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000872 stdout = None # Return
873 stderr = None # Return
874
875 if self.stdout:
876 stdout = []
Tim Peterse8374a52004-10-13 03:15:00 +0000877 stdout_thread = threading.Thread(target=self._readerthread,
878 args=(self.stdout, stdout))
Benjamin Peterson632e0362008-08-18 19:08:51 +0000879 stdout_thread.daemon = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000880 stdout_thread.start()
881 if self.stderr:
882 stderr = []
Tim Peterse8374a52004-10-13 03:15:00 +0000883 stderr_thread = threading.Thread(target=self._readerthread,
884 args=(self.stderr, stderr))
Benjamin Peterson632e0362008-08-18 19:08:51 +0000885 stderr_thread.daemon = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000886 stderr_thread.start()
887
888 if self.stdin:
Peter Astrandd38ddf42005-02-10 08:32:50 +0000889 if input is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000890 self.stdin.write(input)
891 self.stdin.close()
892
893 if self.stdout:
894 stdout_thread.join()
895 if self.stderr:
896 stderr_thread.join()
897
898 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000899 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000900 stdout = stdout[0]
Peter Astrandd38ddf42005-02-10 08:32:50 +0000901 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000902 stderr = stderr[0]
903
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000904 self.wait()
905 return (stdout, stderr)
906
Christian Heimesa342c012008-04-20 21:01:16 +0000907 def send_signal(self, sig):
908 """Send a signal to the process
909 """
910 if sig == signal.SIGTERM:
911 self.terminate()
912 else:
913 raise ValueError("Only SIGTERM is supported on Windows")
914
915 def terminate(self):
916 """Terminates the process
917 """
918 TerminateProcess(self._handle, 1)
919
920 kill = terminate
921
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000922 else:
923 #
924 # POSIX methods
925 #
926 def _get_handles(self, stdin, stdout, stderr):
927 """Construct and return tupel with IO objects:
928 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
929 """
930 p2cread, p2cwrite = None, None
931 c2pread, c2pwrite = None, None
932 errread, errwrite = None, None
933
Peter Astrandd38ddf42005-02-10 08:32:50 +0000934 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000935 pass
936 elif stdin == PIPE:
937 p2cread, p2cwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000938 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000939 p2cread = stdin
940 else:
941 # Assuming file-like object
942 p2cread = stdin.fileno()
943
Peter Astrandd38ddf42005-02-10 08:32:50 +0000944 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000945 pass
946 elif stdout == PIPE:
947 c2pread, c2pwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000948 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000949 c2pwrite = stdout
950 else:
951 # Assuming file-like object
Tim Peterse718f612004-10-12 21:51:32 +0000952 c2pwrite = stdout.fileno()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000953
Peter Astrandd38ddf42005-02-10 08:32:50 +0000954 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000955 pass
956 elif stderr == PIPE:
957 errread, errwrite = os.pipe()
958 elif stderr == STDOUT:
959 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000960 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000961 errwrite = stderr
962 else:
963 # Assuming file-like object
964 errwrite = stderr.fileno()
965
966 return (p2cread, p2cwrite,
967 c2pread, c2pwrite,
968 errread, errwrite)
969
970
971 def _set_cloexec_flag(self, fd):
972 try:
973 cloexec_flag = fcntl.FD_CLOEXEC
974 except AttributeError:
975 cloexec_flag = 1
976
977 old = fcntl.fcntl(fd, fcntl.F_GETFD)
978 fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
979
980
981 def _close_fds(self, but):
Christian Heimesfdab48e2008-01-20 09:06:41 +0000982 os.closerange(3, but)
983 os.closerange(but + 1, MAXFD)
Tim Peterse718f612004-10-12 21:51:32 +0000984
985
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000986 def _execute_child(self, args, executable, preexec_fn, close_fds,
987 cwd, env, universal_newlines,
988 startupinfo, creationflags, shell,
989 p2cread, p2cwrite,
990 c2pread, c2pwrite,
991 errread, errwrite):
992 """Execute program (POSIX version)"""
993
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000994 if isinstance(args, str):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000995 args = [args]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000996 else:
997 args = list(args)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000998
999 if shell:
1000 args = ["/bin/sh", "-c"] + args
1001
Peter Astrandd38ddf42005-02-10 08:32:50 +00001002 if executable is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001003 executable = args[0]
1004
1005 # For transferring possible exec failure from child to parent
1006 # The first char specifies the exception type: 0 means
1007 # OSError, 1 means some other error.
1008 errpipe_read, errpipe_write = os.pipe()
1009 self._set_cloexec_flag(errpipe_write)
1010
Christian Heimesfdab48e2008-01-20 09:06:41 +00001011 gc_was_enabled = gc.isenabled()
1012 # Disable gc to avoid bug where gc -> file_dealloc ->
1013 # write to stderr -> hang. http://bugs.python.org/issue1336
1014 gc.disable()
1015 try:
1016 self.pid = os.fork()
1017 except:
1018 if gc_was_enabled:
1019 gc.enable()
1020 raise
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001021 self._child_created = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001022 if self.pid == 0:
1023 # Child
1024 try:
1025 # Close parent's pipe ends
Thomas Wouterscf297e42007-02-23 15:07:44 +00001026 if p2cwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001027 os.close(p2cwrite)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001028 if c2pread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001029 os.close(c2pread)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001030 if errread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001031 os.close(errread)
1032 os.close(errpipe_read)
1033
1034 # Dup fds for child
Thomas Wouterscf297e42007-02-23 15:07:44 +00001035 if p2cread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001036 os.dup2(p2cread, 0)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001037 if c2pwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001038 os.dup2(c2pwrite, 1)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001039 if errwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001040 os.dup2(errwrite, 2)
1041
Thomas Wouters89f507f2006-12-13 04:49:30 +00001042 # Close pipe fds. Make sure we don't close the same
1043 # fd more than once, or standard fds.
Thomas Wouterscf297e42007-02-23 15:07:44 +00001044 if p2cread is not None and p2cread not in (0,):
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001045 os.close(p2cread)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001046 if c2pwrite is not None and c2pwrite not in (p2cread, 1):
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001047 os.close(c2pwrite)
Guido van Rossum98297ee2007-11-06 21:34:58 +00001048 if (errwrite is not None and
1049 errwrite not in (p2cread, c2pwrite, 2)):
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001050 os.close(errwrite)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001051
1052 # Close all other fds, if asked for
1053 if close_fds:
1054 self._close_fds(but=errpipe_write)
1055
Peter Astrandd38ddf42005-02-10 08:32:50 +00001056 if cwd is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001057 os.chdir(cwd)
1058
1059 if preexec_fn:
Neal Norwitzd9108552006-03-17 08:00:19 +00001060 preexec_fn()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001061
Peter Astrandd38ddf42005-02-10 08:32:50 +00001062 if env is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001063 os.execvp(executable, args)
1064 else:
1065 os.execvpe(executable, args, env)
1066
1067 except:
1068 exc_type, exc_value, tb = sys.exc_info()
1069 # Save the traceback and attach it to the exception object
Tim Peterse8374a52004-10-13 03:15:00 +00001070 exc_lines = traceback.format_exception(exc_type,
1071 exc_value,
1072 tb)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001073 exc_value.child_traceback = ''.join(exc_lines)
1074 os.write(errpipe_write, pickle.dumps(exc_value))
1075
1076 # This exitcode won't be reported to applications, so it
1077 # really doesn't matter what we return.
1078 os._exit(255)
1079
1080 # Parent
Christian Heimesfdab48e2008-01-20 09:06:41 +00001081 if gc_was_enabled:
1082 gc.enable()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001083 os.close(errpipe_write)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001084 if p2cread is not None and p2cwrite is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001085 os.close(p2cread)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001086 if c2pwrite is not None and c2pread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001087 os.close(c2pwrite)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001088 if errwrite is not None and errread is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001089 os.close(errwrite)
1090
1091 # Wait for exec to fail or succeed; possibly raising exception
1092 data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB
1093 os.close(errpipe_read)
Guido van Rossumaf2362a2007-05-15 22:32:02 +00001094 if data:
Peter Astrandf791d7a2005-01-01 09:38:57 +00001095 os.waitpid(self.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001096 child_exception = pickle.loads(data)
1097 raise child_exception
1098
1099
1100 def _handle_exitstatus(self, sts):
1101 if os.WIFSIGNALED(sts):
1102 self.returncode = -os.WTERMSIG(sts)
1103 elif os.WIFEXITED(sts):
1104 self.returncode = os.WEXITSTATUS(sts)
1105 else:
1106 # Should never happen
1107 raise RuntimeError("Unknown child exit status!")
1108
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001109
Georg Brandl6aa2d1f2008-08-12 08:35:52 +00001110 def _internal_poll(self, _deadstate=None):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001111 """Check if child process has terminated. Returns returncode
1112 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001113 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001114 try:
1115 pid, sts = os.waitpid(self.pid, os.WNOHANG)
1116 if pid == self.pid:
1117 self._handle_exitstatus(sts)
1118 except os.error:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001119 if _deadstate is not None:
1120 self.returncode = _deadstate
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001121 return self.returncode
1122
1123
1124 def wait(self):
1125 """Wait for child process to terminate. Returns returncode
1126 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001127 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001128 pid, sts = os.waitpid(self.pid, 0)
1129 self._handle_exitstatus(sts)
1130 return self.returncode
1131
1132
Peter Astrand23109f02005-03-03 20:28:59 +00001133 def _communicate(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001134 read_set = []
1135 write_set = []
1136 stdout = None # Return
1137 stderr = None # Return
1138
1139 if self.stdin:
1140 # Flush stdio buffer. This might block, if the user has
1141 # been writing to .stdin in an uncontrolled fashion.
1142 self.stdin.flush()
1143 if input:
1144 write_set.append(self.stdin)
1145 else:
1146 self.stdin.close()
1147 if self.stdout:
1148 read_set.append(self.stdout)
Tim Peterse718f612004-10-12 21:51:32 +00001149 stdout = []
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001150 if self.stderr:
1151 read_set.append(self.stderr)
1152 stderr = []
1153
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001154 input_offset = 0
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001155 while read_set or write_set:
Georg Brandl86b2fb92008-07-16 03:43:04 +00001156 try:
1157 rlist, wlist, xlist = select.select(read_set, write_set, [])
1158 except select.error as e:
1159 if e.args[0] == errno.EINTR:
1160 continue
1161 raise
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001162
Guido van Rossum98297ee2007-11-06 21:34:58 +00001163 # XXX Rewrite these to use non-blocking I/O on the
1164 # file objects; they are no longer using C stdio!
1165
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001166 if self.stdin in wlist:
1167 # When select has indicated that the file is writable,
1168 # we can write up to PIPE_BUF bytes without risk
1169 # blocking. POSIX defines PIPE_BUF >= 512
Guido van Rossumbae07c92007-10-08 02:46:15 +00001170 chunk = input[input_offset : input_offset + 512]
1171 bytes_written = os.write(self.stdin.fileno(), chunk)
Thomas Wouters9fe394c2007-02-05 01:24:16 +00001172 input_offset += bytes_written
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001173 if input_offset >= len(input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001174 self.stdin.close()
1175 write_set.remove(self.stdin)
1176
1177 if self.stdout in rlist:
1178 data = os.read(self.stdout.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001179 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001180 self.stdout.close()
1181 read_set.remove(self.stdout)
1182 stdout.append(data)
1183
1184 if self.stderr in rlist:
1185 data = os.read(self.stderr.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001186 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001187 self.stderr.close()
1188 read_set.remove(self.stderr)
1189 stderr.append(data)
1190
1191 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +00001192 if stdout is not None:
Guido van Rossum98297ee2007-11-06 21:34:58 +00001193 stdout = b"".join(stdout)
Peter Astrandd38ddf42005-02-10 08:32:50 +00001194 if stderr is not None:
Guido van Rossum98297ee2007-11-06 21:34:58 +00001195 stderr = b"".join(stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001196
Guido van Rossum98297ee2007-11-06 21:34:58 +00001197 # Translate newlines, if requested.
1198 # This also turns bytes into strings.
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001199 if self.universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +00001200 if stdout is not None:
Guido van Rossum98297ee2007-11-06 21:34:58 +00001201 stdout = self._translate_newlines(stdout,
1202 self.stdout.encoding)
Guido van Rossumfa0054a2007-05-24 04:05:35 +00001203 if stderr is not None:
Guido van Rossum98297ee2007-11-06 21:34:58 +00001204 stderr = self._translate_newlines(stderr,
1205 self.stderr.encoding)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001206
1207 self.wait()
1208 return (stdout, stderr)
1209
Christian Heimesa342c012008-04-20 21:01:16 +00001210 def send_signal(self, sig):
1211 """Send a signal to the process
1212 """
1213 os.kill(self.pid, sig)
1214
1215 def terminate(self):
1216 """Terminate the process with SIGTERM
1217 """
1218 self.send_signal(signal.SIGTERM)
1219
1220 def kill(self):
1221 """Kill the process with SIGKILL
1222 """
1223 self.send_signal(signal.SIGKILL)
1224
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001225
1226def _demo_posix():
1227 #
1228 # Example 1: Simple redirection: Get process list
1229 #
1230 plist = Popen(["ps"], stdout=PIPE).communicate()[0]
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001231 print("Process list:")
1232 print(plist)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001233
1234 #
1235 # Example 2: Change uid before executing child
1236 #
1237 if os.getuid() == 0:
1238 p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1239 p.wait()
1240
1241 #
1242 # Example 3: Connecting several subprocesses
1243 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001244 print("Looking for 'hda'...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001245 p1 = Popen(["dmesg"], stdout=PIPE)
1246 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001247 print(repr(p2.communicate()[0]))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001248
1249 #
1250 # Example 4: Catch execution error
1251 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001252 print()
1253 print("Trying a weird file...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001254 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001255 print(Popen(["/this/path/does/not/exist"]).communicate())
Guido van Rossumb940e112007-01-10 16:19:56 +00001256 except OSError as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001257 if e.errno == errno.ENOENT:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001258 print("The file didn't exist. I thought so...")
1259 print("Child traceback:")
1260 print(e.child_traceback)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001261 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001262 print("Error", e.errno)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001263 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001264 print("Gosh. No error.", file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001265
1266
1267def _demo_windows():
1268 #
1269 # Example 1: Connecting several subprocesses
1270 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001271 print("Looking for 'PROMPT' in set output...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001272 p1 = Popen("set", stdout=PIPE, shell=True)
1273 p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001274 print(repr(p2.communicate()[0]))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001275
1276 #
1277 # Example 2: Simple execution of program
1278 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001279 print("Executing calc...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001280 p = Popen("calc")
1281 p.wait()
1282
1283
1284if __name__ == "__main__":
1285 if mswindows:
1286 _demo_windows()
1287 else:
1288 _demo_posix()