blob: da0c31b6c93d9d5248238a4f881645b16c5c5ef6 [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#
5# Copyright (c) 2003-2004 by Peter Astrand <astrand@lysator.liu.se>
6#
7# By obtaining, using, and/or copying this software and/or its
8# associated documentation, you agree that you have read, understood,
9# and will comply with the following terms and conditions:
10#
11# Permission to use, copy, modify, and distribute this software and
12# its associated documentation for any purpose and without fee is
13# hereby granted, provided that the above copyright notice appears in
14# all copies, and that both that copyright notice and this permission
15# notice appear in supporting documentation, and that the name of the
16# author not be used in advertising or publicity pertaining to
17# distribution of the software without specific, written prior
18# permission.
19#
20# THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
21# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
22# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR
23# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
24# OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
25# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
26# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
27
Raymond Hettinger837dd932004-10-17 16:36:53 +000028r"""subprocess - Subprocesses with accessible I/O streams
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000029
Fredrik Lundh15aaacc2004-10-17 14:47:05 +000030This module allows you to spawn processes, connect to their
31input/output/error pipes, and obtain their return codes. This module
32intends to replace several other, older modules and functions, like:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000033
34os.system
35os.spawn*
36os.popen*
37popen2.*
38commands.*
39
40Information about how the subprocess module can be used to replace these
41modules and functions can be found below.
42
43
44
45Using the subprocess module
46===========================
47This module defines one class called Popen:
48
49class Popen(args, bufsize=0, executable=None,
50 stdin=None, stdout=None, stderr=None,
51 preexec_fn=None, close_fds=False, shell=False,
52 cwd=None, env=None, universal_newlines=False,
53 startupinfo=None, creationflags=0):
54
55
56Arguments are:
57
58args should be a string, or a sequence of program arguments. The
59program to execute is normally the first item in the args sequence or
60string, but can be explicitly set by using the executable argument.
61
62On UNIX, with shell=False (default): In this case, the Popen class
63uses os.execvp() to execute the child program. args should normally
64be a sequence. A string will be treated as a sequence with the string
65as the only item (the program to execute).
66
67On UNIX, with shell=True: If args is a string, it specifies the
68command string to execute through the shell. If args is a sequence,
69the first item specifies the command string, and any additional items
70will be treated as additional shell arguments.
71
72On Windows: the Popen class uses CreateProcess() to execute the child
73program, which operates on strings. If args is a sequence, it will be
74converted to a string using the list2cmdline method. Please note that
75not all MS Windows applications interpret the command line the same
76way: The list2cmdline is designed for applications using the same
77rules as the MS C runtime.
78
79bufsize, if given, has the same meaning as the corresponding argument
80to the built-in open() function: 0 means unbuffered, 1 means line
81buffered, any other positive value means use a buffer of
82(approximately) that size. A negative bufsize means to use the system
83default, which usually means fully buffered. The default value for
84bufsize is 0 (unbuffered).
85
86stdin, stdout and stderr specify the executed programs' standard
87input, standard output and standard error file handles, respectively.
88Valid values are PIPE, an existing file descriptor (a positive
89integer), an existing file object, and None. PIPE indicates that a
90new pipe to the child should be created. With None, no redirection
91will occur; the child's file handles will be inherited from the
92parent. Additionally, stderr can be STDOUT, which indicates that the
93stderr data from the applications should be captured into the same
94file handle as for stdout.
95
96If preexec_fn is set to a callable object, this object will be called
97in the child process just before the child is executed.
98
99If close_fds is true, all file descriptors except 0, 1 and 2 will be
100closed before the child process is executed.
101
102if shell is true, the specified command will be executed through the
103shell.
104
105If cwd is not None, the current directory will be changed to cwd
106before the child is executed.
107
108If env is not None, it defines the environment variables for the new
109process.
110
111If universal_newlines is true, the file objects stdout and stderr are
112opened as a text files, but lines may be terminated by any of '\n',
113the Unix end-of-line convention, '\r', the Macintosh convention or
114'\r\n', the Windows convention. All of these external representations
115are seen as '\n' by the Python program. Note: This feature is only
116available if Python is built with universal newline support (the
117default). Also, the newlines attribute of the file objects stdout,
118stdin and stderr are not updated by the communicate() method.
119
120The startupinfo and creationflags, if given, will be passed to the
121underlying CreateProcess() function. They can specify things such as
122appearance of the main window and priority for the new process.
123(Windows only)
124
125
126This module also defines two shortcut functions:
127
Peter Astrand5f5e1412004-12-05 20:15:36 +0000128call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000129 Run command with arguments. Wait for command to complete, then
130 return the returncode attribute.
131
132 The arguments are the same as for the Popen constructor. Example:
133
134 retcode = call(["ls", "-l"])
135
Peter Astrand454f7672005-01-01 09:36:35 +0000136check_call(*popenargs, **kwargs):
137 Run command with arguments. Wait for command to complete. If the
138 exit code was zero then return, otherwise raise
139 CalledProcessError. The CalledProcessError object will have the
140 return code in the errno attribute.
141
142 The arguments are the same as for the Popen constructor. Example:
143
144 check_call(["ls", "-l"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000145
146Exceptions
147----------
148Exceptions raised in the child process, before the new program has
149started to execute, will be re-raised in the parent. Additionally,
150the exception object will have one extra attribute called
151'child_traceback', which is a string containing traceback information
152from the childs point of view.
153
154The most common exception raised is OSError. This occurs, for
155example, when trying to execute a non-existent file. Applications
156should prepare for OSErrors.
157
158A ValueError will be raised if Popen is called with invalid arguments.
159
Peter Astrand454f7672005-01-01 09:36:35 +0000160check_call() will raise CalledProcessError, which is a subclass of
161OSError, if the called process returns a non-zero return code.
162
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000163
164Security
165--------
166Unlike some other popen functions, this implementation will never call
167/bin/sh implicitly. This means that all characters, including shell
168metacharacters, can safely be passed to child processes.
169
170
171Popen objects
172=============
173Instances of the Popen class have the following methods:
174
175poll()
176 Check if child process has terminated. Returns returncode
177 attribute.
178
179wait()
180 Wait for child process to terminate. Returns returncode attribute.
181
182communicate(input=None)
183 Interact with process: Send data to stdin. Read data from stdout
184 and stderr, until end-of-file is reached. Wait for process to
185 terminate. The optional stdin argument should be a string to be
186 sent to the child process, or None, if no data should be sent to
187 the child.
Tim Peterse718f612004-10-12 21:51:32 +0000188
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000189 communicate() returns a tuple (stdout, stderr).
190
191 Note: The data read is buffered in memory, so do not use this
192 method if the data size is large or unlimited.
193
194The following attributes are also available:
195
196stdin
197 If the stdin argument is PIPE, this attribute is a file object
198 that provides input to the child process. Otherwise, it is None.
199
200stdout
201 If the stdout argument is PIPE, this attribute is a file object
202 that provides output from the child process. Otherwise, it is
203 None.
204
205stderr
206 If the stderr argument is PIPE, this attribute is file object that
207 provides error output from the child process. Otherwise, it is
208 None.
209
210pid
211 The process ID of the child process.
212
213returncode
214 The child return code. A None value indicates that the process
215 hasn't terminated yet. A negative value -N indicates that the
216 child was terminated by signal N (UNIX only).
217
218
219Replacing older functions with the subprocess module
220====================================================
221In this section, "a ==> b" means that b can be used as a replacement
222for a.
223
224Note: All functions in this section fail (more or less) silently if
225the executed program cannot be found; this module raises an OSError
226exception.
227
228In the following examples, we assume that the subprocess module is
229imported with "from subprocess import *".
230
231
232Replacing /bin/sh shell backquote
233---------------------------------
234output=`mycmd myarg`
235==>
236output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
237
238
239Replacing shell pipe line
240-------------------------
241output=`dmesg | grep hda`
242==>
243p1 = Popen(["dmesg"], stdout=PIPE)
Peter Astrand6fdf3cb2004-11-30 18:06:42 +0000244p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000245output = p2.communicate()[0]
246
247
248Replacing os.system()
249---------------------
250sts = os.system("mycmd" + " myarg")
251==>
252p = Popen("mycmd" + " myarg", shell=True)
253sts = os.waitpid(p.pid, 0)
254
255Note:
256
257* Calling the program through the shell is usually not required.
258
259* It's easier to look at the returncode attribute than the
260 exitstatus.
261
262A more real-world example would look like this:
263
264try:
265 retcode = call("mycmd" + " myarg", shell=True)
266 if retcode < 0:
267 print >>sys.stderr, "Child was terminated by signal", -retcode
268 else:
269 print >>sys.stderr, "Child returned", retcode
270except OSError, e:
271 print >>sys.stderr, "Execution failed:", e
272
273
274Replacing os.spawn*
275-------------------
Tim Peterse718f612004-10-12 21:51:32 +0000276P_NOWAIT example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000277
278pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
279==>
280pid = Popen(["/bin/mycmd", "myarg"]).pid
281
282
283P_WAIT example:
284
285retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
286==>
287retcode = call(["/bin/mycmd", "myarg"])
288
289
Tim Peterse718f612004-10-12 21:51:32 +0000290Vector example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000291
292os.spawnvp(os.P_NOWAIT, path, args)
293==>
294Popen([path] + args[1:])
295
296
Tim Peterse718f612004-10-12 21:51:32 +0000297Environment example:
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000298
299os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
300==>
301Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
302
303
Tim Peterse718f612004-10-12 21:51:32 +0000304Replacing os.popen*
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000305-------------------
306pipe = os.popen(cmd, mode='r', bufsize)
307==>
308pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout
309
310pipe = os.popen(cmd, mode='w', bufsize)
311==>
312pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
313
314
315(child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
316==>
317p = Popen(cmd, shell=True, bufsize=bufsize,
318 stdin=PIPE, stdout=PIPE, close_fds=True)
319(child_stdin, child_stdout) = (p.stdin, p.stdout)
320
321
322(child_stdin,
323 child_stdout,
324 child_stderr) = os.popen3(cmd, mode, bufsize)
325==>
326p = Popen(cmd, shell=True, bufsize=bufsize,
327 stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
328(child_stdin,
329 child_stdout,
330 child_stderr) = (p.stdin, p.stdout, p.stderr)
331
332
333(child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
334==>
335p = Popen(cmd, shell=True, bufsize=bufsize,
336 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
337(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
338
339
340Replacing popen2.*
341------------------
342Note: If the cmd argument to popen2 functions is a string, the command
343is executed through /bin/sh. If it is a list, the command is directly
344executed.
345
346(child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
347==>
348p = Popen(["somestring"], shell=True, bufsize=bufsize
349 stdin=PIPE, stdout=PIPE, close_fds=True)
350(child_stdout, child_stdin) = (p.stdout, p.stdin)
351
352
353(child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
354==>
355p = Popen(["mycmd", "myarg"], bufsize=bufsize,
356 stdin=PIPE, stdout=PIPE, close_fds=True)
357(child_stdout, child_stdin) = (p.stdout, p.stdin)
358
359The popen2.Popen3 and popen3.Popen4 basically works as subprocess.Popen,
360except that:
361
362* subprocess.Popen raises an exception if the execution fails
363* the capturestderr argument is replaced with the stderr argument.
364* stdin=PIPE and stdout=PIPE must be specified.
365* popen2 closes all filedescriptors by default, but you have to specify
Tim Peterse718f612004-10-12 21:51:32 +0000366 close_fds=True with subprocess.Popen.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000367
368
369"""
370
371import sys
372mswindows = (sys.platform == "win32")
373
374import os
375import types
376import traceback
377
Peter Astrand454f7672005-01-01 09:36:35 +0000378# Exception classes used by this module.
379class CalledProcessError(OSError):
380 """This exception is raised when a process run by check_call() returns
381 a non-zero exit status. The exit status will be stored in the
382 errno attribute. This exception is a subclass of
383 OSError."""
384
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000385if mswindows:
386 import threading
387 import msvcrt
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000388 if 0: # <-- change this to use pywin32 instead of the _subprocess driver
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000389 import pywintypes
Tim Peterse8374a52004-10-13 03:15:00 +0000390 from win32api import GetStdHandle, STD_INPUT_HANDLE, \
391 STD_OUTPUT_HANDLE, STD_ERROR_HANDLE
392 from win32api import GetCurrentProcess, DuplicateHandle, \
393 GetModuleFileName, GetVersion
Peter Astrandc1d65362004-11-07 14:30:34 +0000394 from win32con import DUPLICATE_SAME_ACCESS, SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000395 from win32pipe import CreatePipe
Tim Peterse8374a52004-10-13 03:15:00 +0000396 from win32process import CreateProcess, STARTUPINFO, \
397 GetExitCodeProcess, STARTF_USESTDHANDLES, \
Peter Astrandc1d65362004-11-07 14:30:34 +0000398 STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000399 from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0
Fredrik Lundh3e73a012004-10-13 18:19:18 +0000400 else:
401 from _subprocess import *
402 class STARTUPINFO:
403 dwFlags = 0
404 hStdInput = None
405 hStdOutput = None
406 hStdError = None
407 class pywintypes:
408 error = IOError
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000409else:
410 import select
411 import errno
412 import fcntl
413 import pickle
414
Peter Astrand454f7672005-01-01 09:36:35 +0000415__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "CalledProcessError"]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000416
417try:
418 MAXFD = os.sysconf("SC_OPEN_MAX")
419except:
420 MAXFD = 256
421
422# True/False does not exist on 2.2.0
423try:
424 False
425except NameError:
426 False = 0
427 True = 1
428
429_active = []
430
431def _cleanup():
432 for inst in _active[:]:
433 inst.poll()
434
435PIPE = -1
436STDOUT = -2
437
438
Peter Astrand5f5e1412004-12-05 20:15:36 +0000439def call(*popenargs, **kwargs):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000440 """Run command with arguments. Wait for command to complete, then
441 return the returncode attribute.
442
443 The arguments are the same as for the Popen constructor. Example:
444
445 retcode = call(["ls", "-l"])
446 """
Peter Astrand5f5e1412004-12-05 20:15:36 +0000447 return Popen(*popenargs, **kwargs).wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000448
449
Peter Astrand454f7672005-01-01 09:36:35 +0000450def check_call(*popenargs, **kwargs):
451 """Run command with arguments. Wait for command to complete. If
452 the exit code was zero then return, otherwise raise
453 CalledProcessError. The CalledProcessError object will have the
454 return code in the errno attribute.
455
456 The arguments are the same as for the Popen constructor. Example:
457
458 check_call(["ls", "-l"])
459 """
460 retcode = call(*popenargs, **kwargs)
461 cmd = kwargs.get("args")
462 if cmd is None:
463 cmd = popenargs[0]
464 if retcode:
465 raise CalledProcessError(retcode, "Command %s returned non-zero exit status" % cmd)
466 return retcode
467
468
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000469def list2cmdline(seq):
470 """
471 Translate a sequence of arguments into a command line
472 string, using the same rules as the MS C runtime:
473
474 1) Arguments are delimited by white space, which is either a
475 space or a tab.
476
477 2) A string surrounded by double quotation marks is
478 interpreted as a single argument, regardless of white space
479 contained within. A quoted string can be embedded in an
480 argument.
481
482 3) A double quotation mark preceded by a backslash is
483 interpreted as a literal double quotation mark.
484
485 4) Backslashes are interpreted literally, unless they
486 immediately precede a double quotation mark.
487
488 5) If backslashes immediately precede a double quotation mark,
489 every pair of backslashes is interpreted as a literal
490 backslash. If the number of backslashes is odd, the last
491 backslash escapes the next double quotation mark as
492 described in rule 3.
493 """
494
495 # See
496 # http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp
497 result = []
498 needquote = False
499 for arg in seq:
500 bs_buf = []
501
502 # Add a space to separate this argument from the others
503 if result:
504 result.append(' ')
505
506 needquote = (" " in arg) or ("\t" in arg)
507 if needquote:
508 result.append('"')
509
510 for c in arg:
511 if c == '\\':
Tim Peterse718f612004-10-12 21:51:32 +0000512 # Don't know if we need to double yet.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000513 bs_buf.append(c)
514 elif c == '"':
Tim Peterse718f612004-10-12 21:51:32 +0000515 # Double backspaces.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000516 result.append('\\' * len(bs_buf)*2)
517 bs_buf = []
518 result.append('\\"')
519 else:
520 # Normal char
521 if bs_buf:
522 result.extend(bs_buf)
523 bs_buf = []
524 result.append(c)
525
Tim Peterse718f612004-10-12 21:51:32 +0000526 # Add remaining backspaces, if any.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000527 if bs_buf:
528 result.extend(bs_buf)
529
530 if needquote:
531 result.append('"')
532
533 return ''.join(result)
534
535
536class Popen(object):
537 def __init__(self, args, bufsize=0, executable=None,
538 stdin=None, stdout=None, stderr=None,
539 preexec_fn=None, close_fds=False, shell=False,
540 cwd=None, env=None, universal_newlines=False,
541 startupinfo=None, creationflags=0):
542 """Create new Popen instance."""
543 _cleanup()
544
Peter Astrand738131d2004-11-30 21:04:45 +0000545 if not isinstance(bufsize, (int, long)):
546 raise TypeError("bufsize must be an integer")
547
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000548 if mswindows:
Tim Peterse8374a52004-10-13 03:15:00 +0000549 if preexec_fn is not None:
550 raise ValueError("preexec_fn is not supported on Windows "
551 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000552 if close_fds:
Tim Peterse8374a52004-10-13 03:15:00 +0000553 raise ValueError("close_fds is not supported on Windows "
554 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000555 else:
556 # POSIX
Tim Peterse8374a52004-10-13 03:15:00 +0000557 if startupinfo is not None:
558 raise ValueError("startupinfo is only supported on Windows "
559 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000560 if creationflags != 0:
Tim Peterse8374a52004-10-13 03:15:00 +0000561 raise ValueError("creationflags is only supported on Windows "
562 "platforms")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000563
Tim Peterse718f612004-10-12 21:51:32 +0000564 self.stdin = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000565 self.stdout = None
566 self.stderr = None
567 self.pid = None
568 self.returncode = None
569 self.universal_newlines = universal_newlines
570
571 # Input and output objects. The general principle is like
572 # this:
573 #
574 # Parent Child
575 # ------ -----
576 # p2cwrite ---stdin---> p2cread
577 # c2pread <--stdout--- c2pwrite
578 # errread <--stderr--- errwrite
579 #
580 # On POSIX, the child objects are file descriptors. On
581 # Windows, these are Windows file handles. The parent objects
582 # are file descriptors on both platforms. The parent objects
583 # are None when not using PIPEs. The child objects are None
584 # when not redirecting.
Tim Peterse718f612004-10-12 21:51:32 +0000585
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000586 (p2cread, p2cwrite,
587 c2pread, c2pwrite,
588 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
589
590 self._execute_child(args, executable, preexec_fn, close_fds,
591 cwd, env, universal_newlines,
592 startupinfo, creationflags, shell,
593 p2cread, p2cwrite,
594 c2pread, c2pwrite,
595 errread, errwrite)
596
597 if p2cwrite:
598 self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
599 if c2pread:
600 if universal_newlines:
601 self.stdout = os.fdopen(c2pread, 'rU', bufsize)
602 else:
603 self.stdout = os.fdopen(c2pread, 'rb', bufsize)
604 if errread:
605 if universal_newlines:
606 self.stderr = os.fdopen(errread, 'rU', bufsize)
607 else:
608 self.stderr = os.fdopen(errread, 'rb', bufsize)
Tim Peterse718f612004-10-12 21:51:32 +0000609
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000610 _active.append(self)
611
612
613 def _translate_newlines(self, data):
614 data = data.replace("\r\n", "\n")
615 data = data.replace("\r", "\n")
616 return data
617
618
619 if mswindows:
620 #
621 # Windows methods
622 #
623 def _get_handles(self, stdin, stdout, stderr):
624 """Construct and return tupel with IO objects:
625 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
626 """
627 if stdin == None and stdout == None and stderr == None:
628 return (None, None, None, None, None, None)
Tim Peterse718f612004-10-12 21:51:32 +0000629
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000630 p2cread, p2cwrite = None, None
631 c2pread, c2pwrite = None, None
632 errread, errwrite = None, None
633
634 if stdin == None:
635 p2cread = GetStdHandle(STD_INPUT_HANDLE)
636 elif stdin == PIPE:
637 p2cread, p2cwrite = CreatePipe(None, 0)
638 # Detach and turn into fd
639 p2cwrite = p2cwrite.Detach()
640 p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0)
641 elif type(stdin) == types.IntType:
642 p2cread = msvcrt.get_osfhandle(stdin)
643 else:
644 # Assuming file-like object
645 p2cread = msvcrt.get_osfhandle(stdin.fileno())
646 p2cread = self._make_inheritable(p2cread)
647
648 if stdout == None:
649 c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
650 elif stdout == PIPE:
651 c2pread, c2pwrite = CreatePipe(None, 0)
652 # Detach and turn into fd
653 c2pread = c2pread.Detach()
654 c2pread = msvcrt.open_osfhandle(c2pread, 0)
655 elif type(stdout) == types.IntType:
656 c2pwrite = msvcrt.get_osfhandle(stdout)
657 else:
658 # Assuming file-like object
659 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
660 c2pwrite = self._make_inheritable(c2pwrite)
661
662 if stderr == None:
663 errwrite = GetStdHandle(STD_ERROR_HANDLE)
664 elif stderr == PIPE:
665 errread, errwrite = CreatePipe(None, 0)
666 # Detach and turn into fd
667 errread = errread.Detach()
668 errread = msvcrt.open_osfhandle(errread, 0)
669 elif stderr == STDOUT:
670 errwrite = c2pwrite
671 elif type(stderr) == types.IntType:
672 errwrite = msvcrt.get_osfhandle(stderr)
673 else:
674 # Assuming file-like object
675 errwrite = msvcrt.get_osfhandle(stderr.fileno())
676 errwrite = self._make_inheritable(errwrite)
677
678 return (p2cread, p2cwrite,
679 c2pread, c2pwrite,
680 errread, errwrite)
681
682
683 def _make_inheritable(self, handle):
684 """Return a duplicate of handle, which is inheritable"""
685 return DuplicateHandle(GetCurrentProcess(), handle,
686 GetCurrentProcess(), 0, 1,
687 DUPLICATE_SAME_ACCESS)
688
689
690 def _find_w9xpopen(self):
691 """Find and return absolut path to w9xpopen.exe"""
Tim Peterse8374a52004-10-13 03:15:00 +0000692 w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)),
693 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000694 if not os.path.exists(w9xpopen):
695 # Eeek - file-not-found - possibly an embedding
696 # situation - see if we can locate it in sys.exec_prefix
Tim Peterse8374a52004-10-13 03:15:00 +0000697 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
698 "w9xpopen.exe")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000699 if not os.path.exists(w9xpopen):
Tim Peterse8374a52004-10-13 03:15:00 +0000700 raise RuntimeError("Cannot locate w9xpopen.exe, which is "
701 "needed for Popen to work with your "
702 "shell or platform.")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000703 return w9xpopen
704
Tim Peterse718f612004-10-12 21:51:32 +0000705
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000706 def _execute_child(self, args, executable, preexec_fn, close_fds,
707 cwd, env, universal_newlines,
708 startupinfo, creationflags, shell,
709 p2cread, p2cwrite,
710 c2pread, c2pwrite,
711 errread, errwrite):
712 """Execute program (MS Windows version)"""
713
714 if not isinstance(args, types.StringTypes):
715 args = list2cmdline(args)
716
Peter Astrandc1d65362004-11-07 14:30:34 +0000717 # Process startup details
718 default_startupinfo = STARTUPINFO()
719 if startupinfo == None:
720 startupinfo = default_startupinfo
721 if not None in (p2cread, c2pwrite, errwrite):
722 startupinfo.dwFlags |= STARTF_USESTDHANDLES
723 startupinfo.hStdInput = p2cread
724 startupinfo.hStdOutput = c2pwrite
725 startupinfo.hStdError = errwrite
726
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000727 if shell:
Peter Astrandc1d65362004-11-07 14:30:34 +0000728 default_startupinfo.dwFlags |= STARTF_USESHOWWINDOW
729 default_startupinfo.wShowWindow = SW_HIDE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000730 comspec = os.environ.get("COMSPEC", "cmd.exe")
731 args = comspec + " /c " + args
Tim Peterse8374a52004-10-13 03:15:00 +0000732 if (GetVersion() >= 0x80000000L or
733 os.path.basename(comspec).lower() == "command.com"):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000734 # Win9x, or using command.com on NT. We need to
735 # use the w9xpopen intermediate program. For more
736 # information, see KB Q150956
737 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
738 w9xpopen = self._find_w9xpopen()
739 args = '"%s" %s' % (w9xpopen, args)
740 # Not passing CREATE_NEW_CONSOLE has been known to
741 # cause random failures on win9x. Specifically a
742 # dialog: "Your program accessed mem currently in
743 # use at xxx" and a hopeful warning about the
744 # stability of your system. Cost is Ctrl+C wont
745 # kill children.
746 creationflags |= CREATE_NEW_CONSOLE
747
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000748 # Start the process
749 try:
750 hp, ht, pid, tid = CreateProcess(executable, args,
Tim Peterse8374a52004-10-13 03:15:00 +0000751 # no special security
752 None, None,
753 # must inherit handles to pass std
754 # handles
755 1,
756 creationflags,
757 env,
758 cwd,
759 startupinfo)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000760 except pywintypes.error, e:
761 # Translate pywintypes.error to WindowsError, which is
762 # a subclass of OSError. FIXME: We should really
763 # translate errno using _sys_errlist (or simliar), but
764 # how can this be done from Python?
765 raise WindowsError(*e.args)
766
767 # Retain the process handle, but close the thread handle
768 self._handle = hp
769 self.pid = pid
770 ht.Close()
771
Andrew M. Kuchling51ee66e2004-10-12 16:38:42 +0000772 # Child is launched. Close the parent's copy of those pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000773 # handles that only the child should have open. You need
774 # to make sure that no handles to the write end of the
775 # output pipe are maintained in this process or else the
776 # pipe will not close when the child process exits and the
777 # ReadFile will hang.
778 if p2cread != None:
779 p2cread.Close()
780 if c2pwrite != None:
781 c2pwrite.Close()
782 if errwrite != None:
783 errwrite.Close()
784
Tim Peterse718f612004-10-12 21:51:32 +0000785
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000786 def poll(self):
787 """Check if child process has terminated. Returns returncode
788 attribute."""
789 if self.returncode == None:
790 if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
791 self.returncode = GetExitCodeProcess(self._handle)
792 _active.remove(self)
793 return self.returncode
794
795
796 def wait(self):
797 """Wait for child process to terminate. Returns returncode
798 attribute."""
799 if self.returncode == None:
800 obj = WaitForSingleObject(self._handle, INFINITE)
801 self.returncode = GetExitCodeProcess(self._handle)
802 _active.remove(self)
803 return self.returncode
804
805
806 def _readerthread(self, fh, buffer):
807 buffer.append(fh.read())
808
809
810 def communicate(self, input=None):
811 """Interact with process: Send data to stdin. Read data from
812 stdout and stderr, until end-of-file is reached. Wait for
813 process to terminate. The optional input argument should be a
814 string to be sent to the child process, or None, if no data
815 should be sent to the child.
816
817 communicate() returns a tuple (stdout, stderr)."""
818 stdout = None # Return
819 stderr = None # Return
820
821 if self.stdout:
822 stdout = []
Tim Peterse8374a52004-10-13 03:15:00 +0000823 stdout_thread = threading.Thread(target=self._readerthread,
824 args=(self.stdout, stdout))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000825 stdout_thread.setDaemon(True)
826 stdout_thread.start()
827 if self.stderr:
828 stderr = []
Tim Peterse8374a52004-10-13 03:15:00 +0000829 stderr_thread = threading.Thread(target=self._readerthread,
830 args=(self.stderr, stderr))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000831 stderr_thread.setDaemon(True)
832 stderr_thread.start()
833
834 if self.stdin:
835 if input != None:
836 self.stdin.write(input)
837 self.stdin.close()
838
839 if self.stdout:
840 stdout_thread.join()
841 if self.stderr:
842 stderr_thread.join()
843
844 # All data exchanged. Translate lists into strings.
845 if stdout != None:
846 stdout = stdout[0]
847 if stderr != None:
848 stderr = stderr[0]
849
850 # Translate newlines, if requested. We cannot let the file
851 # object do the translation: It is based on stdio, which is
852 # impossible to combine with select (unless forcing no
853 # buffering).
854 if self.universal_newlines and hasattr(open, 'newlines'):
855 if stdout:
856 stdout = self._translate_newlines(stdout)
857 if stderr:
858 stderr = self._translate_newlines(stderr)
859
860 self.wait()
861 return (stdout, stderr)
862
863 else:
864 #
865 # POSIX methods
866 #
867 def _get_handles(self, stdin, stdout, stderr):
868 """Construct and return tupel with IO objects:
869 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
870 """
871 p2cread, p2cwrite = None, None
872 c2pread, c2pwrite = None, None
873 errread, errwrite = None, None
874
875 if stdin == None:
876 pass
877 elif stdin == PIPE:
878 p2cread, p2cwrite = os.pipe()
879 elif type(stdin) == types.IntType:
880 p2cread = stdin
881 else:
882 # Assuming file-like object
883 p2cread = stdin.fileno()
884
885 if stdout == None:
886 pass
887 elif stdout == PIPE:
888 c2pread, c2pwrite = os.pipe()
889 elif type(stdout) == types.IntType:
890 c2pwrite = stdout
891 else:
892 # Assuming file-like object
Tim Peterse718f612004-10-12 21:51:32 +0000893 c2pwrite = stdout.fileno()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000894
895 if stderr == None:
896 pass
897 elif stderr == PIPE:
898 errread, errwrite = os.pipe()
899 elif stderr == STDOUT:
900 errwrite = c2pwrite
901 elif type(stderr) == types.IntType:
902 errwrite = stderr
903 else:
904 # Assuming file-like object
905 errwrite = stderr.fileno()
906
907 return (p2cread, p2cwrite,
908 c2pread, c2pwrite,
909 errread, errwrite)
910
911
912 def _set_cloexec_flag(self, fd):
913 try:
914 cloexec_flag = fcntl.FD_CLOEXEC
915 except AttributeError:
916 cloexec_flag = 1
917
918 old = fcntl.fcntl(fd, fcntl.F_GETFD)
919 fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
920
921
922 def _close_fds(self, but):
923 for i in range(3, MAXFD):
924 if i == but:
925 continue
926 try:
927 os.close(i)
928 except:
929 pass
Tim Peterse718f612004-10-12 21:51:32 +0000930
931
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000932 def _execute_child(self, args, executable, preexec_fn, close_fds,
933 cwd, env, universal_newlines,
934 startupinfo, creationflags, shell,
935 p2cread, p2cwrite,
936 c2pread, c2pwrite,
937 errread, errwrite):
938 """Execute program (POSIX version)"""
939
940 if isinstance(args, types.StringTypes):
941 args = [args]
942
943 if shell:
944 args = ["/bin/sh", "-c"] + args
945
946 if executable == None:
947 executable = args[0]
948
949 # For transferring possible exec failure from child to parent
950 # The first char specifies the exception type: 0 means
951 # OSError, 1 means some other error.
952 errpipe_read, errpipe_write = os.pipe()
953 self._set_cloexec_flag(errpipe_write)
954
955 self.pid = os.fork()
956 if self.pid == 0:
957 # Child
958 try:
959 # Close parent's pipe ends
960 if p2cwrite:
961 os.close(p2cwrite)
962 if c2pread:
963 os.close(c2pread)
964 if errread:
965 os.close(errread)
966 os.close(errpipe_read)
967
968 # Dup fds for child
969 if p2cread:
970 os.dup2(p2cread, 0)
971 if c2pwrite:
972 os.dup2(c2pwrite, 1)
973 if errwrite:
974 os.dup2(errwrite, 2)
975
976 # Close pipe fds. Make sure we doesn't close the same
977 # fd more than once.
978 if p2cread:
979 os.close(p2cread)
980 if c2pwrite and c2pwrite not in (p2cread,):
981 os.close(c2pwrite)
982 if errwrite and errwrite not in (p2cread, c2pwrite):
983 os.close(errwrite)
984
985 # Close all other fds, if asked for
986 if close_fds:
987 self._close_fds(but=errpipe_write)
988
989 if cwd != None:
990 os.chdir(cwd)
991
992 if preexec_fn:
993 apply(preexec_fn)
994
995 if env == None:
996 os.execvp(executable, args)
997 else:
998 os.execvpe(executable, args, env)
999
1000 except:
1001 exc_type, exc_value, tb = sys.exc_info()
1002 # Save the traceback and attach it to the exception object
Tim Peterse8374a52004-10-13 03:15:00 +00001003 exc_lines = traceback.format_exception(exc_type,
1004 exc_value,
1005 tb)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001006 exc_value.child_traceback = ''.join(exc_lines)
1007 os.write(errpipe_write, pickle.dumps(exc_value))
1008
1009 # This exitcode won't be reported to applications, so it
1010 # really doesn't matter what we return.
1011 os._exit(255)
1012
1013 # Parent
1014 os.close(errpipe_write)
1015 if p2cread and p2cwrite:
1016 os.close(p2cread)
1017 if c2pwrite and c2pread:
1018 os.close(c2pwrite)
1019 if errwrite and errread:
1020 os.close(errwrite)
1021
1022 # Wait for exec to fail or succeed; possibly raising exception
1023 data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB
1024 os.close(errpipe_read)
1025 if data != "":
1026 child_exception = pickle.loads(data)
1027 raise child_exception
1028
1029
1030 def _handle_exitstatus(self, sts):
1031 if os.WIFSIGNALED(sts):
1032 self.returncode = -os.WTERMSIG(sts)
1033 elif os.WIFEXITED(sts):
1034 self.returncode = os.WEXITSTATUS(sts)
1035 else:
1036 # Should never happen
1037 raise RuntimeError("Unknown child exit status!")
1038
1039 _active.remove(self)
1040
Tim Peterse718f612004-10-12 21:51:32 +00001041
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001042 def poll(self):
1043 """Check if child process has terminated. Returns returncode
1044 attribute."""
1045 if self.returncode == None:
1046 try:
1047 pid, sts = os.waitpid(self.pid, os.WNOHANG)
1048 if pid == self.pid:
1049 self._handle_exitstatus(sts)
1050 except os.error:
1051 pass
1052 return self.returncode
1053
1054
1055 def wait(self):
1056 """Wait for child process to terminate. Returns returncode
1057 attribute."""
1058 if self.returncode == None:
1059 pid, sts = os.waitpid(self.pid, 0)
1060 self._handle_exitstatus(sts)
1061 return self.returncode
1062
1063
1064 def communicate(self, input=None):
1065 """Interact with process: Send data to stdin. Read data from
1066 stdout and stderr, until end-of-file is reached. Wait for
1067 process to terminate. The optional input argument should be a
1068 string to be sent to the child process, or None, if no data
1069 should be sent to the child.
1070
1071 communicate() returns a tuple (stdout, stderr)."""
1072 read_set = []
1073 write_set = []
1074 stdout = None # Return
1075 stderr = None # Return
1076
1077 if self.stdin:
1078 # Flush stdio buffer. This might block, if the user has
1079 # been writing to .stdin in an uncontrolled fashion.
1080 self.stdin.flush()
1081 if input:
1082 write_set.append(self.stdin)
1083 else:
1084 self.stdin.close()
1085 if self.stdout:
1086 read_set.append(self.stdout)
Tim Peterse718f612004-10-12 21:51:32 +00001087 stdout = []
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001088 if self.stderr:
1089 read_set.append(self.stderr)
1090 stderr = []
1091
1092 while read_set or write_set:
1093 rlist, wlist, xlist = select.select(read_set, write_set, [])
1094
1095 if self.stdin in wlist:
1096 # When select has indicated that the file is writable,
1097 # we can write up to PIPE_BUF bytes without risk
1098 # blocking. POSIX defines PIPE_BUF >= 512
1099 bytes_written = os.write(self.stdin.fileno(), input[:512])
1100 input = input[bytes_written:]
1101 if not input:
1102 self.stdin.close()
1103 write_set.remove(self.stdin)
1104
1105 if self.stdout in rlist:
1106 data = os.read(self.stdout.fileno(), 1024)
1107 if data == "":
1108 self.stdout.close()
1109 read_set.remove(self.stdout)
1110 stdout.append(data)
1111
1112 if self.stderr in rlist:
1113 data = os.read(self.stderr.fileno(), 1024)
1114 if data == "":
1115 self.stderr.close()
1116 read_set.remove(self.stderr)
1117 stderr.append(data)
1118
1119 # All data exchanged. Translate lists into strings.
1120 if stdout != None:
1121 stdout = ''.join(stdout)
1122 if stderr != None:
1123 stderr = ''.join(stderr)
1124
1125 # Translate newlines, if requested. We cannot let the file
1126 # object do the translation: It is based on stdio, which is
1127 # impossible to combine with select (unless forcing no
1128 # buffering).
1129 if self.universal_newlines and hasattr(open, 'newlines'):
1130 if stdout:
1131 stdout = self._translate_newlines(stdout)
1132 if stderr:
1133 stderr = self._translate_newlines(stderr)
1134
1135 self.wait()
1136 return (stdout, stderr)
1137
1138
1139def _demo_posix():
1140 #
1141 # Example 1: Simple redirection: Get process list
1142 #
1143 plist = Popen(["ps"], stdout=PIPE).communicate()[0]
1144 print "Process list:"
1145 print plist
1146
1147 #
1148 # Example 2: Change uid before executing child
1149 #
1150 if os.getuid() == 0:
1151 p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1152 p.wait()
1153
1154 #
1155 # Example 3: Connecting several subprocesses
1156 #
1157 print "Looking for 'hda'..."
1158 p1 = Popen(["dmesg"], stdout=PIPE)
1159 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
1160 print repr(p2.communicate()[0])
1161
1162 #
1163 # Example 4: Catch execution error
1164 #
1165 print
1166 print "Trying a weird file..."
1167 try:
1168 print Popen(["/this/path/does/not/exist"]).communicate()
1169 except OSError, e:
1170 if e.errno == errno.ENOENT:
1171 print "The file didn't exist. I thought so..."
1172 print "Child traceback:"
1173 print e.child_traceback
1174 else:
1175 print "Error", e.errno
1176 else:
1177 print >>sys.stderr, "Gosh. No error."
1178
1179
1180def _demo_windows():
1181 #
1182 # Example 1: Connecting several subprocesses
1183 #
1184 print "Looking for 'PROMPT' in set output..."
1185 p1 = Popen("set", stdout=PIPE, shell=True)
1186 p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
1187 print repr(p2.communicate()[0])
1188
1189 #
1190 # Example 2: Simple execution of program
1191 #
1192 print "Executing calc..."
1193 p = Popen("calc")
1194 p.wait()
1195
1196
1197if __name__ == "__main__":
1198 if mswindows:
1199 _demo_windows()
1200 else:
1201 _demo_posix()