ยปCore Development>Code coverage>Lib/subprocess.py

Python code coverage for Lib/subprocess.py

#countcontent
1n/a# subprocess - Subprocesses with accessible I/O streams
2n/a#
3n/a# For more information about this module, see PEP 324.
4n/a#
5n/a# Copyright (c) 2003-2005 by Peter Astrand <astrand@lysator.liu.se>
6n/a#
7n/a# Licensed to PSF under a Contributor Agreement.
8n/a# See http://www.python.org/2.4/license for licensing details.
9n/a
10n/ar"""subprocess - Subprocesses with accessible I/O streams
11n/a
12n/aThis module allows you to spawn processes, connect to their
13n/ainput/output/error pipes, and obtain their return codes. This module
14n/aintends to replace several other, older modules and functions, like:
15n/a
16n/aos.system
17n/aos.spawn*
18n/a
19n/aInformation about how the subprocess module can be used to replace these
20n/amodules and functions can be found below.
21n/a
22n/a
23n/a
24n/aUsing the subprocess module
25n/a===========================
26n/aThis module defines one class called Popen:
27n/a
28n/aclass Popen(args, bufsize=0, executable=None,
29n/a stdin=None, stdout=None, stderr=None,
30n/a preexec_fn=None, close_fds=False, shell=False,
31n/a cwd=None, env=None, universal_newlines=False,
32n/a startupinfo=None, creationflags=0,
33n/a restore_signals=True, start_new_session=False):
34n/a
35n/a
36n/aArguments are:
37n/a
38n/aargs should be a string, or a sequence of program arguments. The
39n/aprogram to execute is normally the first item in the args sequence or
40n/astring, but can be explicitly set by using the executable argument.
41n/a
42n/aOn UNIX, with shell=False (default): In this case, the Popen class
43n/auses os.execvp() to execute the child program. args should normally
44n/abe a sequence. A string will be treated as a sequence with the string
45n/aas the only item (the program to execute).
46n/a
47n/aOn UNIX, with shell=True: If args is a string, it specifies the
48n/acommand string to execute through the shell. If args is a sequence,
49n/athe first item specifies the command string, and any additional items
50n/awill be treated as additional shell arguments.
51n/a
52n/aOn Windows: the Popen class uses CreateProcess() to execute the child
53n/aprogram, which operates on strings. If args is a sequence, it will be
54n/aconverted to a string using the list2cmdline method. Please note that
55n/anot all MS Windows applications interpret the command line the same
56n/away: The list2cmdline is designed for applications using the same
57n/arules as the MS C runtime.
58n/a
59n/abufsize, if given, has the same meaning as the corresponding argument
60n/ato the built-in open() function: 0 means unbuffered, 1 means line
61n/abuffered, any other positive value means use a buffer of
62n/a(approximately) that size. A negative bufsize means to use the system
63n/adefault, which usually means fully buffered. The default value for
64n/abufsize is 0 (unbuffered).
65n/a
66n/astdin, stdout and stderr specify the executed programs' standard
67n/ainput, standard output and standard error file handles, respectively.
68n/aValid values are PIPE, an existing file descriptor (a positive
69n/ainteger), an existing file object, and None. PIPE indicates that a
70n/anew pipe to the child should be created. With None, no redirection
71n/awill occur; the child's file handles will be inherited from the
72n/aparent. Additionally, stderr can be STDOUT, which indicates that the
73n/astderr data from the applications should be captured into the same
74n/afile handle as for stdout.
75n/a
76n/aOn UNIX, if preexec_fn is set to a callable object, this object will be
77n/acalled in the child process just before the child is executed. The use
78n/aof preexec_fn is not thread safe, using it in the presence of threads
79n/acould lead to a deadlock in the child process before the new executable
80n/ais executed.
81n/a
82n/aIf close_fds is true, all file descriptors except 0, 1 and 2 will be
83n/aclosed before the child process is executed.
84n/a
85n/aif shell is true, the specified command will be executed through the
86n/ashell.
87n/a
88n/aIf cwd is not None, the current directory will be changed to cwd
89n/abefore the child is executed.
90n/a
91n/aOn UNIX, if restore_signals is True all signals that Python sets to
92n/aSIG_IGN are restored to SIG_DFL in the child process before the exec.
93n/aCurrently this includes the SIGPIPE, SIGXFZ and SIGXFSZ signals. This
94n/aparameter does nothing on Windows.
95n/a
96n/aOn UNIX, if start_new_session is True, the setsid() system call will be made
97n/ain the child process prior to executing the command.
98n/a
99n/aIf env is not None, it defines the environment variables for the new
100n/aprocess.
101n/a
102n/aIf universal_newlines is true, the file objects stdout and stderr are
103n/aopened as a text files, but lines may be terminated by any of '\n',
104n/athe Unix end-of-line convention, '\r', the Macintosh convention or
105n/a'\r\n', the Windows convention. All of these external representations
106n/aare seen as '\n' by the Python program. Note: This feature is only
107n/aavailable if Python is built with universal newline support (the
108n/adefault). Also, the newlines attribute of the file objects stdout,
109n/astdin and stderr are not updated by the communicate() method.
110n/a
111n/aThe startupinfo and creationflags, if given, will be passed to the
112n/aunderlying CreateProcess() function. They can specify things such as
113n/aappearance of the main window and priority for the new process.
114n/a(Windows only)
115n/a
116n/a
117n/aThis module also defines some shortcut functions:
118n/a
119n/acall(*popenargs, **kwargs):
120n/a Run command with arguments. Wait for command to complete, then
121n/a return the returncode attribute.
122n/a
123n/a The arguments are the same as for the Popen constructor. Example:
124n/a
125n/a >>> retcode = subprocess.call(["ls", "-l"])
126n/a
127n/acheck_call(*popenargs, **kwargs):
128n/a Run command with arguments. Wait for command to complete. If the
129n/a exit code was zero then return, otherwise raise
130n/a CalledProcessError. The CalledProcessError object will have the
131n/a return code in the returncode attribute.
132n/a
133n/a The arguments are the same as for the Popen constructor. Example:
134n/a
135n/a >>> subprocess.check_call(["ls", "-l"])
136n/a 0
137n/a
138n/agetstatusoutput(cmd):
139n/a Return (status, output) of executing cmd in a shell.
140n/a
141n/a Execute the string 'cmd' in a shell with os.popen() and return a 2-tuple
142n/a (status, output). cmd is actually run as '{ cmd ; } 2>&1', so that the
143n/a returned output will contain output or error messages. A trailing newline
144n/a is stripped from the output. The exit status for the command can be
145n/a interpreted according to the rules for the C function wait(). Example:
146n/a
147n/a >>> subprocess.getstatusoutput('ls /bin/ls')
148n/a (0, '/bin/ls')
149n/a >>> subprocess.getstatusoutput('cat /bin/junk')
150n/a (256, 'cat: /bin/junk: No such file or directory')
151n/a >>> subprocess.getstatusoutput('/bin/junk')
152n/a (256, 'sh: /bin/junk: not found')
153n/a
154n/agetoutput(cmd):
155n/a Return output (stdout or stderr) of executing cmd in a shell.
156n/a
157n/a Like getstatusoutput(), except the exit status is ignored and the return
158n/a value is a string containing the command's output. Example:
159n/a
160n/a >>> subprocess.getoutput('ls /bin/ls')
161n/a '/bin/ls'
162n/a
163n/acheck_output(*popenargs, **kwargs):
164n/a Run command with arguments and return its output as a byte string.
165n/a
166n/a If the exit code was non-zero it raises a CalledProcessError. The
167n/a CalledProcessError object will have the return code in the returncode
168n/a attribute and output in the output attribute.
169n/a
170n/a The arguments are the same as for the Popen constructor. Example:
171n/a
172n/a >>> output = subprocess.check_output(["ls", "-l", "/dev/null"])
173n/a
174n/a
175n/aExceptions
176n/a----------
177n/aExceptions raised in the child process, before the new program has
178n/astarted to execute, will be re-raised in the parent. Additionally,
179n/athe exception object will have one extra attribute called
180n/a'child_traceback', which is a string containing traceback information
181n/afrom the childs point of view.
182n/a
183n/aThe most common exception raised is OSError. This occurs, for
184n/aexample, when trying to execute a non-existent file. Applications
185n/ashould prepare for OSErrors.
186n/a
187n/aA ValueError will be raised if Popen is called with invalid arguments.
188n/a
189n/acheck_call() and check_output() will raise CalledProcessError, if the
190n/acalled process returns a non-zero return code.
191n/a
192n/a
193n/aSecurity
194n/a--------
195n/aUnlike some other popen functions, this implementation will never call
196n/a/bin/sh implicitly. This means that all characters, including shell
197n/ametacharacters, can safely be passed to child processes.
198n/a
199n/a
200n/aPopen objects
201n/a=============
202n/aInstances of the Popen class have the following methods:
203n/a
204n/apoll()
205n/a Check if child process has terminated. Returns returncode
206n/a attribute.
207n/a
208n/await()
209n/a Wait for child process to terminate. Returns returncode attribute.
210n/a
211n/acommunicate(input=None)
212n/a Interact with process: Send data to stdin. Read data from stdout
213n/a and stderr, until end-of-file is reached. Wait for process to
214n/a terminate. The optional input argument should be a string to be
215n/a sent to the child process, or None, if no data should be sent to
216n/a the child.
217n/a
218n/a communicate() returns a tuple (stdout, stderr).
219n/a
220n/a Note: The data read is buffered in memory, so do not use this
221n/a method if the data size is large or unlimited.
222n/a
223n/aThe following attributes are also available:
224n/a
225n/astdin
226n/a If the stdin argument is PIPE, this attribute is a file object
227n/a that provides input to the child process. Otherwise, it is None.
228n/a
229n/astdout
230n/a If the stdout argument is PIPE, this attribute is a file object
231n/a that provides output from the child process. Otherwise, it is
232n/a None.
233n/a
234n/astderr
235n/a If the stderr argument is PIPE, this attribute is file object that
236n/a provides error output from the child process. Otherwise, it is
237n/a None.
238n/a
239n/apid
240n/a The process ID of the child process.
241n/a
242n/areturncode
243n/a The child return code. A None value indicates that the process
244n/a hasn't terminated yet. A negative value -N indicates that the
245n/a child was terminated by signal N (UNIX only).
246n/a
247n/a
248n/aReplacing older functions with the subprocess module
249n/a====================================================
250n/aIn this section, "a ==> b" means that b can be used as a replacement
251n/afor a.
252n/a
253n/aNote: All functions in this section fail (more or less) silently if
254n/athe executed program cannot be found; this module raises an OSError
255n/aexception.
256n/a
257n/aIn the following examples, we assume that the subprocess module is
258n/aimported with "from subprocess import *".
259n/a
260n/a
261n/aReplacing /bin/sh shell backquote
262n/a---------------------------------
263n/aoutput=`mycmd myarg`
264n/a==>
265n/aoutput = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
266n/a
267n/a
268n/aReplacing shell pipe line
269n/a-------------------------
270n/aoutput=`dmesg | grep hda`
271n/a==>
272n/ap1 = Popen(["dmesg"], stdout=PIPE)
273n/ap2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
274n/aoutput = p2.communicate()[0]
275n/a
276n/a
277n/aReplacing os.system()
278n/a---------------------
279n/asts = os.system("mycmd" + " myarg")
280n/a==>
281n/ap = Popen("mycmd" + " myarg", shell=True)
282n/apid, sts = os.waitpid(p.pid, 0)
283n/a
284n/aNote:
285n/a
286n/a* Calling the program through the shell is usually not required.
287n/a
288n/a* It's easier to look at the returncode attribute than the
289n/a exitstatus.
290n/a
291n/aA more real-world example would look like this:
292n/a
293n/atry:
294n/a retcode = call("mycmd" + " myarg", shell=True)
295n/a if retcode < 0:
296n/a print("Child was terminated by signal", -retcode, file=sys.stderr)
297n/a else:
298n/a print("Child returned", retcode, file=sys.stderr)
299n/aexcept OSError as e:
300n/a print("Execution failed:", e, file=sys.stderr)
301n/a
302n/a
303n/aReplacing os.spawn*
304n/a-------------------
305n/aP_NOWAIT example:
306n/a
307n/apid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
308n/a==>
309n/apid = Popen(["/bin/mycmd", "myarg"]).pid
310n/a
311n/a
312n/aP_WAIT example:
313n/a
314n/aretcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
315n/a==>
316n/aretcode = call(["/bin/mycmd", "myarg"])
317n/a
318n/a
319n/aVector example:
320n/a
321n/aos.spawnvp(os.P_NOWAIT, path, args)
322n/a==>
323n/aPopen([path] + args[1:])
324n/a
325n/a
326n/aEnvironment example:
327n/a
328n/aos.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
329n/a==>
330n/aPopen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
331n/a"""
332n/a
333n/aimport sys
334n/amswindows = (sys.platform == "win32")
335n/a
336n/aimport io
337n/aimport os
338n/aimport traceback
339n/aimport gc
340n/aimport signal
341n/aimport builtins
342n/a
343n/a# Exception classes used by this module.
344n/aclass CalledProcessError(Exception):
345n/a """This exception is raised when a process run by check_call() or
346n/a check_output() returns a non-zero exit status.
347n/a The exit status will be stored in the returncode attribute;
348n/a check_output() will also store the output in the output attribute.
349n/a """
350n/a def __init__(self, returncode, cmd, output=None):
351n/a self.returncode = returncode
352n/a self.cmd = cmd
353n/a self.output = output
354n/a def __str__(self):
355n/a return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
356n/a
357n/a
358n/aif mswindows:
359n/a import threading
360n/a import msvcrt
361n/a import _subprocess
362n/a class STARTUPINFO:
363n/a dwFlags = 0
364n/a hStdInput = None
365n/a hStdOutput = None
366n/a hStdError = None
367n/a wShowWindow = 0
368n/a class pywintypes:
369n/a error = IOError
370n/aelse:
371n/a import select
372n/a _has_poll = hasattr(select, 'poll')
373n/a import errno
374n/a import fcntl
375n/a import pickle
376n/a
377n/a try:
378n/a import _posixsubprocess
379n/a except ImportError:
380n/a _posixsubprocess = None
381n/a import warnings
382n/a warnings.warn("The _posixsubprocess module is not being used. "
383n/a "Child process reliability may suffer if your "
384n/a "program uses threads.", RuntimeWarning)
385n/a
386n/a # When select or poll has indicated that the file is writable,
387n/a # we can write up to _PIPE_BUF bytes without risk of blocking.
388n/a # POSIX defines PIPE_BUF as >= 512.
389n/a _PIPE_BUF = getattr(select, 'PIPE_BUF', 512)
390n/a
391n/a
392n/a__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "getstatusoutput",
393n/a "getoutput", "check_output", "CalledProcessError"]
394n/a
395n/aif mswindows:
396n/a from _subprocess import CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP
397n/a __all__.extend(["CREATE_NEW_CONSOLE", "CREATE_NEW_PROCESS_GROUP"])
398n/atry:
399n/a MAXFD = os.sysconf("SC_OPEN_MAX")
400n/aexcept:
401n/a MAXFD = 256
402n/a
403n/a_active = []
404n/a
405n/adef _cleanup():
406n/a for inst in _active[:]:
407n/a res = inst._internal_poll(_deadstate=sys.maxsize)
408n/a if res is not None and res >= 0:
409n/a try:
410n/a _active.remove(inst)
411n/a except ValueError:
412n/a # This can happen if two threads create a new Popen instance.
413n/a # It's harmless that it was already removed, so ignore.
414n/a pass
415n/a
416n/aPIPE = -1
417n/aSTDOUT = -2
418n/a
419n/a
420n/adef _eintr_retry_call(func, *args):
421n/a while True:
422n/a try:
423n/a return func(*args)
424n/a except OSError as e:
425n/a if e.errno == errno.EINTR:
426n/a continue
427n/a raise
428n/a
429n/a
430n/adef call(*popenargs, **kwargs):
431n/a """Run command with arguments. Wait for command to complete, then
432n/a return the returncode attribute.
433n/a
434n/a The arguments are the same as for the Popen constructor. Example:
435n/a
436n/a retcode = call(["ls", "-l"])
437n/a """
438n/a return Popen(*popenargs, **kwargs).wait()
439n/a
440n/a
441n/adef check_call(*popenargs, **kwargs):
442n/a """Run command with arguments. Wait for command to complete. If
443n/a the exit code was zero then return, otherwise raise
444n/a CalledProcessError. The CalledProcessError object will have the
445n/a return code in the returncode attribute.
446n/a
447n/a The arguments are the same as for the Popen constructor. Example:
448n/a
449n/a check_call(["ls", "-l"])
450n/a """
451n/a retcode = call(*popenargs, **kwargs)
452n/a if retcode:
453n/a cmd = kwargs.get("args")
454n/a if cmd is None:
455n/a cmd = popenargs[0]
456n/a raise CalledProcessError(retcode, cmd)
457n/a return 0
458n/a
459n/a
460n/adef check_output(*popenargs, **kwargs):
461n/a r"""Run command with arguments and return its output as a byte string.
462n/a
463n/a If the exit code was non-zero it raises a CalledProcessError. The
464n/a CalledProcessError object will have the return code in the returncode
465n/a attribute and output in the output attribute.
466n/a
467n/a The arguments are the same as for the Popen constructor. Example:
468n/a
469n/a >>> check_output(["ls", "-l", "/dev/null"])
470n/a b'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
471n/a
472n/a The stdout argument is not allowed as it is used internally.
473n/a To capture standard error in the result, use stderr=STDOUT.
474n/a
475n/a >>> check_output(["/bin/sh", "-c",
476n/a ... "ls -l non_existent_file ; exit 0"],
477n/a ... stderr=STDOUT)
478n/a b'ls: non_existent_file: No such file or directory\n'
479n/a """
480n/a if 'stdout' in kwargs:
481n/a raise ValueError('stdout argument not allowed, it will be overridden.')
482n/a process = Popen(*popenargs, stdout=PIPE, **kwargs)
483n/a output, unused_err = process.communicate()
484n/a retcode = process.poll()
485n/a if retcode:
486n/a cmd = kwargs.get("args")
487n/a if cmd is None:
488n/a cmd = popenargs[0]
489n/a raise CalledProcessError(retcode, cmd, output=output)
490n/a return output
491n/a
492n/a
493n/adef list2cmdline(seq):
494n/a """
495n/a Translate a sequence of arguments into a command line
496n/a string, using the same rules as the MS C runtime:
497n/a
498n/a 1) Arguments are delimited by white space, which is either a
499n/a space or a tab.
500n/a
501n/a 2) A string surrounded by double quotation marks is
502n/a interpreted as a single argument, regardless of white space
503n/a contained within. A quoted string can be embedded in an
504n/a argument.
505n/a
506n/a 3) A double quotation mark preceded by a backslash is
507n/a interpreted as a literal double quotation mark.
508n/a
509n/a 4) Backslashes are interpreted literally, unless they
510n/a immediately precede a double quotation mark.
511n/a
512n/a 5) If backslashes immediately precede a double quotation mark,
513n/a every pair of backslashes is interpreted as a literal
514n/a backslash. If the number of backslashes is odd, the last
515n/a backslash escapes the next double quotation mark as
516n/a described in rule 3.
517n/a """
518n/a
519n/a # See
520n/a # http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
521n/a # or search http://msdn.microsoft.com for
522n/a # "Parsing C++ Command-Line Arguments"
523n/a result = []
524n/a needquote = False
525n/a for arg in seq:
526n/a bs_buf = []
527n/a
528n/a # Add a space to separate this argument from the others
529n/a if result:
530n/a result.append(' ')
531n/a
532n/a needquote = (" " in arg) or ("\t" in arg) or not arg
533n/a if needquote:
534n/a result.append('"')
535n/a
536n/a for c in arg:
537n/a if c == '\\':
538n/a # Don't know if we need to double yet.
539n/a bs_buf.append(c)
540n/a elif c == '"':
541n/a # Double backslashes.
542n/a result.append('\\' * len(bs_buf)*2)
543n/a bs_buf = []
544n/a result.append('\\"')
545n/a else:
546n/a # Normal char
547n/a if bs_buf:
548n/a result.extend(bs_buf)
549n/a bs_buf = []
550n/a result.append(c)
551n/a
552n/a # Add remaining backslashes, if any.
553n/a if bs_buf:
554n/a result.extend(bs_buf)
555n/a
556n/a if needquote:
557n/a result.extend(bs_buf)
558n/a result.append('"')
559n/a
560n/a return ''.join(result)
561n/a
562n/a
563n/a# Various tools for executing commands and looking at their output and status.
564n/a#
565n/a# NB This only works (and is only relevant) for UNIX.
566n/a
567n/adef getstatusoutput(cmd):
568n/a """Return (status, output) of executing cmd in a shell.
569n/a
570n/a Execute the string 'cmd' in a shell with os.popen() and return a 2-tuple
571n/a (status, output). cmd is actually run as '{ cmd ; } 2>&1', so that the
572n/a returned output will contain output or error messages. A trailing newline
573n/a is stripped from the output. The exit status for the command can be
574n/a interpreted according to the rules for the C function wait(). Example:
575n/a
576n/a >>> import subprocess
577n/a >>> subprocess.getstatusoutput('ls /bin/ls')
578n/a (0, '/bin/ls')
579n/a >>> subprocess.getstatusoutput('cat /bin/junk')
580n/a (256, 'cat: /bin/junk: No such file or directory')
581n/a >>> subprocess.getstatusoutput('/bin/junk')
582n/a (256, 'sh: /bin/junk: not found')
583n/a """
584n/a pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
585n/a text = pipe.read()
586n/a sts = pipe.close()
587n/a if sts is None: sts = 0
588n/a if text[-1:] == '\n': text = text[:-1]
589n/a return sts, text
590n/a
591n/a
592n/adef getoutput(cmd):
593n/a """Return output (stdout or stderr) of executing cmd in a shell.
594n/a
595n/a Like getstatusoutput(), except the exit status is ignored and the return
596n/a value is a string containing the command's output. Example:
597n/a
598n/a >>> import subprocess
599n/a >>> subprocess.getoutput('ls /bin/ls')
600n/a '/bin/ls'
601n/a """
602n/a return getstatusoutput(cmd)[1]
603n/a
604n/a
605n/aclass Popen(object):
606n/a def __init__(self, args, bufsize=0, executable=None,
607n/a stdin=None, stdout=None, stderr=None,
608n/a preexec_fn=None, close_fds=False, shell=False,
609n/a cwd=None, env=None, universal_newlines=False,
610n/a startupinfo=None, creationflags=0,
611n/a restore_signals=True, start_new_session=False):
612n/a """Create new Popen instance."""
613n/a _cleanup()
614n/a
615n/a self._child_created = False
616n/a if bufsize is None:
617n/a bufsize = 0 # Restore default
618n/a if not isinstance(bufsize, int):
619n/a raise TypeError("bufsize must be an integer")
620n/a
621n/a if mswindows:
622n/a if preexec_fn is not None:
623n/a raise ValueError("preexec_fn is not supported on Windows "
624n/a "platforms")
625n/a if close_fds and (stdin is not None or stdout is not None or
626n/a stderr is not None):
627n/a raise ValueError("close_fds is not supported on Windows "
628n/a "platforms if you redirect stdin/stdout/stderr")
629n/a else:
630n/a # POSIX
631n/a if startupinfo is not None:
632n/a raise ValueError("startupinfo is only supported on Windows "
633n/a "platforms")
634n/a if creationflags != 0:
635n/a raise ValueError("creationflags is only supported on Windows "
636n/a "platforms")
637n/a
638n/a self.stdin = None
639n/a self.stdout = None
640n/a self.stderr = None
641n/a self.pid = None
642n/a self.returncode = None
643n/a self.universal_newlines = universal_newlines
644n/a
645n/a # Input and output objects. The general principle is like
646n/a # this:
647n/a #
648n/a # Parent Child
649n/a # ------ -----
650n/a # p2cwrite ---stdin---> p2cread
651n/a # c2pread <--stdout--- c2pwrite
652n/a # errread <--stderr--- errwrite
653n/a #
654n/a # On POSIX, the child objects are file descriptors. On
655n/a # Windows, these are Windows file handles. The parent objects
656n/a # are file descriptors on both platforms. The parent objects
657n/a # are -1 when not using PIPEs. The child objects are -1
658n/a # when not redirecting.
659n/a
660n/a (p2cread, p2cwrite,
661n/a c2pread, c2pwrite,
662n/a errread, errwrite) = self._get_handles(stdin, stdout, stderr)
663n/a
664n/a self._execute_child(args, executable, preexec_fn, close_fds,
665n/a cwd, env, universal_newlines,
666n/a startupinfo, creationflags, shell,
667n/a p2cread, p2cwrite,
668n/a c2pread, c2pwrite,
669n/a errread, errwrite,
670n/a restore_signals, start_new_session)
671n/a
672n/a if mswindows:
673n/a if p2cwrite != -1:
674n/a p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
675n/a if c2pread != -1:
676n/a c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
677n/a if errread != -1:
678n/a errread = msvcrt.open_osfhandle(errread.Detach(), 0)
679n/a
680n/a if bufsize == 0:
681n/a bufsize = 1 # Nearly unbuffered (XXX for now)
682n/a if p2cwrite != -1:
683n/a self.stdin = io.open(p2cwrite, 'wb', bufsize)
684n/a if self.universal_newlines:
685n/a self.stdin = io.TextIOWrapper(self.stdin)
686n/a if c2pread != -1:
687n/a self.stdout = io.open(c2pread, 'rb', bufsize)
688n/a if universal_newlines:
689n/a self.stdout = io.TextIOWrapper(self.stdout)
690n/a if errread != -1:
691n/a self.stderr = io.open(errread, 'rb', bufsize)
692n/a if universal_newlines:
693n/a self.stderr = io.TextIOWrapper(self.stderr)
694n/a
695n/a
696n/a def _translate_newlines(self, data, encoding):
697n/a data = data.replace(b"\r\n", b"\n").replace(b"\r", b"\n")
698n/a return data.decode(encoding)
699n/a
700n/a
701n/a def __del__(self, _maxsize=sys.maxsize, _active=_active):
702n/a if not self._child_created:
703n/a # We didn't get to successfully create a child process.
704n/a return
705n/a # In case the child hasn't been waited on, check if it's done.
706n/a self._internal_poll(_deadstate=_maxsize)
707n/a if self.returncode is None and _active is not None:
708n/a # Child is still running, keep us alive until we can wait on it.
709n/a _active.append(self)
710n/a
711n/a
712n/a def communicate(self, input=None):
713n/a """Interact with process: Send data to stdin. Read data from
714n/a stdout and stderr, until end-of-file is reached. Wait for
715n/a process to terminate. The optional input argument should be a
716n/a string to be sent to the child process, or None, if no data
717n/a should be sent to the child.
718n/a
719n/a communicate() returns a tuple (stdout, stderr)."""
720n/a
721n/a # Optimization: If we are only using one pipe, or no pipe at
722n/a # all, using select() or threads is unnecessary.
723n/a if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
724n/a stdout = None
725n/a stderr = None
726n/a if self.stdin:
727n/a if input:
728n/a self.stdin.write(input)
729n/a self.stdin.close()
730n/a elif self.stdout:
731n/a stdout = self.stdout.read()
732n/a self.stdout.close()
733n/a elif self.stderr:
734n/a stderr = self.stderr.read()
735n/a self.stderr.close()
736n/a self.wait()
737n/a return (stdout, stderr)
738n/a
739n/a return self._communicate(input)
740n/a
741n/a
742n/a def poll(self):
743n/a return self._internal_poll()
744n/a
745n/a
746n/a if mswindows:
747n/a #
748n/a # Windows methods
749n/a #
750n/a def _get_handles(self, stdin, stdout, stderr):
751n/a """Construct and return tuple with IO objects:
752n/a p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
753n/a """
754n/a if stdin is None and stdout is None and stderr is None:
755n/a return (-1, -1, -1, -1, -1, -1)
756n/a
757n/a p2cread, p2cwrite = -1, -1
758n/a c2pread, c2pwrite = -1, -1
759n/a errread, errwrite = -1, -1
760n/a
761n/a if stdin is None:
762n/a p2cread = _subprocess.GetStdHandle(_subprocess.STD_INPUT_HANDLE)
763n/a if p2cread is None:
764n/a p2cread, _ = _subprocess.CreatePipe(None, 0)
765n/a elif stdin == PIPE:
766n/a p2cread, p2cwrite = _subprocess.CreatePipe(None, 0)
767n/a elif isinstance(stdin, int):
768n/a p2cread = msvcrt.get_osfhandle(stdin)
769n/a else:
770n/a # Assuming file-like object
771n/a p2cread = msvcrt.get_osfhandle(stdin.fileno())
772n/a p2cread = self._make_inheritable(p2cread)
773n/a
774n/a if stdout is None:
775n/a c2pwrite = _subprocess.GetStdHandle(_subprocess.STD_OUTPUT_HANDLE)
776n/a if c2pwrite is None:
777n/a _, c2pwrite = _subprocess.CreatePipe(None, 0)
778n/a elif stdout == PIPE:
779n/a c2pread, c2pwrite = _subprocess.CreatePipe(None, 0)
780n/a elif isinstance(stdout, int):
781n/a c2pwrite = msvcrt.get_osfhandle(stdout)
782n/a else:
783n/a # Assuming file-like object
784n/a c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
785n/a c2pwrite = self._make_inheritable(c2pwrite)
786n/a
787n/a if stderr is None:
788n/a errwrite = _subprocess.GetStdHandle(_subprocess.STD_ERROR_HANDLE)
789n/a if errwrite is None:
790n/a _, errwrite = _subprocess.CreatePipe(None, 0)
791n/a elif stderr == PIPE:
792n/a errread, errwrite = _subprocess.CreatePipe(None, 0)
793n/a elif stderr == STDOUT:
794n/a errwrite = c2pwrite
795n/a elif isinstance(stderr, int):
796n/a errwrite = msvcrt.get_osfhandle(stderr)
797n/a else:
798n/a # Assuming file-like object
799n/a errwrite = msvcrt.get_osfhandle(stderr.fileno())
800n/a errwrite = self._make_inheritable(errwrite)
801n/a
802n/a return (p2cread, p2cwrite,
803n/a c2pread, c2pwrite,
804n/a errread, errwrite)
805n/a
806n/a
807n/a def _make_inheritable(self, handle):
808n/a """Return a duplicate of handle, which is inheritable"""
809n/a return _subprocess.DuplicateHandle(_subprocess.GetCurrentProcess(),
810n/a handle, _subprocess.GetCurrentProcess(), 0, 1,
811n/a _subprocess.DUPLICATE_SAME_ACCESS)
812n/a
813n/a
814n/a def _find_w9xpopen(self):
815n/a """Find and return absolut path to w9xpopen.exe"""
816n/a w9xpopen = os.path.join(
817n/a os.path.dirname(_subprocess.GetModuleFileName(0)),
818n/a "w9xpopen.exe")
819n/a if not os.path.exists(w9xpopen):
820n/a # Eeek - file-not-found - possibly an embedding
821n/a # situation - see if we can locate it in sys.exec_prefix
822n/a w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
823n/a "w9xpopen.exe")
824n/a if not os.path.exists(w9xpopen):
825n/a raise RuntimeError("Cannot locate w9xpopen.exe, which is "
826n/a "needed for Popen to work with your "
827n/a "shell or platform.")
828n/a return w9xpopen
829n/a
830n/a
831n/a def _execute_child(self, args, executable, preexec_fn, close_fds,
832n/a cwd, env, universal_newlines,
833n/a startupinfo, creationflags, shell,
834n/a p2cread, p2cwrite,
835n/a c2pread, c2pwrite,
836n/a errread, errwrite,
837n/a unused_restore_signals, unused_start_new_session):
838n/a """Execute program (MS Windows version)"""
839n/a
840n/a if not isinstance(args, str):
841n/a args = list2cmdline(args)
842n/a
843n/a # Process startup details
844n/a if startupinfo is None:
845n/a startupinfo = STARTUPINFO()
846n/a if -1 not in (p2cread, c2pwrite, errwrite):
847n/a startupinfo.dwFlags |= _subprocess.STARTF_USESTDHANDLES
848n/a startupinfo.hStdInput = p2cread
849n/a startupinfo.hStdOutput = c2pwrite
850n/a startupinfo.hStdError = errwrite
851n/a
852n/a if shell:
853n/a startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW
854n/a startupinfo.wShowWindow = _subprocess.SW_HIDE
855n/a comspec = os.environ.get("COMSPEC", "cmd.exe")
856n/a args = comspec + " /c " + args
857n/a if (_subprocess.GetVersion() >= 0x80000000 or
858n/a os.path.basename(comspec).lower() == "command.com"):
859n/a # Win9x, or using command.com on NT. We need to
860n/a # use the w9xpopen intermediate program. For more
861n/a # information, see KB Q150956
862n/a # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
863n/a w9xpopen = self._find_w9xpopen()
864n/a args = '"%s" %s' % (w9xpopen, args)
865n/a # Not passing CREATE_NEW_CONSOLE has been known to
866n/a # cause random failures on win9x. Specifically a
867n/a # dialog: "Your program accessed mem currently in
868n/a # use at xxx" and a hopeful warning about the
869n/a # stability of your system. Cost is Ctrl+C won't
870n/a # kill children.
871n/a creationflags |= _subprocess.CREATE_NEW_CONSOLE
872n/a
873n/a # Start the process
874n/a try:
875n/a hp, ht, pid, tid = _subprocess.CreateProcess(executable, args,
876n/a # no special security
877n/a None, None,
878n/a int(not close_fds),
879n/a creationflags,
880n/a env,
881n/a cwd,
882n/a startupinfo)
883n/a except pywintypes.error as e:
884n/a # Translate pywintypes.error to WindowsError, which is
885n/a # a subclass of OSError. FIXME: We should really
886n/a # translate errno using _sys_errlist (or simliar), but
887n/a # how can this be done from Python?
888n/a raise WindowsError(*e.args)
889n/a
890n/a # Retain the process handle, but close the thread handle
891n/a self._child_created = True
892n/a self._handle = hp
893n/a self.pid = pid
894n/a ht.Close()
895n/a
896n/a # Child is launched. Close the parent's copy of those pipe
897n/a # handles that only the child should have open. You need
898n/a # to make sure that no handles to the write end of the
899n/a # output pipe are maintained in this process or else the
900n/a # pipe will not close when the child process exits and the
901n/a # ReadFile will hang.
902n/a if p2cread != -1:
903n/a p2cread.Close()
904n/a if c2pwrite != -1:
905n/a c2pwrite.Close()
906n/a if errwrite != -1:
907n/a errwrite.Close()
908n/a
909n/a
910n/a def _internal_poll(self, _deadstate=None,
911n/a _WaitForSingleObject=_subprocess.WaitForSingleObject,
912n/a _WAIT_OBJECT_0=_subprocess.WAIT_OBJECT_0,
913n/a _GetExitCodeProcess=_subprocess.GetExitCodeProcess):
914n/a """Check if child process has terminated. Returns returncode
915n/a attribute.
916n/a
917n/a This method is called by __del__, so it can only refer to objects
918n/a in its local scope.
919n/a
920n/a """
921n/a if self.returncode is None:
922n/a if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
923n/a self.returncode = _GetExitCodeProcess(self._handle)
924n/a return self.returncode
925n/a
926n/a
927n/a def wait(self):
928n/a """Wait for child process to terminate. Returns returncode
929n/a attribute."""
930n/a if self.returncode is None:
931n/a _subprocess.WaitForSingleObject(self._handle,
932n/a _subprocess.INFINITE)
933n/a self.returncode = _subprocess.GetExitCodeProcess(self._handle)
934n/a return self.returncode
935n/a
936n/a
937n/a def _readerthread(self, fh, buffer):
938n/a buffer.append(fh.read())
939n/a
940n/a
941n/a def _communicate(self, input):
942n/a stdout = None # Return
943n/a stderr = None # Return
944n/a
945n/a if self.stdout:
946n/a stdout = []
947n/a stdout_thread = threading.Thread(target=self._readerthread,
948n/a args=(self.stdout, stdout))
949n/a stdout_thread.daemon = True
950n/a stdout_thread.start()
951n/a if self.stderr:
952n/a stderr = []
953n/a stderr_thread = threading.Thread(target=self._readerthread,
954n/a args=(self.stderr, stderr))
955n/a stderr_thread.daemon = True
956n/a stderr_thread.start()
957n/a
958n/a if self.stdin:
959n/a if input is not None:
960n/a self.stdin.write(input)
961n/a self.stdin.close()
962n/a
963n/a if self.stdout:
964n/a stdout_thread.join()
965n/a if self.stderr:
966n/a stderr_thread.join()
967n/a
968n/a # All data exchanged. Translate lists into strings.
969n/a if stdout is not None:
970n/a stdout = stdout[0]
971n/a if stderr is not None:
972n/a stderr = stderr[0]
973n/a
974n/a self.wait()
975n/a return (stdout, stderr)
976n/a
977n/a def send_signal(self, sig):
978n/a """Send a signal to the process
979n/a """
980n/a if sig == signal.SIGTERM:
981n/a self.terminate()
982n/a elif sig == signal.CTRL_C_EVENT:
983n/a os.kill(self.pid, signal.CTRL_C_EVENT)
984n/a elif sig == signal.CTRL_BREAK_EVENT:
985n/a os.kill(self.pid, signal.CTRL_BREAK_EVENT)
986n/a else:
987n/a raise ValueError("Only SIGTERM is supported on Windows")
988n/a
989n/a def terminate(self):
990n/a """Terminates the process
991n/a """
992n/a _subprocess.TerminateProcess(self._handle, 1)
993n/a
994n/a kill = terminate
995n/a
996n/a else:
997n/a #
998n/a # POSIX methods
999n/a #
1000n/a def _get_handles(self, stdin, stdout, stderr):
1001n/a """Construct and return tuple with IO objects:
1002n/a p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
1003n/a """
1004n/a p2cread, p2cwrite = -1, -1
1005n/a c2pread, c2pwrite = -1, -1
1006n/a errread, errwrite = -1, -1
1007n/a
1008n/a if stdin is None:
1009n/a pass
1010n/a elif stdin == PIPE:
1011n/a p2cread, p2cwrite = os.pipe()
1012n/a elif isinstance(stdin, int):
1013n/a p2cread = stdin
1014n/a else:
1015n/a # Assuming file-like object
1016n/a p2cread = stdin.fileno()
1017n/a
1018n/a if stdout is None:
1019n/a pass
1020n/a elif stdout == PIPE:
1021n/a c2pread, c2pwrite = os.pipe()
1022n/a elif isinstance(stdout, int):
1023n/a c2pwrite = stdout
1024n/a else:
1025n/a # Assuming file-like object
1026n/a c2pwrite = stdout.fileno()
1027n/a
1028n/a if stderr is None:
1029n/a pass
1030n/a elif stderr == PIPE:
1031n/a errread, errwrite = os.pipe()
1032n/a elif stderr == STDOUT:
1033n/a errwrite = c2pwrite
1034n/a elif isinstance(stderr, int):
1035n/a errwrite = stderr
1036n/a else:
1037n/a # Assuming file-like object
1038n/a errwrite = stderr.fileno()
1039n/a
1040n/a return (p2cread, p2cwrite,
1041n/a c2pread, c2pwrite,
1042n/a errread, errwrite)
1043n/a
1044n/a
1045n/a def _set_cloexec_flag(self, fd):
1046n/a try:
1047n/a cloexec_flag = fcntl.FD_CLOEXEC
1048n/a except AttributeError:
1049n/a cloexec_flag = 1
1050n/a
1051n/a old = fcntl.fcntl(fd, fcntl.F_GETFD)
1052n/a fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
1053n/a
1054n/a
1055n/a def _close_fds(self, but):
1056n/a os.closerange(3, but)
1057n/a os.closerange(but + 1, MAXFD)
1058n/a
1059n/a
1060n/a def _execute_child(self, args, executable, preexec_fn, close_fds,
1061n/a cwd, env, universal_newlines,
1062n/a startupinfo, creationflags, shell,
1063n/a p2cread, p2cwrite,
1064n/a c2pread, c2pwrite,
1065n/a errread, errwrite,
1066n/a restore_signals, start_new_session):
1067n/a """Execute program (POSIX version)"""
1068n/a
1069n/a if isinstance(args, str):
1070n/a args = [args]
1071n/a else:
1072n/a args = list(args)
1073n/a
1074n/a if shell:
1075n/a args = ["/bin/sh", "-c"] + args
1076n/a if executable:
1077n/a args[0] = executable
1078n/a
1079n/a if executable is None:
1080n/a executable = args[0]
1081n/a
1082n/a # For transferring possible exec failure from child to parent.
1083n/a # Data format: "exception name:hex errno:description"
1084n/a # Pickle is not used; it is complex and involves memory allocation.
1085n/a errpipe_read, errpipe_write = os.pipe()
1086n/a try:
1087n/a try:
1088n/a self._set_cloexec_flag(errpipe_write)
1089n/a
1090n/a if _posixsubprocess:
1091n/a # We must avoid complex work that could involve
1092n/a # malloc or free in the child process to avoid
1093n/a # potential deadlocks, thus we do all this here.
1094n/a # and pass it to fork_exec()
1095n/a
1096n/a if env:
1097n/a env_list = [os.fsencode(k) + b'=' + os.fsencode(v)
1098n/a for k, v in env.items()]
1099n/a else:
1100n/a env_list = None # Use execv instead of execve.
1101n/a executable = os.fsencode(executable)
1102n/a if os.path.dirname(executable):
1103n/a executable_list = (executable,)
1104n/a else:
1105n/a # This matches the behavior of os._execvpe().
1106n/a executable_list = tuple(
1107n/a os.path.join(os.fsencode(dir), executable)
1108n/a for dir in os.get_exec_path(env))
1109n/a self.pid = _posixsubprocess.fork_exec(
1110n/a args, executable_list,
1111n/a close_fds, cwd, env_list,
1112n/a p2cread, p2cwrite, c2pread, c2pwrite,
1113n/a errread, errwrite,
1114n/a errpipe_read, errpipe_write,
1115n/a restore_signals, start_new_session, preexec_fn)
1116n/a else:
1117n/a # Pure Python implementation: It is not thread safe.
1118n/a # This implementation may deadlock in the child if your
1119n/a # parent process has any other threads running.
1120n/a
1121n/a gc_was_enabled = gc.isenabled()
1122n/a # Disable gc to avoid bug where gc -> file_dealloc ->
1123n/a # write to stderr -> hang. See issue1336
1124n/a gc.disable()
1125n/a try:
1126n/a self.pid = os.fork()
1127n/a except:
1128n/a if gc_was_enabled:
1129n/a gc.enable()
1130n/a raise
1131n/a self._child_created = True
1132n/a if self.pid == 0:
1133n/a # Child
1134n/a try:
1135n/a # Close parent's pipe ends
1136n/a if p2cwrite != -1:
1137n/a os.close(p2cwrite)
1138n/a if c2pread != -1:
1139n/a os.close(c2pread)
1140n/a if errread != -1:
1141n/a os.close(errread)
1142n/a os.close(errpipe_read)
1143n/a
1144n/a # Dup fds for child
1145n/a if p2cread != -1:
1146n/a os.dup2(p2cread, 0)
1147n/a if c2pwrite != -1:
1148n/a os.dup2(c2pwrite, 1)
1149n/a if errwrite != -1:
1150n/a os.dup2(errwrite, 2)
1151n/a
1152n/a # Close pipe fds. Make sure we don't close the
1153n/a # same fd more than once, or standard fds.
1154n/a if p2cread != -1 and p2cread not in (0,):
1155n/a os.close(p2cread)
1156n/a if (c2pwrite != -1 and
1157n/a c2pwrite not in (p2cread, 1)):
1158n/a os.close(c2pwrite)
1159n/a if (errwrite != -1 and
1160n/a errwrite not in (p2cread, c2pwrite, 2)):
1161n/a os.close(errwrite)
1162n/a
1163n/a # Close all other fds, if asked for
1164n/a if close_fds:
1165n/a self._close_fds(but=errpipe_write)
1166n/a
1167n/a if cwd is not None:
1168n/a os.chdir(cwd)
1169n/a
1170n/a # This is a copy of Python/pythonrun.c
1171n/a # _Py_RestoreSignals(). If that were exposed
1172n/a # as a sys._py_restoresignals func it would be
1173n/a # better.. but this pure python implementation
1174n/a # isn't likely to be used much anymore.
1175n/a if restore_signals:
1176n/a signals = ('SIGPIPE', 'SIGXFZ', 'SIGXFSZ')
1177n/a for sig in signals:
1178n/a if hasattr(signal, sig):
1179n/a signal.signal(getattr(signal, sig),
1180n/a signal.SIG_DFL)
1181n/a
1182n/a if start_new_session and hasattr(os, 'setsid'):
1183n/a os.setsid()
1184n/a
1185n/a if preexec_fn:
1186n/a preexec_fn()
1187n/a
1188n/a if env is None:
1189n/a os.execvp(executable, args)
1190n/a else:
1191n/a os.execvpe(executable, args, env)
1192n/a
1193n/a except:
1194n/a try:
1195n/a exc_type, exc_value = sys.exc_info()[:2]
1196n/a if isinstance(exc_value, OSError):
1197n/a errno = exc_value.errno
1198n/a else:
1199n/a errno = 0
1200n/a message = '%s:%x:%s' % (exc_type.__name__,
1201n/a errno, exc_value)
1202n/a message = message.encode(errors="surrogatepass")
1203n/a os.write(errpipe_write, message)
1204n/a except Exception:
1205n/a # We MUST not allow anything odd happening
1206n/a # above to prevent us from exiting below.
1207n/a pass
1208n/a
1209n/a # This exitcode won't be reported to applications
1210n/a # so it really doesn't matter what we return.
1211n/a os._exit(255)
1212n/a
1213n/a # Parent
1214n/a if gc_was_enabled:
1215n/a gc.enable()
1216n/a finally:
1217n/a # be sure the FD is closed no matter what
1218n/a os.close(errpipe_write)
1219n/a
1220n/a if p2cread != -1 and p2cwrite != -1:
1221n/a os.close(p2cread)
1222n/a if c2pwrite != -1 and c2pread != -1:
1223n/a os.close(c2pwrite)
1224n/a if errwrite != -1 and errread != -1:
1225n/a os.close(errwrite)
1226n/a
1227n/a # Wait for exec to fail or succeed; possibly raising an
1228n/a # exception (limited in size)
1229n/a data = bytearray()
1230n/a while True:
1231n/a part = _eintr_retry_call(os.read, errpipe_read, 50000)
1232n/a data += part
1233n/a if not part or len(data) > 50000:
1234n/a break
1235n/a finally:
1236n/a # be sure the FD is closed no matter what
1237n/a os.close(errpipe_read)
1238n/a
1239n/a if data:
1240n/a _eintr_retry_call(os.waitpid, self.pid, 0)
1241n/a try:
1242n/a exception_name, hex_errno, err_msg = data.split(b':', 2)
1243n/a except ValueError:
1244n/a print('Bad exception data:', repr(data))
1245n/a exception_name = b'RuntimeError'
1246n/a hex_errno = b'0'
1247n/a err_msg = b'Unknown'
1248n/a child_exception_type = getattr(
1249n/a builtins, exception_name.decode('ascii'),
1250n/a RuntimeError)
1251n/a for fd in (p2cwrite, c2pread, errread):
1252n/a if fd != -1:
1253n/a os.close(fd)
1254n/a err_msg = err_msg.decode(errors="surrogatepass")
1255n/a if issubclass(child_exception_type, OSError) and hex_errno:
1256n/a errno = int(hex_errno, 16)
1257n/a if errno != 0:
1258n/a err_msg = os.strerror(errno)
1259n/a raise child_exception_type(errno, err_msg)
1260n/a raise child_exception_type(err_msg)
1261n/a
1262n/a
1263n/a def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED,
1264n/a _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED,
1265n/a _WEXITSTATUS=os.WEXITSTATUS):
1266n/a # This method is called (indirectly) by __del__, so it cannot
1267n/a # refer to anything outside of its local scope."""
1268n/a if _WIFSIGNALED(sts):
1269n/a self.returncode = -_WTERMSIG(sts)
1270n/a elif _WIFEXITED(sts):
1271n/a self.returncode = _WEXITSTATUS(sts)
1272n/a else:
1273n/a # Should never happen
1274n/a raise RuntimeError("Unknown child exit status!")
1275n/a
1276n/a
1277n/a def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid,
1278n/a _WNOHANG=os.WNOHANG, _os_error=os.error):
1279n/a """Check if child process has terminated. Returns returncode
1280n/a attribute.
1281n/a
1282n/a This method is called by __del__, so it cannot reference anything
1283n/a outside of the local scope (nor can any methods it calls).
1284n/a
1285n/a """
1286n/a if self.returncode is None:
1287n/a try:
1288n/a pid, sts = _waitpid(self.pid, _WNOHANG)
1289n/a if pid == self.pid:
1290n/a self._handle_exitstatus(sts)
1291n/a except _os_error:
1292n/a if _deadstate is not None:
1293n/a self.returncode = _deadstate
1294n/a return self.returncode
1295n/a
1296n/a
1297n/a def wait(self):
1298n/a """Wait for child process to terminate. Returns returncode
1299n/a attribute."""
1300n/a if self.returncode is None:
1301n/a pid, sts = _eintr_retry_call(os.waitpid, self.pid, 0)
1302n/a self._handle_exitstatus(sts)
1303n/a return self.returncode
1304n/a
1305n/a
1306n/a def _communicate(self, input):
1307n/a if self.stdin:
1308n/a # Flush stdio buffer. This might block, if the user has
1309n/a # been writing to .stdin in an uncontrolled fashion.
1310n/a self.stdin.flush()
1311n/a if not input:
1312n/a self.stdin.close()
1313n/a
1314n/a if _has_poll:
1315n/a stdout, stderr = self._communicate_with_poll(input)
1316n/a else:
1317n/a stdout, stderr = self._communicate_with_select(input)
1318n/a
1319n/a # All data exchanged. Translate lists into strings.
1320n/a if stdout is not None:
1321n/a stdout = b''.join(stdout)
1322n/a if stderr is not None:
1323n/a stderr = b''.join(stderr)
1324n/a
1325n/a # Translate newlines, if requested.
1326n/a # This also turns bytes into strings.
1327n/a if self.universal_newlines:
1328n/a if stdout is not None:
1329n/a stdout = self._translate_newlines(stdout,
1330n/a self.stdout.encoding)
1331n/a if stderr is not None:
1332n/a stderr = self._translate_newlines(stderr,
1333n/a self.stderr.encoding)
1334n/a
1335n/a self.wait()
1336n/a return (stdout, stderr)
1337n/a
1338n/a
1339n/a def _communicate_with_poll(self, input):
1340n/a stdout = None # Return
1341n/a stderr = None # Return
1342n/a fd2file = {}
1343n/a fd2output = {}
1344n/a
1345n/a poller = select.poll()
1346n/a def register_and_append(file_obj, eventmask):
1347n/a poller.register(file_obj.fileno(), eventmask)
1348n/a fd2file[file_obj.fileno()] = file_obj
1349n/a
1350n/a def close_unregister_and_remove(fd):
1351n/a poller.unregister(fd)
1352n/a fd2file[fd].close()
1353n/a fd2file.pop(fd)
1354n/a
1355n/a if self.stdin and input:
1356n/a register_and_append(self.stdin, select.POLLOUT)
1357n/a
1358n/a select_POLLIN_POLLPRI = select.POLLIN | select.POLLPRI
1359n/a if self.stdout:
1360n/a register_and_append(self.stdout, select_POLLIN_POLLPRI)
1361n/a fd2output[self.stdout.fileno()] = stdout = []
1362n/a if self.stderr:
1363n/a register_and_append(self.stderr, select_POLLIN_POLLPRI)
1364n/a fd2output[self.stderr.fileno()] = stderr = []
1365n/a
1366n/a input_offset = 0
1367n/a while fd2file:
1368n/a try:
1369n/a ready = poller.poll()
1370n/a except select.error as e:
1371n/a if e.args[0] == errno.EINTR:
1372n/a continue
1373n/a raise
1374n/a
1375n/a # XXX Rewrite these to use non-blocking I/O on the
1376n/a # file objects; they are no longer using C stdio!
1377n/a
1378n/a for fd, mode in ready:
1379n/a if mode & select.POLLOUT:
1380n/a chunk = input[input_offset : input_offset + _PIPE_BUF]
1381n/a input_offset += os.write(fd, chunk)
1382n/a if input_offset >= len(input):
1383n/a close_unregister_and_remove(fd)
1384n/a elif mode & select_POLLIN_POLLPRI:
1385n/a data = os.read(fd, 4096)
1386n/a if not data:
1387n/a close_unregister_and_remove(fd)
1388n/a fd2output[fd].append(data)
1389n/a else:
1390n/a # Ignore hang up or errors.
1391n/a close_unregister_and_remove(fd)
1392n/a
1393n/a return (stdout, stderr)
1394n/a
1395n/a
1396n/a def _communicate_with_select(self, input):
1397n/a read_set = []
1398n/a write_set = []
1399n/a stdout = None # Return
1400n/a stderr = None # Return
1401n/a
1402n/a if self.stdin and input:
1403n/a write_set.append(self.stdin)
1404n/a if self.stdout:
1405n/a read_set.append(self.stdout)
1406n/a stdout = []
1407n/a if self.stderr:
1408n/a read_set.append(self.stderr)
1409n/a stderr = []
1410n/a
1411n/a input_offset = 0
1412n/a while read_set or write_set:
1413n/a try:
1414n/a rlist, wlist, xlist = select.select(read_set, write_set, [])
1415n/a except select.error as e:
1416n/a if e.args[0] == errno.EINTR:
1417n/a continue
1418n/a raise
1419n/a
1420n/a # XXX Rewrite these to use non-blocking I/O on the
1421n/a # file objects; they are no longer using C stdio!
1422n/a
1423n/a if self.stdin in wlist:
1424n/a chunk = input[input_offset : input_offset + _PIPE_BUF]
1425n/a bytes_written = os.write(self.stdin.fileno(), chunk)
1426n/a input_offset += bytes_written
1427n/a if input_offset >= len(input):
1428n/a self.stdin.close()
1429n/a write_set.remove(self.stdin)
1430n/a
1431n/a if self.stdout in rlist:
1432n/a data = os.read(self.stdout.fileno(), 1024)
1433n/a if not data:
1434n/a self.stdout.close()
1435n/a read_set.remove(self.stdout)
1436n/a stdout.append(data)
1437n/a
1438n/a if self.stderr in rlist:
1439n/a data = os.read(self.stderr.fileno(), 1024)
1440n/a if not data:
1441n/a self.stderr.close()
1442n/a read_set.remove(self.stderr)
1443n/a stderr.append(data)
1444n/a
1445n/a return (stdout, stderr)
1446n/a
1447n/a
1448n/a def send_signal(self, sig):
1449n/a """Send a signal to the process
1450n/a """
1451n/a os.kill(self.pid, sig)
1452n/a
1453n/a def terminate(self):
1454n/a """Terminate the process with SIGTERM
1455n/a """
1456n/a self.send_signal(signal.SIGTERM)
1457n/a
1458n/a def kill(self):
1459n/a """Kill the process with SIGKILL
1460n/a """
1461n/a self.send_signal(signal.SIGKILL)
1462n/a
1463n/a
1464n/adef _demo_posix():
1465n/a #
1466n/a # Example 1: Simple redirection: Get process list
1467n/a #
1468n/a plist = Popen(["ps"], stdout=PIPE).communicate()[0]
1469n/a print("Process list:")
1470n/a print(plist)
1471n/a
1472n/a #
1473n/a # Example 2: Change uid before executing child
1474n/a #
1475n/a if os.getuid() == 0:
1476n/a p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
1477n/a p.wait()
1478n/a
1479n/a #
1480n/a # Example 3: Connecting several subprocesses
1481n/a #
1482n/a print("Looking for 'hda'...")
1483n/a p1 = Popen(["dmesg"], stdout=PIPE)
1484n/a p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
1485n/a print(repr(p2.communicate()[0]))
1486n/a
1487n/a #
1488n/a # Example 4: Catch execution error
1489n/a #
1490n/a print()
1491n/a print("Trying a weird file...")
1492n/a try:
1493n/a print(Popen(["/this/path/does/not/exist"]).communicate())
1494n/a except OSError as e:
1495n/a if e.errno == errno.ENOENT:
1496n/a print("The file didn't exist. I thought so...")
1497n/a print("Child traceback:")
1498n/a print(e.child_traceback)
1499n/a else:
1500n/a print("Error", e.errno)
1501n/a else:
1502n/a print("Gosh. No error.", file=sys.stderr)
1503n/a
1504n/a
1505n/adef _demo_windows():
1506n/a #
1507n/a # Example 1: Connecting several subprocesses
1508n/a #
1509n/a print("Looking for 'PROMPT' in set output...")
1510n/a p1 = Popen("set", stdout=PIPE, shell=True)
1511n/a p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
1512n/a print(repr(p2.communicate()[0]))
1513n/a
1514n/a #
1515n/a # Example 2: Simple execution of program
1516n/a #
1517n/a print("Executing calc...")
1518n/a p = Popen("calc")
1519n/a p.wait()
1520n/a
1521n/a
1522n/aif __name__ == "__main__":
1523n/a if mswindows:
1524n/a _demo_windows()
1525n/a else:
1526n/a _demo_posix()