blob: 299f73e711a8d3588c7df275d441f6a740202a6d [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001# subprocess - Subprocesses with accessible I/O streams
2#
Tim Peterse718f612004-10-12 21:51:32 +00003# For more information about this module, see PEP 324.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00004#
Peter Astrand3a708df2005-09-23 17:37:29 +00005# Copyright (c) 2003-2005 by Peter Astrand <astrand@lysator.liu.se>
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00006#
Peter Astrand69bf13f2005-02-14 08:56:32 +00007# Licensed to PSF under a Contributor Agreement.
Peter Astrand3a708df2005-09-23 17:37:29 +00008# See http://www.python.org/2.4/license for licensing details.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00009
Raymond Hettinger837dd932004-10-17 16:36:53 +000010r"""subprocess - Subprocesses with accessible I/O streams
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000011
Fredrik Lundh15aaacc2004-10-17 14:47:05 +000012This module allows you to spawn processes, connect to their
13input/output/error pipes, and obtain their return codes. This module
14intends to replace several other, older modules and functions, like:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000015
16os.system
17os.spawn*
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000018
19Information about how the subprocess module can be used to replace these
20modules and functions can be found below.
21
22
23
24Using the subprocess module
25===========================
26This module defines one class called Popen:
27
28class Popen(args, bufsize=0, executable=None,
29 stdin=None, stdout=None, stderr=None,
30 preexec_fn=None, close_fds=False, shell=False,
31 cwd=None, env=None, universal_newlines=False,
32 startupinfo=None, creationflags=0):
33
34
35Arguments are:
36
37args should be a string, or a sequence of program arguments. The
38program to execute is normally the first item in the args sequence or
39string, but can be explicitly set by using the executable argument.
40
41On UNIX, with shell=False (default): In this case, the Popen class
42uses os.execvp() to execute the child program. args should normally
43be a sequence. A string will be treated as a sequence with the string
44as the only item (the program to execute).
45
46On UNIX, with shell=True: If args is a string, it specifies the
47command string to execute through the shell. If args is a sequence,
48the first item specifies the command string, and any additional items
49will be treated as additional shell arguments.
50
51On Windows: the Popen class uses CreateProcess() to execute the child
52program, which operates on strings. If args is a sequence, it will be
53converted to a string using the list2cmdline method. Please note that
54not all MS Windows applications interpret the command line the same
55way: The list2cmdline is designed for applications using the same
56rules as the MS C runtime.
57
58bufsize, if given, has the same meaning as the corresponding argument
59to the built-in open() function: 0 means unbuffered, 1 means line
60buffered, any other positive value means use a buffer of
61(approximately) that size. A negative bufsize means to use the system
62default, which usually means fully buffered. The default value for
63bufsize is 0 (unbuffered).
64
65stdin, stdout and stderr specify the executed programs' standard
66input, standard output and standard error file handles, respectively.
67Valid values are PIPE, an existing file descriptor (a positive
68integer), an existing file object, and None. PIPE indicates that a
69new pipe to the child should be created. With None, no redirection
70will occur; the child's file handles will be inherited from the
71parent. Additionally, stderr can be STDOUT, which indicates that the
72stderr data from the applications should be captured into the same
73file handle as for stdout.
74
75If preexec_fn is set to a callable object, this object will be called
76in the child process just before the child is executed.
77
78If close_fds is true, all file descriptors except 0, 1 and 2 will be
79closed before the child process is executed.
80
81if shell is true, the specified command will be executed through the
82shell.
83
84If cwd is not None, the current directory will be changed to cwd
85before the child is executed.
86
87If env is not None, it defines the environment variables for the new
88process.
89
90If universal_newlines is true, the file objects stdout and stderr are
91opened as a text files, but lines may be terminated by any of '\n',
92the Unix end-of-line convention, '\r', the Macintosh convention or
93'\r\n', the Windows convention. All of these external representations
94are seen as '\n' by the Python program. Note: This feature is only
95available if Python is built with universal newline support (the
96default). Also, the newlines attribute of the file objects stdout,
97stdin and stderr are not updated by the communicate() method.
98
99The startupinfo and creationflags, if given, will be passed to the
100underlying CreateProcess() function. They can specify things such as
101appearance of the main window and priority for the new process.
102(Windows only)
103
104
Georg Brandlf9734072008-12-07 15:30:06 +0000105This module also defines some shortcut functions:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000106
Peter Astrand5f5e1412004-12-05 20:15:36 +0000107call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000108 Run command with arguments. Wait for command to complete, then
109 return the returncode attribute.
110
111 The arguments are the same as for the Popen constructor. Example:
112
Georg Brandl8ffe0bc2010-10-06 07:17:29 +0000113 >>> retcode = call(["ls", "-l"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000114
Peter Astrand454f7672005-01-01 09:36:35 +0000115check_call(*popenargs, **kwargs):
116 Run command with arguments. Wait for command to complete. If the
117 exit code was zero then return, otherwise raise
118 CalledProcessError. The CalledProcessError object will have the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000119 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000120
121 The arguments are the same as for the Popen constructor. Example:
122
Georg Brandl8ffe0bc2010-10-06 07:17:29 +0000123 >>> check_call(["ls", "-l"])
124 0
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000125
Brett Cannona23810f2008-05-26 19:04:21 +0000126getstatusoutput(cmd):
127 Return (status, output) of executing cmd in a shell.
128
129 Execute the string 'cmd' in a shell with os.popen() and return a 2-tuple
130 (status, output). cmd is actually run as '{ cmd ; } 2>&1', so that the
131 returned output will contain output or error messages. A trailing newline
132 is stripped from the output. The exit status for the command can be
133 interpreted according to the rules for the C function wait(). Example:
134
Brett Cannona23810f2008-05-26 19:04:21 +0000135 >>> subprocess.getstatusoutput('ls /bin/ls')
136 (0, '/bin/ls')
137 >>> subprocess.getstatusoutput('cat /bin/junk')
138 (256, 'cat: /bin/junk: No such file or directory')
139 >>> subprocess.getstatusoutput('/bin/junk')
140 (256, 'sh: /bin/junk: not found')
141
142getoutput(cmd):
143 Return output (stdout or stderr) of executing cmd in a shell.
144
145 Like getstatusoutput(), except the exit status is ignored and the return
146 value is a string containing the command's output. Example:
147
Brett Cannona23810f2008-05-26 19:04:21 +0000148 >>> subprocess.getoutput('ls /bin/ls')
149 '/bin/ls'
150
Georg Brandlf9734072008-12-07 15:30:06 +0000151check_output(*popenargs, **kwargs):
Georg Brandl8ffe0bc2010-10-06 07:17:29 +0000152 Run command with arguments and return its output as a byte string.
Georg Brandlf9734072008-12-07 15:30:06 +0000153
Georg Brandl8ffe0bc2010-10-06 07:17:29 +0000154 If the exit code was non-zero it raises a CalledProcessError. The
155 CalledProcessError object will have the return code in the returncode
156 attribute and output in the output attribute.
Georg Brandlf9734072008-12-07 15:30:06 +0000157
Georg Brandl8ffe0bc2010-10-06 07:17:29 +0000158 The arguments are the same as for the Popen constructor. Example:
Georg Brandlf9734072008-12-07 15:30:06 +0000159
Georg Brandl8ffe0bc2010-10-06 07:17:29 +0000160 >>> output = subprocess.check_output(["ls", "-l", "/dev/null"])
Georg Brandlf9734072008-12-07 15:30:06 +0000161
Brett Cannona23810f2008-05-26 19:04:21 +0000162
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000163Exceptions
164----------
165Exceptions raised in the child process, before the new program has
166started to execute, will be re-raised in the parent. Additionally,
167the exception object will have one extra attribute called
168'child_traceback', which is a string containing traceback information
169from the childs point of view.
170
171The most common exception raised is OSError. This occurs, for
172example, when trying to execute a non-existent file. Applications
173should prepare for OSErrors.
174
175A ValueError will be raised if Popen is called with invalid arguments.
176
Georg Brandlf9734072008-12-07 15:30:06 +0000177check_call() and check_output() will raise CalledProcessError, if the
178called process returns a non-zero return code.
Peter Astrand454f7672005-01-01 09:36:35 +0000179
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000180
181Security
182--------
183Unlike some other popen functions, this implementation will never call
184/bin/sh implicitly. This means that all characters, including shell
185metacharacters, can safely be passed to child processes.
186
187
188Popen objects
189=============
190Instances of the Popen class have the following methods:
191
192poll()
193 Check if child process has terminated. Returns returncode
194 attribute.
195
196wait()
197 Wait for child process to terminate. Returns returncode attribute.
198
199communicate(input=None)
200 Interact with process: Send data to stdin. Read data from stdout
201 and stderr, until end-of-file is reached. Wait for process to
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000202 terminate. The optional input argument should be a string to be
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000203 sent to the child process, or None, if no data should be sent to
204 the child.
Tim Peterse718f612004-10-12 21:51:32 +0000205
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000206 communicate() returns a tuple (stdout, stderr).
207
208 Note: The data read is buffered in memory, so do not use this
209 method if the data size is large or unlimited.
210
211The following attributes are also available:
212
213stdin
214 If the stdin argument is PIPE, this attribute is a file object
215 that provides input to the child process. Otherwise, it is None.
216
217stdout
218 If the stdout argument is PIPE, this attribute is a file object
219 that provides output from the child process. Otherwise, it is
220 None.
221
222stderr
223 If the stderr argument is PIPE, this attribute is file object that
224 provides error output from the child process. Otherwise, it is
225 None.
226
227pid
228 The process ID of the child process.
229
230returncode
231 The child return code. A None value indicates that the process
232 hasn't terminated yet. A negative value -N indicates that the
233 child was terminated by signal N (UNIX only).
234
235
236Replacing older functions with the subprocess module
237====================================================
238In this section, "a ==> b" means that b can be used as a replacement
239for a.
240
241Note: All functions in this section fail (more or less) silently if
242the executed program cannot be found; this module raises an OSError
243exception.
244
245In the following examples, we assume that the subprocess module is
246imported with "from subprocess import *".
247
248
249Replacing /bin/sh shell backquote
250---------------------------------
251output=`mycmd myarg`
252==>
253output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
254
255
256Replacing shell pipe line
257-------------------------
258output=`dmesg | grep hda`
259==>
260p1 = Popen(["dmesg"], stdout=PIPE)
Peter Astrand6fdf3cb2004-11-30 18:06:42 +0000261p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000262output = p2.communicate()[0]
263
264
265Replacing os.system()
266---------------------
267sts = os.system("mycmd" + " myarg")
268==>
269p = Popen("mycmd" + " myarg", shell=True)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000270pid, sts = os.waitpid(p.pid, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000271
272Note:
273
274* Calling the program through the shell is usually not required.
275
276* It's easier to look at the returncode attribute than the
277 exitstatus.
278
279A more real-world example would look like this:
280
281try:
282 retcode = call("mycmd" + " myarg", shell=True)
283 if retcode < 0:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000284 print("Child was terminated by signal", -retcode, file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000285 else:
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000286 print("Child returned", retcode, file=sys.stderr)
287except OSError as e:
288 print("Execution failed:", e, file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000289
290
291Replacing os.spawn*
292-------------------
Tim Peterse718f612004-10-12 21:51:32 +0000293P_NOWAIT example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000294
295pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
296==>
297pid = Popen(["/bin/mycmd", "myarg"]).pid
298
299
300P_WAIT example:
301
302retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
303==>
304retcode = call(["/bin/mycmd", "myarg"])
305
306
Tim Peterse718f612004-10-12 21:51:32 +0000307Vector example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000308
309os.spawnvp(os.P_NOWAIT, path, args)
310==>
311Popen([path] + args[1:])
312
313
Tim Peterse718f612004-10-12 21:51:32 +0000314Environment example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000315
316os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
317==>
318Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000319"""
320
321import sys
322mswindows = (sys.platform == "win32")
323
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000324import io
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000325import os
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000326import traceback
Christian Heimesfdab48e2008-01-20 09:06:41 +0000327import gc
Christian Heimesa342c012008-04-20 21:01:16 +0000328import signal
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200329import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000330
Peter Astrand454f7672005-01-01 09:36:35 +0000331# Exception classes used by this module.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000332class CalledProcessError(Exception):
Georg Brandlf9734072008-12-07 15:30:06 +0000333 """This exception is raised when a process run by check_call() or
334 check_output() returns a non-zero exit status.
335 The exit status will be stored in the returncode attribute;
336 check_output() will also store the output in the output attribute.
337 """
338 def __init__(self, returncode, cmd, output=None):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000339 self.returncode = returncode
340 self.cmd = cmd
Georg Brandlf9734072008-12-07 15:30:06 +0000341 self.output = output
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000342 def __str__(self):
343 return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
344
Peter Astrand454f7672005-01-01 09:36:35 +0000345
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000346if mswindows:
347 import threading
348 import msvcrt
Brian Curtine1491662010-04-24 16:33:18 +0000349 import _subprocess
350 class STARTUPINFO:
351 dwFlags = 0
352 hStdInput = None
353 hStdOutput = None
354 hStdError = None
355 wShowWindow = 0
356 class pywintypes:
357 error = IOError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000358else:
359 import select
Georg Brandlae83d6e2009-08-13 09:04:31 +0000360 _has_poll = hasattr(select, 'poll')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000361 import fcntl
362 import pickle
363
Gregory P. Smith10d29522009-08-13 18:33:30 +0000364 # When select or poll has indicated that the file is writable,
365 # we can write up to _PIPE_BUF bytes without risk of blocking.
366 # POSIX defines PIPE_BUF as >= 512.
367 _PIPE_BUF = getattr(select, 'PIPE_BUF', 512)
368
369
Brett Cannona23810f2008-05-26 19:04:21 +0000370__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "getstatusoutput",
Georg Brandlf9734072008-12-07 15:30:06 +0000371 "getoutput", "check_output", "CalledProcessError"]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000372
Brian Curtine1491662010-04-24 16:33:18 +0000373if mswindows:
Brian Curtin8b8e7f42011-04-29 15:48:13 -0500374 from _subprocess import (CREATE_NEW_CONSOLE,
375 STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
376 STD_ERROR_HANDLE, SW_HIDE,
377 STARTF_USESTDHANDLES, STARTF_USESHOWWINDOW)
378
379 __all__.extend(["CREATE_NEW_CONSOLE",
380 "STD_INPUT_HANDLE", "STD_OUTPUT_HANDLE",
381 "STD_ERROR_HANDLE", "SW_HIDE",
382 "STARTF_USESTDHANDLES", "STARTF_USESHOWWINDOW"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000383try:
384 MAXFD = os.sysconf("SC_OPEN_MAX")
385except:
386 MAXFD = 256
387
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000388_active = []
389
390def _cleanup():
391 for inst in _active[:]:
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000392 res = inst._internal_poll(_deadstate=sys.maxsize)
Guido van Rossumb5d47ef2006-08-24 02:27:45 +0000393 if res is not None and res >= 0:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000394 try:
395 _active.remove(inst)
396 except ValueError:
397 # This can happen if two threads create a new Popen instance.
398 # It's harmless that it was already removed, so ignore.
399 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000400
401PIPE = -1
402STDOUT = -2
403
404
Gregory P. Smith3fff44d2010-03-01 00:43:08 +0000405def _eintr_retry_call(func, *args):
406 while True:
407 try:
408 return func(*args)
409 except OSError as e:
410 if e.errno == errno.EINTR:
411 continue
412 raise
413
414
Peter Astrand5f5e1412004-12-05 20:15:36 +0000415def call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000416 """Run command with arguments. Wait for command to complete, then
417 return the returncode attribute.
418
419 The arguments are the same as for the Popen constructor. Example:
420
421 retcode = call(["ls", "-l"])
422 """
Peter Astrand5f5e1412004-12-05 20:15:36 +0000423 return Popen(*popenargs, **kwargs).wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000424
425
Peter Astrand454f7672005-01-01 09:36:35 +0000426def check_call(*popenargs, **kwargs):
427 """Run command with arguments. Wait for command to complete. If
428 the exit code was zero then return, otherwise raise
429 CalledProcessError. The CalledProcessError object will have the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000430 return code in the returncode attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000431
432 The arguments are the same as for the Popen constructor. Example:
433
434 check_call(["ls", "-l"])
435 """
436 retcode = call(*popenargs, **kwargs)
Peter Astrand454f7672005-01-01 09:36:35 +0000437 if retcode:
Georg Brandlf9734072008-12-07 15:30:06 +0000438 cmd = kwargs.get("args")
439 if cmd is None:
440 cmd = popenargs[0]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000441 raise CalledProcessError(retcode, cmd)
Georg Brandlf9734072008-12-07 15:30:06 +0000442 return 0
443
444
445def check_output(*popenargs, **kwargs):
Georg Brandl8ffe0bc2010-10-06 07:17:29 +0000446 r"""Run command with arguments and return its output as a byte string.
Georg Brandlf9734072008-12-07 15:30:06 +0000447
448 If the exit code was non-zero it raises a CalledProcessError. The
449 CalledProcessError object will have the return code in the returncode
450 attribute and output in the output attribute.
451
452 The arguments are the same as for the Popen constructor. Example:
453
454 >>> check_output(["ls", "-l", "/dev/null"])
Georg Brandl8ffe0bc2010-10-06 07:17:29 +0000455 b'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000456
457 The stdout argument is not allowed as it is used internally.
Georg Brandl8ffe0bc2010-10-06 07:17:29 +0000458 To capture standard error in the result, use stderr=STDOUT.
Georg Brandlf9734072008-12-07 15:30:06 +0000459
460 >>> check_output(["/bin/sh", "-c",
Georg Brandl8ffe0bc2010-10-06 07:17:29 +0000461 ... "ls -l non_existent_file ; exit 0"],
462 ... stderr=STDOUT)
463 b'ls: non_existent_file: No such file or directory\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000464 """
465 if 'stdout' in kwargs:
466 raise ValueError('stdout argument not allowed, it will be overridden.')
467 process = Popen(*popenargs, stdout=PIPE, **kwargs)
468 output, unused_err = process.communicate()
469 retcode = process.poll()
470 if retcode:
471 cmd = kwargs.get("args")
472 if cmd is None:
473 cmd = popenargs[0]
474 raise CalledProcessError(retcode, cmd, output=output)
475 return output
Peter Astrand454f7672005-01-01 09:36:35 +0000476
477
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000478def list2cmdline(seq):
479 """
480 Translate a sequence of arguments into a command line
481 string, using the same rules as the MS C runtime:
482
483 1) Arguments are delimited by white space, which is either a
484 space or a tab.
485
486 2) A string surrounded by double quotation marks is
487 interpreted as a single argument, regardless of white space
Jean-Paul Calderone2323d202010-06-18 20:11:43 +0000488 contained within. A quoted string can be embedded in an
489 argument.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000490
491 3) A double quotation mark preceded by a backslash is
492 interpreted as a literal double quotation mark.
493
494 4) Backslashes are interpreted literally, unless they
495 immediately precede a double quotation mark.
496
497 5) If backslashes immediately precede a double quotation mark,
498 every pair of backslashes is interpreted as a literal
499 backslash. If the number of backslashes is odd, the last
500 backslash escapes the next double quotation mark as
501 described in rule 3.
502 """
503
504 # See
Eric Smith536d2992009-11-09 15:24:55 +0000505 # http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
506 # or search http://msdn.microsoft.com for
507 # "Parsing C++ Command-Line Arguments"
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000508 result = []
509 needquote = False
510 for arg in seq:
511 bs_buf = []
512
513 # Add a space to separate this argument from the others
514 if result:
515 result.append(' ')
516
Jean-Paul Calderone2323d202010-06-18 20:11:43 +0000517 needquote = (" " in arg) or ("\t" in arg) or not arg
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000518 if needquote:
519 result.append('"')
520
521 for c in arg:
522 if c == '\\':
Tim Peterse718f612004-10-12 21:51:32 +0000523 # Don't know if we need to double yet.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000524 bs_buf.append(c)
525 elif c == '"':
Christian Heimesfdab48e2008-01-20 09:06:41 +0000526 # Double backslashes.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000527 result.append('\\' * len(bs_buf)*2)
528 bs_buf = []
529 result.append('\\"')
530 else:
531 # Normal char
532 if bs_buf:
533 result.extend(bs_buf)
534 bs_buf = []
535 result.append(c)
536
Christian Heimesfdab48e2008-01-20 09:06:41 +0000537 # Add remaining backslashes, if any.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000538 if bs_buf:
539 result.extend(bs_buf)
540
541 if needquote:
Peter Astrand7e78ade2005-03-03 21:10:23 +0000542 result.extend(bs_buf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000543 result.append('"')
544
545 return ''.join(result)
546
547
Brett Cannona23810f2008-05-26 19:04:21 +0000548# Various tools for executing commands and looking at their output and status.
549#
550# NB This only works (and is only relevant) for UNIX.
551
552def getstatusoutput(cmd):
553 """Return (status, output) of executing cmd in a shell.
554
555 Execute the string 'cmd' in a shell with os.popen() and return a 2-tuple
556 (status, output). cmd is actually run as '{ cmd ; } 2>&1', so that the
557 returned output will contain output or error messages. A trailing newline
558 is stripped from the output. The exit status for the command can be
559 interpreted according to the rules for the C function wait(). Example:
560
561 >>> import subprocess
562 >>> subprocess.getstatusoutput('ls /bin/ls')
563 (0, '/bin/ls')
564 >>> subprocess.getstatusoutput('cat /bin/junk')
565 (256, 'cat: /bin/junk: No such file or directory')
566 >>> subprocess.getstatusoutput('/bin/junk')
567 (256, 'sh: /bin/junk: not found')
568 """
569 pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
570 text = pipe.read()
571 sts = pipe.close()
572 if sts is None: sts = 0
573 if text[-1:] == '\n': text = text[:-1]
574 return sts, text
575
576
577def getoutput(cmd):
578 """Return output (stdout or stderr) of executing cmd in a shell.
579
580 Like getstatusoutput(), except the exit status is ignored and the return
581 value is a string containing the command's output. Example:
582
583 >>> import subprocess
584 >>> subprocess.getoutput('ls /bin/ls')
585 '/bin/ls'
586 """
587 return getstatusoutput(cmd)[1]
588
589
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000590class Popen(object):
591 def __init__(self, args, bufsize=0, executable=None,
592 stdin=None, stdout=None, stderr=None,
593 preexec_fn=None, close_fds=False, shell=False,
594 cwd=None, env=None, universal_newlines=False,
595 startupinfo=None, creationflags=0):
596 """Create new Popen instance."""
597 _cleanup()
598
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000599 self._child_created = False
Guido van Rossum46a05a72007-06-07 21:56:45 +0000600 if bufsize is None:
601 bufsize = 0 # Restore default
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000602 if not isinstance(bufsize, int):
Peter Astrand738131d2004-11-30 21:04:45 +0000603 raise TypeError("bufsize must be an integer")
604
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000605 if mswindows:
Tim Peterse8374a52004-10-13 03:15:00 +0000606 if preexec_fn is not None:
607 raise ValueError("preexec_fn is not supported on Windows "
608 "platforms")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000609 if close_fds and (stdin is not None or stdout is not None or
610 stderr is not None):
Tim Peterse8374a52004-10-13 03:15:00 +0000611 raise ValueError("close_fds is not supported on Windows "
Guido van Rossume7ba4952007-06-06 23:52:48 +0000612 "platforms if you redirect stdin/stdout/stderr")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000613 else:
614 # POSIX
Tim Peterse8374a52004-10-13 03:15:00 +0000615 if startupinfo is not None:
616 raise ValueError("startupinfo is only supported on Windows "
617 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000618 if creationflags != 0:
Tim Peterse8374a52004-10-13 03:15:00 +0000619 raise ValueError("creationflags is only supported on Windows "
620 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000621
Tim Peterse718f612004-10-12 21:51:32 +0000622 self.stdin = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000623 self.stdout = None
624 self.stderr = None
625 self.pid = None
626 self.returncode = None
627 self.universal_newlines = universal_newlines
628
629 # Input and output objects. The general principle is like
630 # this:
631 #
632 # Parent Child
633 # ------ -----
634 # p2cwrite ---stdin---> p2cread
635 # c2pread <--stdout--- c2pwrite
636 # errread <--stderr--- errwrite
637 #
638 # On POSIX, the child objects are file descriptors. On
639 # Windows, these are Windows file handles. The parent objects
640 # are file descriptors on both platforms. The parent objects
641 # are None when not using PIPEs. The child objects are None
642 # when not redirecting.
Tim Peterse718f612004-10-12 21:51:32 +0000643
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000644 (p2cread, p2cwrite,
645 c2pread, c2pwrite,
646 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
647
648 self._execute_child(args, executable, preexec_fn, close_fds,
649 cwd, env, universal_newlines,
650 startupinfo, creationflags, shell,
651 p2cread, p2cwrite,
652 c2pread, c2pwrite,
653 errread, errwrite)
654
Thomas Wouterscf297e42007-02-23 15:07:44 +0000655 if mswindows:
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000656 if p2cwrite is not None:
657 p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
658 if c2pread is not None:
659 c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
660 if errread is not None:
661 errread = msvcrt.open_osfhandle(errread.Detach(), 0)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000662
663 if p2cwrite is not None:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000664 self.stdin = io.open(p2cwrite, 'wb', bufsize)
665 if self.universal_newlines:
666 self.stdin = io.TextIOWrapper(self.stdin)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000667 if c2pread is not None:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000668 self.stdout = io.open(c2pread, 'rb', bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000669 if universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000670 self.stdout = io.TextIOWrapper(self.stdout)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000671 if errread is not None:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000672 self.stderr = io.open(errread, 'rb', bufsize)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000673 if universal_newlines:
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000674 self.stderr = io.TextIOWrapper(self.stderr)
Tim Peterse718f612004-10-12 21:51:32 +0000675
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000676
Guido van Rossum98297ee2007-11-06 21:34:58 +0000677 def _translate_newlines(self, data, encoding):
678 data = data.replace(b"\r\n", b"\n").replace(b"\r", b"\n")
679 return data.decode(encoding)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000680
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000681
Brett Cannon19640502010-05-14 01:28:56 +0000682 def __del__(self, _maxsize=sys.maxsize, _active=_active):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000683 if not self._child_created:
684 # We didn't get to successfully create a child process.
685 return
686 # In case the child hasn't been waited on, check if it's done.
Brett Cannon19640502010-05-14 01:28:56 +0000687 self._internal_poll(_deadstate=_maxsize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000688 if self.returncode is None and _active is not None:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000689 # Child is still running, keep us alive until we can wait on it.
690 _active.append(self)
691
692
Peter Astrand23109f02005-03-03 20:28:59 +0000693 def communicate(self, input=None):
694 """Interact with process: Send data to stdin. Read data from
695 stdout and stderr, until end-of-file is reached. Wait for
696 process to terminate. The optional input argument should be a
697 string to be sent to the child process, or None, if no data
698 should be sent to the child.
Tim Peterseba28be2005-03-28 01:08:02 +0000699
Peter Astrand23109f02005-03-03 20:28:59 +0000700 communicate() returns a tuple (stdout, stderr)."""
701
702 # Optimization: If we are only using one pipe, or no pipe at
703 # all, using select() or threads is unnecessary.
704 if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
Tim Peterseba28be2005-03-28 01:08:02 +0000705 stdout = None
706 stderr = None
Peter Astrand23109f02005-03-03 20:28:59 +0000707 if self.stdin:
708 if input:
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200709 try:
710 self.stdin.write(input)
711 except IOError as e:
712 if e.errno != errno.EPIPE and e.errno != errno.EINVAL:
713 raise
Peter Astrand23109f02005-03-03 20:28:59 +0000714 self.stdin.close()
715 elif self.stdout:
716 stdout = self.stdout.read()
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000717 self.stdout.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000718 elif self.stderr:
719 stderr = self.stderr.read()
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000720 self.stderr.close()
Peter Astrand23109f02005-03-03 20:28:59 +0000721 self.wait()
722 return (stdout, stderr)
Tim Peterseba28be2005-03-28 01:08:02 +0000723
Peter Astrand23109f02005-03-03 20:28:59 +0000724 return self._communicate(input)
725
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000726
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000727 def poll(self):
728 return self._internal_poll()
729
730
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000731 if mswindows:
732 #
733 # Windows methods
734 #
735 def _get_handles(self, stdin, stdout, stderr):
Georg Brandla85ee5c2009-08-13 12:13:42 +0000736 """Construct and return tuple with IO objects:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000737 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
738 """
Peter Astrandd38ddf42005-02-10 08:32:50 +0000739 if stdin is None and stdout is None and stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000740 return (None, None, None, None, None, None)
Tim Peterse718f612004-10-12 21:51:32 +0000741
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000742 p2cread, p2cwrite = None, None
743 c2pread, c2pwrite = None, None
744 errread, errwrite = None, None
745
Peter Astrandd38ddf42005-02-10 08:32:50 +0000746 if stdin is None:
Brian Curtine1491662010-04-24 16:33:18 +0000747 p2cread = _subprocess.GetStdHandle(_subprocess.STD_INPUT_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000748 if p2cread is None:
Brian Curtine1491662010-04-24 16:33:18 +0000749 p2cread, _ = _subprocess.CreatePipe(None, 0)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000750 elif stdin == PIPE:
Brian Curtine1491662010-04-24 16:33:18 +0000751 p2cread, p2cwrite = _subprocess.CreatePipe(None, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000752 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000753 p2cread = msvcrt.get_osfhandle(stdin)
754 else:
755 # Assuming file-like object
756 p2cread = msvcrt.get_osfhandle(stdin.fileno())
757 p2cread = self._make_inheritable(p2cread)
758
Peter Astrandd38ddf42005-02-10 08:32:50 +0000759 if stdout is None:
Brian Curtine1491662010-04-24 16:33:18 +0000760 c2pwrite = _subprocess.GetStdHandle(_subprocess.STD_OUTPUT_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000761 if c2pwrite is None:
Brian Curtine1491662010-04-24 16:33:18 +0000762 _, c2pwrite = _subprocess.CreatePipe(None, 0)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000763 elif stdout == PIPE:
Brian Curtine1491662010-04-24 16:33:18 +0000764 c2pread, c2pwrite = _subprocess.CreatePipe(None, 0)
Peter Astrandd38ddf42005-02-10 08:32:50 +0000765 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000766 c2pwrite = msvcrt.get_osfhandle(stdout)
767 else:
768 # Assuming file-like object
769 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
770 c2pwrite = self._make_inheritable(c2pwrite)
771
Peter Astrandd38ddf42005-02-10 08:32:50 +0000772 if stderr is None:
Brian Curtine1491662010-04-24 16:33:18 +0000773 errwrite = _subprocess.GetStdHandle(_subprocess.STD_ERROR_HANDLE)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000774 if errwrite is None:
Brian Curtine1491662010-04-24 16:33:18 +0000775 _, errwrite = _subprocess.CreatePipe(None, 0)
Hirokazu Yamamoto0c988172009-03-03 22:41:26 +0000776 elif stderr == PIPE:
Brian Curtine1491662010-04-24 16:33:18 +0000777 errread, errwrite = _subprocess.CreatePipe(None, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000778 elif stderr == STDOUT:
779 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +0000780 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000781 errwrite = msvcrt.get_osfhandle(stderr)
782 else:
783 # Assuming file-like object
784 errwrite = msvcrt.get_osfhandle(stderr.fileno())
785 errwrite = self._make_inheritable(errwrite)
786
787 return (p2cread, p2cwrite,
788 c2pread, c2pwrite,
789 errread, errwrite)
790
791
792 def _make_inheritable(self, handle):
793 """Return a duplicate of handle, which is inheritable"""
Brian Curtine1491662010-04-24 16:33:18 +0000794 return _subprocess.DuplicateHandle(_subprocess.GetCurrentProcess(),
795 handle, _subprocess.GetCurrentProcess(), 0, 1,
796 _subprocess.DUPLICATE_SAME_ACCESS)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000797
798
799 def _find_w9xpopen(self):
800 """Find and return absolut path to w9xpopen.exe"""
Brian Curtine1491662010-04-24 16:33:18 +0000801 w9xpopen = os.path.join(
802 os.path.dirname(_subprocess.GetModuleFileName(0)),
Tim Peterse8374a52004-10-13 03:15:00 +0000803 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000804 if not os.path.exists(w9xpopen):
805 # Eeek - file-not-found - possibly an embedding
806 # situation - see if we can locate it in sys.exec_prefix
Tim Peterse8374a52004-10-13 03:15:00 +0000807 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
808 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000809 if not os.path.exists(w9xpopen):
Tim Peterse8374a52004-10-13 03:15:00 +0000810 raise RuntimeError("Cannot locate w9xpopen.exe, which is "
811 "needed for Popen to work with your "
812 "shell or platform.")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000813 return w9xpopen
814
Tim Peterse718f612004-10-12 21:51:32 +0000815
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000816 def _execute_child(self, args, executable, preexec_fn, close_fds,
817 cwd, env, universal_newlines,
818 startupinfo, creationflags, shell,
819 p2cread, p2cwrite,
820 c2pread, c2pwrite,
821 errread, errwrite):
822 """Execute program (MS Windows version)"""
823
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000824 if not isinstance(args, str):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000825 args = list2cmdline(args)
826
Peter Astrandc1d65362004-11-07 14:30:34 +0000827 # Process startup details
Peter Astrandd38ddf42005-02-10 08:32:50 +0000828 if startupinfo is None:
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000829 startupinfo = STARTUPINFO()
830 if None not in (p2cread, c2pwrite, errwrite):
Brian Curtine1491662010-04-24 16:33:18 +0000831 startupinfo.dwFlags |= _subprocess.STARTF_USESTDHANDLES
Peter Astrandc1d65362004-11-07 14:30:34 +0000832 startupinfo.hStdInput = p2cread
833 startupinfo.hStdOutput = c2pwrite
834 startupinfo.hStdError = errwrite
835
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000836 if shell:
Brian Curtine1491662010-04-24 16:33:18 +0000837 startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW
838 startupinfo.wShowWindow = _subprocess.SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000839 comspec = os.environ.get("COMSPEC", "cmd.exe")
Tim Golden595c8d32010-08-12 09:45:25 +0000840 args = '{} /c "{}"'.format (comspec, args)
Brian Curtine1491662010-04-24 16:33:18 +0000841 if (_subprocess.GetVersion() >= 0x80000000 or
Tim Peterse8374a52004-10-13 03:15:00 +0000842 os.path.basename(comspec).lower() == "command.com"):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000843 # Win9x, or using command.com on NT. We need to
844 # use the w9xpopen intermediate program. For more
845 # information, see KB Q150956
846 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
847 w9xpopen = self._find_w9xpopen()
848 args = '"%s" %s' % (w9xpopen, args)
849 # Not passing CREATE_NEW_CONSOLE has been known to
850 # cause random failures on win9x. Specifically a
851 # dialog: "Your program accessed mem currently in
852 # use at xxx" and a hopeful warning about the
Mark Dickinson934896d2009-02-21 20:59:32 +0000853 # stability of your system. Cost is Ctrl+C won't
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000854 # kill children.
Brian Curtine1491662010-04-24 16:33:18 +0000855 creationflags |= _subprocess.CREATE_NEW_CONSOLE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000856
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000857 # Start the process
858 try:
Brian Curtine1491662010-04-24 16:33:18 +0000859 hp, ht, pid, tid = _subprocess.CreateProcess(executable, args,
Tim Peterse8374a52004-10-13 03:15:00 +0000860 # no special security
861 None, None,
Guido van Rossume7ba4952007-06-06 23:52:48 +0000862 int(not close_fds),
Tim Peterse8374a52004-10-13 03:15:00 +0000863 creationflags,
864 env,
865 cwd,
866 startupinfo)
Guido van Rossumb940e112007-01-10 16:19:56 +0000867 except pywintypes.error as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000868 # Translate pywintypes.error to WindowsError, which is
869 # a subclass of OSError. FIXME: We should really
Ezio Melotti13925002011-03-16 11:05:33 +0200870 # translate errno using _sys_errlist (or similar), but
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000871 # how can this be done from Python?
872 raise WindowsError(*e.args)
Tim Golden10215de2010-08-08 11:18:34 +0000873 finally:
874 # Child is launched. Close the parent's copy of those pipe
875 # handles that only the child should have open. You need
876 # to make sure that no handles to the write end of the
877 # output pipe are maintained in this process or else the
878 # pipe will not close when the child process exits and the
879 # ReadFile will hang.
880 if p2cread is not None:
881 p2cread.Close()
882 if c2pwrite is not None:
883 c2pwrite.Close()
884 if errwrite is not None:
885 errwrite.Close()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000886
887 # Retain the process handle, but close the thread handle
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000888 self._child_created = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000889 self._handle = hp
890 self.pid = pid
891 ht.Close()
892
Brett Cannon19640502010-05-14 01:28:56 +0000893 def _internal_poll(self, _deadstate=None,
Victor Stinner20f97be2010-05-14 21:57:25 +0000894 _WaitForSingleObject=_subprocess.WaitForSingleObject,
895 _WAIT_OBJECT_0=_subprocess.WAIT_OBJECT_0,
896 _GetExitCodeProcess=_subprocess.GetExitCodeProcess):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000897 """Check if child process has terminated. Returns returncode
Brett Cannon19640502010-05-14 01:28:56 +0000898 attribute.
899
900 This method is called by __del__, so it can only refer to objects
901 in its local scope.
902
903 """
Peter Astrandd38ddf42005-02-10 08:32:50 +0000904 if self.returncode is None:
Brett Cannon19640502010-05-14 01:28:56 +0000905 if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
906 self.returncode = _GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000907 return self.returncode
908
909
910 def wait(self):
911 """Wait for child process to terminate. Returns returncode
912 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +0000913 if self.returncode is None:
Brian Curtine1491662010-04-24 16:33:18 +0000914 _subprocess.WaitForSingleObject(self._handle,
915 _subprocess.INFINITE)
916 self.returncode = _subprocess.GetExitCodeProcess(self._handle)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000917 return self.returncode
918
919
920 def _readerthread(self, fh, buffer):
921 buffer.append(fh.read())
922
923
Peter Astrand23109f02005-03-03 20:28:59 +0000924 def _communicate(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000925 stdout = None # Return
926 stderr = None # Return
927
928 if self.stdout:
929 stdout = []
Tim Peterse8374a52004-10-13 03:15:00 +0000930 stdout_thread = threading.Thread(target=self._readerthread,
931 args=(self.stdout, stdout))
Benjamin Peterson632e0362008-08-18 19:08:51 +0000932 stdout_thread.daemon = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000933 stdout_thread.start()
934 if self.stderr:
935 stderr = []
Tim Peterse8374a52004-10-13 03:15:00 +0000936 stderr_thread = threading.Thread(target=self._readerthread,
937 args=(self.stderr, stderr))
Benjamin Peterson632e0362008-08-18 19:08:51 +0000938 stderr_thread.daemon = True
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000939 stderr_thread.start()
940
941 if self.stdin:
Peter Astrandd38ddf42005-02-10 08:32:50 +0000942 if input is not None:
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200943 try:
944 self.stdin.write(input)
945 except IOError as e:
946 if e.errno != errno.EPIPE:
947 raise
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000948 self.stdin.close()
949
950 if self.stdout:
951 stdout_thread.join()
952 if self.stderr:
953 stderr_thread.join()
954
955 # All data exchanged. Translate lists into strings.
Peter Astrandd38ddf42005-02-10 08:32:50 +0000956 if stdout is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000957 stdout = stdout[0]
Peter Astrandd38ddf42005-02-10 08:32:50 +0000958 if stderr is not None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000959 stderr = stderr[0]
960
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000961 self.wait()
962 return (stdout, stderr)
963
Christian Heimesa342c012008-04-20 21:01:16 +0000964 def send_signal(self, sig):
965 """Send a signal to the process
966 """
967 if sig == signal.SIGTERM:
968 self.terminate()
969 else:
970 raise ValueError("Only SIGTERM is supported on Windows")
971
972 def terminate(self):
973 """Terminates the process
974 """
Brian Curtine1491662010-04-24 16:33:18 +0000975 _subprocess.TerminateProcess(self._handle, 1)
Christian Heimesa342c012008-04-20 21:01:16 +0000976
977 kill = terminate
978
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000979 else:
980 #
981 # POSIX methods
982 #
983 def _get_handles(self, stdin, stdout, stderr):
Georg Brandla85ee5c2009-08-13 12:13:42 +0000984 """Construct and return tuple with IO objects:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000985 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
986 """
987 p2cread, p2cwrite = None, None
988 c2pread, c2pwrite = None, None
989 errread, errwrite = None, None
990
Peter Astrandd38ddf42005-02-10 08:32:50 +0000991 if stdin is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000992 pass
993 elif stdin == PIPE:
994 p2cread, p2cwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +0000995 elif isinstance(stdin, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000996 p2cread = stdin
997 else:
998 # Assuming file-like object
999 p2cread = stdin.fileno()
1000
Peter Astrandd38ddf42005-02-10 08:32:50 +00001001 if stdout is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001002 pass
1003 elif stdout == PIPE:
1004 c2pread, c2pwrite = os.pipe()
Peter Astrandd38ddf42005-02-10 08:32:50 +00001005 elif isinstance(stdout, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001006 c2pwrite = stdout
1007 else:
1008 # Assuming file-like object
Tim Peterse718f612004-10-12 21:51:32 +00001009 c2pwrite = stdout.fileno()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001010
Peter Astrandd38ddf42005-02-10 08:32:50 +00001011 if stderr is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001012 pass
1013 elif stderr == PIPE:
1014 errread, errwrite = os.pipe()
1015 elif stderr == STDOUT:
1016 errwrite = c2pwrite
Peter Astrandd38ddf42005-02-10 08:32:50 +00001017 elif isinstance(stderr, int):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001018 errwrite = stderr
1019 else:
1020 # Assuming file-like object
1021 errwrite = stderr.fileno()
1022
1023 return (p2cread, p2cwrite,
1024 c2pread, c2pwrite,
1025 errread, errwrite)
1026
1027
Antoine Pitrouf50a6b62011-01-03 18:36:36 +00001028 def _set_cloexec_flag(self, fd, cloexec=True):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001029 try:
1030 cloexec_flag = fcntl.FD_CLOEXEC
1031 except AttributeError:
1032 cloexec_flag = 1
1033
1034 old = fcntl.fcntl(fd, fcntl.F_GETFD)
Antoine Pitrouf50a6b62011-01-03 18:36:36 +00001035 if cloexec:
1036 fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
1037 else:
1038 fcntl.fcntl(fd, fcntl.F_SETFD, old & ~cloexec_flag)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001039
1040
1041 def _close_fds(self, but):
Christian Heimesfdab48e2008-01-20 09:06:41 +00001042 os.closerange(3, but)
1043 os.closerange(but + 1, MAXFD)
Tim Peterse718f612004-10-12 21:51:32 +00001044
1045
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001046 def _execute_child(self, args, executable, preexec_fn, close_fds,
1047 cwd, env, universal_newlines,
1048 startupinfo, creationflags, shell,
1049 p2cread, p2cwrite,
1050 c2pread, c2pwrite,
1051 errread, errwrite):
1052 """Execute program (POSIX version)"""
1053
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001054 if isinstance(args, str):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001055 args = [args]
Thomas Wouters89f507f2006-12-13 04:49:30 +00001056 else:
1057 args = list(args)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001058
1059 if shell:
1060 args = ["/bin/sh", "-c"] + args
Stefan Krah8db99c82010-07-19 14:39:36 +00001061 if executable:
1062 args[0] = executable
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001063
Peter Astrandd38ddf42005-02-10 08:32:50 +00001064 if executable is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001065 executable = args[0]
1066
1067 # For transferring possible exec failure from child to parent
1068 # The first char specifies the exception type: 0 means
1069 # OSError, 1 means some other error.
1070 errpipe_read, errpipe_write = os.pipe()
Christian Heimesfdab48e2008-01-20 09:06:41 +00001071 try:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001072 try:
Facundo Batista10706e22009-06-19 20:34:30 +00001073 self._set_cloexec_flag(errpipe_write)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001074
Facundo Batista10706e22009-06-19 20:34:30 +00001075 gc_was_enabled = gc.isenabled()
1076 # Disable gc to avoid bug where gc -> file_dealloc ->
1077 # write to stderr -> hang. http://bugs.python.org/issue1336
1078 gc.disable()
1079 try:
1080 self.pid = os.fork()
1081 except:
1082 if gc_was_enabled:
1083 gc.enable()
1084 raise
1085 self._child_created = True
1086 if self.pid == 0:
1087 # Child
1088 try:
1089 # Close parent's pipe ends
1090 if p2cwrite is not None:
1091 os.close(p2cwrite)
1092 if c2pread is not None:
1093 os.close(c2pread)
1094 if errread is not None:
1095 os.close(errread)
1096 os.close(errpipe_read)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001097
Facundo Batista10706e22009-06-19 20:34:30 +00001098 # Dup fds for child
Antoine Pitrouf50a6b62011-01-03 18:36:36 +00001099 def _dup2(a, b):
1100 # dup2() removes the CLOEXEC flag but
1101 # we must do it ourselves if dup2()
1102 # would be a no-op (issue #10806).
1103 if a == b:
1104 self._set_cloexec_flag(a, False)
1105 elif a is not None:
1106 os.dup2(a, b)
1107 _dup2(p2cread, 0)
1108 _dup2(c2pwrite, 1)
1109 _dup2(errwrite, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001110
Facundo Batista10706e22009-06-19 20:34:30 +00001111 # Close pipe fds. Make sure we don't close the
1112 # same fd more than once, or standard fds.
Antoine Pitrouf50a6b62011-01-03 18:36:36 +00001113 closed = { None }
1114 for fd in [p2cread, c2pwrite, errwrite]:
1115 if fd not in closed and fd > 2:
1116 os.close(fd)
1117 closed.add(fd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001118
Facundo Batista10706e22009-06-19 20:34:30 +00001119 # Close all other fds, if asked for
1120 if close_fds:
1121 self._close_fds(but=errpipe_write)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001122
Facundo Batista10706e22009-06-19 20:34:30 +00001123 if cwd is not None:
1124 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001125
Facundo Batista10706e22009-06-19 20:34:30 +00001126 if preexec_fn:
1127 preexec_fn()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001128
Facundo Batista10706e22009-06-19 20:34:30 +00001129 if env is None:
1130 os.execvp(executable, args)
1131 else:
1132 os.execvpe(executable, args, env)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001133
Facundo Batista10706e22009-06-19 20:34:30 +00001134 except:
1135 exc_type, exc_value, tb = sys.exc_info()
1136 # Save the traceback and attach it to the exception
1137 # object
1138 exc_lines = traceback.format_exception(exc_type,
1139 exc_value,
1140 tb)
1141 exc_value.child_traceback = ''.join(exc_lines)
1142 os.write(errpipe_write, pickle.dumps(exc_value))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001143
Facundo Batista10706e22009-06-19 20:34:30 +00001144 # This exitcode won't be reported to applications, so
1145 # it really doesn't matter what we return.
1146 os._exit(255)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001147
Facundo Batista10706e22009-06-19 20:34:30 +00001148 # Parent
1149 if gc_was_enabled:
1150 gc.enable()
1151 finally:
1152 # be sure the FD is closed no matter what
1153 os.close(errpipe_write)
1154
1155 if p2cread is not None and p2cwrite is not None:
1156 os.close(p2cread)
1157 if c2pwrite is not None and c2pread is not None:
1158 os.close(c2pwrite)
1159 if errwrite is not None and errread is not None:
1160 os.close(errwrite)
1161
1162 # Wait for exec to fail or succeed; possibly raising an
1163 # exception (limited to 1 MB)
Gregory P. Smith3fff44d2010-03-01 00:43:08 +00001164 data = _eintr_retry_call(os.read, errpipe_read, 1048576)
Facundo Batista10706e22009-06-19 20:34:30 +00001165 finally:
1166 # be sure the FD is closed no matter what
1167 os.close(errpipe_read)
1168
Guido van Rossumaf2362a2007-05-15 22:32:02 +00001169 if data:
Gregory P. Smithb740e762010-12-14 15:16:24 +00001170 try:
1171 _eintr_retry_call(os.waitpid, self.pid, 0)
1172 except OSError as e:
1173 if e.errno != errno.ECHILD:
1174 raise
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001175 child_exception = pickle.loads(data)
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001176 for fd in (p2cwrite, c2pread, errread):
1177 if fd is not None:
1178 os.close(fd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001179 raise child_exception
1180
1181
Brett Cannon19640502010-05-14 01:28:56 +00001182 def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED,
1183 _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED,
1184 _WEXITSTATUS=os.WEXITSTATUS):
1185 # This method is called (indirectly) by __del__, so it cannot
1186 # refer to anything outside of its local scope."""
1187 if _WIFSIGNALED(sts):
1188 self.returncode = -_WTERMSIG(sts)
1189 elif _WIFEXITED(sts):
1190 self.returncode = _WEXITSTATUS(sts)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001191 else:
1192 # Should never happen
1193 raise RuntimeError("Unknown child exit status!")
1194
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001195
Brett Cannon19640502010-05-14 01:28:56 +00001196 def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid,
1197 _WNOHANG=os.WNOHANG, _os_error=os.error):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001198 """Check if child process has terminated. Returns returncode
Brett Cannon19640502010-05-14 01:28:56 +00001199 attribute.
1200
1201 This method is called by __del__, so it cannot reference anything
1202 outside of the local scope (nor can any methods it calls).
1203
1204 """
Peter Astrandd38ddf42005-02-10 08:32:50 +00001205 if self.returncode is None:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001206 try:
Brett Cannon19640502010-05-14 01:28:56 +00001207 pid, sts = _waitpid(self.pid, _WNOHANG)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001208 if pid == self.pid:
1209 self._handle_exitstatus(sts)
Brett Cannon19640502010-05-14 01:28:56 +00001210 except _os_error:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001211 if _deadstate is not None:
1212 self.returncode = _deadstate
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001213 return self.returncode
1214
1215
1216 def wait(self):
1217 """Wait for child process to terminate. Returns returncode
1218 attribute."""
Peter Astrandd38ddf42005-02-10 08:32:50 +00001219 if self.returncode is None:
Gregory P. Smithb740e762010-12-14 15:16:24 +00001220 try:
1221 pid, sts = _eintr_retry_call(os.waitpid, self.pid, 0)
1222 except OSError as e:
1223 if e.errno != errno.ECHILD:
1224 raise
1225 # This happens if SIGCLD is set to be ignored or waiting
1226 # for child processes has otherwise been disabled for our
1227 # process. This child is dead, we can't get the status.
1228 sts = 0
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001229 self._handle_exitstatus(sts)
1230 return self.returncode
1231
1232
Peter Astrand23109f02005-03-03 20:28:59 +00001233 def _communicate(self, input):
Georg Brandlae83d6e2009-08-13 09:04:31 +00001234 if self.stdin:
1235 # Flush stdio buffer. This might block, if the user has
1236 # been writing to .stdin in an uncontrolled fashion.
1237 self.stdin.flush()
1238 if not input:
1239 self.stdin.close()
1240
1241 if _has_poll:
1242 stdout, stderr = self._communicate_with_poll(input)
1243 else:
1244 stdout, stderr = self._communicate_with_select(input)
1245
1246 # All data exchanged. Translate lists into strings.
1247 if stdout is not None:
1248 stdout = b''.join(stdout)
1249 if stderr is not None:
1250 stderr = b''.join(stderr)
1251
1252 # Translate newlines, if requested.
1253 # This also turns bytes into strings.
1254 if self.universal_newlines:
1255 if stdout is not None:
1256 stdout = self._translate_newlines(stdout,
1257 self.stdout.encoding)
1258 if stderr is not None:
1259 stderr = self._translate_newlines(stderr,
1260 self.stderr.encoding)
1261
1262 self.wait()
1263 return (stdout, stderr)
1264
1265
1266 def _communicate_with_poll(self, input):
1267 stdout = None # Return
1268 stderr = None # Return
1269 fd2file = {}
1270 fd2output = {}
1271
1272 poller = select.poll()
1273 def register_and_append(file_obj, eventmask):
1274 poller.register(file_obj.fileno(), eventmask)
1275 fd2file[file_obj.fileno()] = file_obj
1276
1277 def close_unregister_and_remove(fd):
1278 poller.unregister(fd)
1279 fd2file[fd].close()
1280 fd2file.pop(fd)
1281
1282 if self.stdin and input:
1283 register_and_append(self.stdin, select.POLLOUT)
1284
1285 select_POLLIN_POLLPRI = select.POLLIN | select.POLLPRI
1286 if self.stdout:
1287 register_and_append(self.stdout, select_POLLIN_POLLPRI)
1288 fd2output[self.stdout.fileno()] = stdout = []
1289 if self.stderr:
1290 register_and_append(self.stderr, select_POLLIN_POLLPRI)
1291 fd2output[self.stderr.fileno()] = stderr = []
1292
1293 input_offset = 0
1294 while fd2file:
1295 try:
1296 ready = poller.poll()
1297 except select.error as e:
1298 if e.args[0] == errno.EINTR:
1299 continue
1300 raise
1301
1302 # XXX Rewrite these to use non-blocking I/O on the
1303 # file objects; they are no longer using C stdio!
1304
1305 for fd, mode in ready:
1306 if mode & select.POLLOUT:
1307 chunk = input[input_offset : input_offset + _PIPE_BUF]
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001308 try:
1309 input_offset += os.write(fd, chunk)
1310 except OSError as e:
1311 if e.errno == errno.EPIPE:
1312 close_unregister_and_remove(fd)
1313 else:
1314 raise
1315 else:
1316 if input_offset >= len(input):
1317 close_unregister_and_remove(fd)
Georg Brandlae83d6e2009-08-13 09:04:31 +00001318 elif mode & select_POLLIN_POLLPRI:
1319 data = os.read(fd, 4096)
1320 if not data:
1321 close_unregister_and_remove(fd)
1322 fd2output[fd].append(data)
1323 else:
1324 # Ignore hang up or errors.
1325 close_unregister_and_remove(fd)
1326
1327 return (stdout, stderr)
1328
1329
1330 def _communicate_with_select(self, input):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001331 read_set = []
1332 write_set = []
1333 stdout = None # Return
1334 stderr = None # Return
1335
Georg Brandlae83d6e2009-08-13 09:04:31 +00001336 if self.stdin and input:
1337 write_set.append(self.stdin)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001338 if self.stdout:
1339 read_set.append(self.stdout)
Tim Peterse718f612004-10-12 21:51:32 +00001340 stdout = []
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001341 if self.stderr:
1342 read_set.append(self.stderr)
1343 stderr = []
1344
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001345 input_offset = 0
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001346 while read_set or write_set:
Georg Brandl86b2fb92008-07-16 03:43:04 +00001347 try:
1348 rlist, wlist, xlist = select.select(read_set, write_set, [])
1349 except select.error as e:
1350 if e.args[0] == errno.EINTR:
1351 continue
1352 raise
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001353
Guido van Rossum98297ee2007-11-06 21:34:58 +00001354 # XXX Rewrite these to use non-blocking I/O on the
1355 # file objects; they are no longer using C stdio!
1356
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001357 if self.stdin in wlist:
Georg Brandlae83d6e2009-08-13 09:04:31 +00001358 chunk = input[input_offset : input_offset + _PIPE_BUF]
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001359 try:
1360 bytes_written = os.write(self.stdin.fileno(), chunk)
1361 except OSError as e:
1362 if e.errno == errno.EPIPE:
1363 self.stdin.close()
1364 write_set.remove(self.stdin)
1365 else:
1366 raise
1367 else:
1368 input_offset += bytes_written
1369 if input_offset >= len(input):
1370 self.stdin.close()
1371 write_set.remove(self.stdin)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001372
1373 if self.stdout in rlist:
1374 data = os.read(self.stdout.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001375 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001376 self.stdout.close()
1377 read_set.remove(self.stdout)
1378 stdout.append(data)
1379
1380 if self.stderr in rlist:
1381 data = os.read(self.stderr.fileno(), 1024)
Guido van Rossumc9e363c2007-05-15 23:18:55 +00001382 if not data:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001383 self.stderr.close()
1384 read_set.remove(self.stderr)
1385 stderr.append(data)
1386
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001387 return (stdout, stderr)
1388
Georg Brandlae83d6e2009-08-13 09:04:31 +00001389
Christian Heimesa342c012008-04-20 21:01:16 +00001390 def send_signal(self, sig):
1391 """Send a signal to the process
1392 """
1393 os.kill(self.pid, sig)
1394
1395 def terminate(self):
1396 """Terminate the process with SIGTERM
1397 """
1398 self.send_signal(signal.SIGTERM)
1399
1400 def kill(self):
1401 """Kill the process with SIGKILL
1402 """
1403 self.send_signal(signal.SIGKILL)
1404
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001405
1406def _demo_posix():
1407 #
1408 # Example 1: Simple redirection: Get process list
1409 #
1410 plist = Popen(["ps"], stdout=PIPE).communicate()[0]
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001411 print("Process list:")
1412 print(plist)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001413
1414 #
1415 # Example 2: Change uid before executing child
1416 #
1417 if os.getuid() == 0:
1418 p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1419 p.wait()
1420
1421 #
1422 # Example 3: Connecting several subprocesses
1423 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001424 print("Looking for 'hda'...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001425 p1 = Popen(["dmesg"], stdout=PIPE)
1426 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001427 print(repr(p2.communicate()[0]))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001428
1429 #
1430 # Example 4: Catch execution error
1431 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001432 print()
1433 print("Trying a weird file...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001434 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001435 print(Popen(["/this/path/does/not/exist"]).communicate())
Guido van Rossumb940e112007-01-10 16:19:56 +00001436 except OSError as e:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001437 if e.errno == errno.ENOENT:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001438 print("The file didn't exist. I thought so...")
1439 print("Child traceback:")
1440 print(e.child_traceback)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001441 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001442 print("Error", e.errno)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001443 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001444 print("Gosh. No error.", file=sys.stderr)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001445
1446
1447def _demo_windows():
1448 #
1449 # Example 1: Connecting several subprocesses
1450 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001451 print("Looking for 'PROMPT' in set output...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001452 p1 = Popen("set", stdout=PIPE, shell=True)
1453 p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001454 print(repr(p2.communicate()[0]))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001455
1456 #
1457 # Example 2: Simple execution of program
1458 #
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001459 print("Executing calc...")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001460 p = Popen("calc")
1461 p.wait()
1462
1463
1464if __name__ == "__main__":
1465 if mswindows:
1466 _demo_windows()
1467 else:
1468 _demo_posix()