blob: 4052c5ef5251dc0dbafcb4484aa7f21426f99fa7 [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +00002from unittest import mock
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003from test import support
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00004import subprocess
5import sys
Gregory P. Smith50e16e32017-01-22 17:28:38 -08006import platform
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00007import signal
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04008import io
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00009import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +000010import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000011import tempfile
12import time
Charles-François Natali3a4586a2013-11-08 19:56:59 +010013import selectors
Ezio Melotti184bdfb2010-02-18 09:37:05 +000014import sysconfig
Gregory P. Smith51ee2702010-12-13 07:59:39 +000015import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040016import shutil
Benjamin Petersonb870aa12011-12-10 12:44:25 -050017import gc
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030018import textwrap
Benjamin Peterson964561b2011-12-10 12:31:42 -050019
20try:
Gregory P. Smith1fa08bc2017-01-22 22:19:38 -080021 import ctypes
22except ImportError:
23 ctypes = None
Gregory P. Smith56bc3b72017-05-23 07:49:13 -070024else:
25 import ctypes.util
Gregory P. Smith1fa08bc2017-01-22 22:19:38 -080026
27try:
Antoine Pitroua8392712013-08-30 23:38:13 +020028 import threading
29except ImportError:
30 threading = None
Benjamin Peterson964561b2011-12-10 12:31:42 -050031
Steve Dower22d06982016-09-06 19:38:15 -070032if support.PGO:
33 raise unittest.SkipTest("test is not helpful for PGO")
34
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000035mswindows = (sys.platform == "win32")
36
37#
38# Depends on the following external programs: Python
39#
40
41if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000042 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
43 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000044else:
45 SETBINARY = ''
46
Florent Xiclunab1e94e82010-02-27 22:12:37 +000047
Florent Xiclunac049d872010-03-27 22:47:23 +000048class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000049 def setUp(self):
50 # Try to minimize the number of children we have so this test
51 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000052 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000053
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000054 def tearDown(self):
55 for inst in subprocess._active:
56 inst.wait()
57 subprocess._cleanup()
58 self.assertFalse(subprocess._active, "subprocess._active not empty")
59
Florent Xiclunab1e94e82010-02-27 22:12:37 +000060 def assertStderrEqual(self, stderr, expected, msg=None):
61 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
62 # shutdown time. That frustrates tests trying to check stderr produced
63 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000064 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040065 # strip_python_stderr also strips whitespace, so we do too.
66 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000067 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000068
Florent Xiclunac049d872010-03-27 22:47:23 +000069
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080070class PopenTestException(Exception):
71 pass
72
73
74class PopenExecuteChildRaises(subprocess.Popen):
75 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
76 _execute_child fails.
77 """
78 def _execute_child(self, *args, **kwargs):
79 raise PopenTestException("Forced Exception for Test")
80
81
Florent Xiclunac049d872010-03-27 22:47:23 +000082class ProcessTestCase(BaseTestCase):
83
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070084 def test_io_buffered_by_default(self):
85 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
86 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
87 stderr=subprocess.PIPE)
88 try:
89 self.assertIsInstance(p.stdin, io.BufferedIOBase)
90 self.assertIsInstance(p.stdout, io.BufferedIOBase)
91 self.assertIsInstance(p.stderr, io.BufferedIOBase)
92 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -070093 p.stdin.close()
94 p.stdout.close()
95 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070096 p.wait()
97
98 def test_io_unbuffered_works(self):
99 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
100 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
101 stderr=subprocess.PIPE, bufsize=0)
102 try:
103 self.assertIsInstance(p.stdin, io.RawIOBase)
104 self.assertIsInstance(p.stdout, io.RawIOBase)
105 self.assertIsInstance(p.stderr, io.RawIOBase)
106 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700107 p.stdin.close()
108 p.stdout.close()
109 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700110 p.wait()
111
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000112 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000113 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000114 rc = subprocess.call([sys.executable, "-c",
115 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000116 self.assertEqual(rc, 47)
117
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400118 def test_call_timeout(self):
119 # call() function with timeout argument; we want to test that the child
120 # process gets killed when the timeout expires. If the child isn't
121 # killed, this call will deadlock since subprocess.call waits for the
122 # child.
123 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
124 [sys.executable, "-c", "while True: pass"],
125 timeout=0.1)
126
Peter Astrand454f7672005-01-01 09:36:35 +0000127 def test_check_call_zero(self):
128 # check_call() function with zero return code
129 rc = subprocess.check_call([sys.executable, "-c",
130 "import sys; sys.exit(0)"])
131 self.assertEqual(rc, 0)
132
133 def test_check_call_nonzero(self):
134 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000135 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000136 subprocess.check_call([sys.executable, "-c",
137 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000138 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000139
Georg Brandlf9734072008-12-07 15:30:06 +0000140 def test_check_output(self):
141 # check_output() function with zero return code
142 output = subprocess.check_output(
143 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000144 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000145
146 def test_check_output_nonzero(self):
147 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000148 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000149 subprocess.check_output(
150 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000151 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000152
153 def test_check_output_stderr(self):
154 # check_output() function stderr redirected to stdout
155 output = subprocess.check_output(
156 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
157 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000158 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000159
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300160 def test_check_output_stdin_arg(self):
161 # check_output() can be called with stdin set to a file
162 tf = tempfile.TemporaryFile()
163 self.addCleanup(tf.close)
164 tf.write(b'pear')
165 tf.seek(0)
166 output = subprocess.check_output(
167 [sys.executable, "-c",
168 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
169 stdin=tf)
170 self.assertIn(b'PEAR', output)
171
172 def test_check_output_input_arg(self):
173 # check_output() can be called with input set to a string
174 output = subprocess.check_output(
175 [sys.executable, "-c",
176 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
177 input=b'pear')
178 self.assertIn(b'PEAR', output)
179
Georg Brandlf9734072008-12-07 15:30:06 +0000180 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300181 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000182 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000183 output = subprocess.check_output(
184 [sys.executable, "-c", "print('will not be run')"],
185 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000186 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000187 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000188
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300189 def test_check_output_stdin_with_input_arg(self):
190 # check_output() refuses to accept 'stdin' with 'input'
191 tf = tempfile.TemporaryFile()
192 self.addCleanup(tf.close)
193 tf.write(b'pear')
194 tf.seek(0)
195 with self.assertRaises(ValueError) as c:
196 output = subprocess.check_output(
197 [sys.executable, "-c", "print('will not be run')"],
198 stdin=tf, input=b'hare')
199 self.fail("Expected ValueError when stdin and input args supplied.")
200 self.assertIn('stdin', c.exception.args[0])
201 self.assertIn('input', c.exception.args[0])
202
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400203 def test_check_output_timeout(self):
204 # check_output() function with timeout arg
205 with self.assertRaises(subprocess.TimeoutExpired) as c:
206 output = subprocess.check_output(
207 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200208 "import sys, time\n"
209 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400210 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200211 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400212 # Some heavily loaded buildbots (sparc Debian 3.x) require
213 # this much time to start and print.
214 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400215 self.fail("Expected TimeoutExpired.")
216 self.assertEqual(c.exception.output, b'BDFL')
217
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000218 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000219 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000220 newenv = os.environ.copy()
221 newenv["FRUIT"] = "banana"
222 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000223 'import sys, os;'
224 'sys.exit(os.getenv("FRUIT")=="banana")'],
225 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000226 self.assertEqual(rc, 1)
227
Victor Stinner87b9bc32011-06-01 00:57:47 +0200228 def test_invalid_args(self):
229 # Popen() called with invalid arguments should raise TypeError
230 # but Popen.__del__ should not complain (issue #12085)
231 with support.captured_stderr() as s:
232 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
233 argcount = subprocess.Popen.__init__.__code__.co_argcount
234 too_many_args = [0] * (argcount + 1)
235 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
236 self.assertEqual(s.getvalue(), '')
237
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000238 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000239 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000240 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000241 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000242 self.addCleanup(p.stdout.close)
243 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000244 p.wait()
245 self.assertEqual(p.stdin, None)
246
247 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200248 # .stdout is None when not redirected, and the child's stdout will
249 # be inherited from the parent. In order to test this we run a
250 # subprocess in a subprocess:
251 # this_test
252 # \-- subprocess created by this test (parent)
253 # \-- subprocess created by the parent subprocess (child)
254 # The parent doesn't specify stdout, so the child will use the
255 # parent's stdout. This test checks that the message printed by the
256 # child goes to the parent stdout. The parent also checks that the
257 # child's stdout is None. See #11963.
258 code = ('import sys; from subprocess import Popen, PIPE;'
259 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
260 ' stdin=PIPE, stderr=PIPE);'
261 'p.wait(); assert p.stdout is None;')
262 p = subprocess.Popen([sys.executable, "-c", code],
263 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
264 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000265 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200266 out, err = p.communicate()
267 self.assertEqual(p.returncode, 0, err)
268 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000269
270 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000271 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000272 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000273 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000274 self.addCleanup(p.stdout.close)
275 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000276 p.wait()
277 self.assertEqual(p.stderr, None)
278
Chris Jerdonek776cb192012-10-08 15:56:43 -0700279 def _assert_python(self, pre_args, **kwargs):
280 # We include sys.exit() to prevent the test runner from hanging
281 # whenever python is found.
282 args = pre_args + ["import sys; sys.exit(47)"]
283 p = subprocess.Popen(args, **kwargs)
284 p.wait()
285 self.assertEqual(47, p.returncode)
286
287 def test_executable(self):
288 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700289 #
290 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
291 # determine where its standard library is, so we need the directory
292 # of args[0] to be valid for the Popen() call to Python to succeed.
293 # See also issue #16170 and issue #7774.
294 doesnotexist = os.path.join(os.path.dirname(sys.executable),
295 "doesnotexist")
296 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700297
298 def test_executable_takes_precedence(self):
299 # Check that the executable argument takes precedence over args[0].
300 #
301 # Verify first that the call succeeds without the executable arg.
302 pre_args = [sys.executable, "-c"]
303 self._assert_python(pre_args)
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +0100304 self.assertRaises((FileNotFoundError, PermissionError),
305 self._assert_python, pre_args,
Chris Jerdonek776cb192012-10-08 15:56:43 -0700306 executable="doesnotexist")
307
308 @unittest.skipIf(mswindows, "executable argument replaces shell")
309 def test_executable_replaces_shell(self):
310 # Check that the executable argument replaces the default shell
311 # when shell=True.
312 self._assert_python([], executable=sys.executable, shell=True)
313
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700314 # For use in the test_cwd* tests below.
315 def _normalize_cwd(self, cwd):
316 # Normalize an expected cwd (for Tru64 support).
317 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
318 # strings. See bug #1063571.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300319 with support.change_cwd(cwd):
320 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700321
322 # For use in the test_cwd* tests below.
323 def _split_python_path(self):
324 # Return normalized (python_dir, python_base).
325 python_path = os.path.realpath(sys.executable)
326 return os.path.split(python_path)
327
328 # For use in the test_cwd* tests below.
329 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
330 # Invoke Python via Popen, and assert that (1) the call succeeds,
331 # and that (2) the current working directory of the child process
332 # matches *expected_cwd*.
333 p = subprocess.Popen([python_arg, "-c",
334 "import os, sys; "
335 "sys.stdout.write(os.getcwd()); "
336 "sys.exit(47)"],
337 stdout=subprocess.PIPE,
338 **kwargs)
339 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000340 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700341 self.assertEqual(47, p.returncode)
342 normcase = os.path.normcase
343 self.assertEqual(normcase(expected_cwd),
344 normcase(p.stdout.read().decode("utf-8")))
345
346 def test_cwd(self):
347 # Check that cwd changes the cwd for the child process.
348 temp_dir = tempfile.gettempdir()
349 temp_dir = self._normalize_cwd(temp_dir)
350 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
351
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530352 def test_cwd_with_pathlike(self):
353 temp_dir = tempfile.gettempdir()
354 temp_dir = self._normalize_cwd(temp_dir)
355
356 class _PathLikeObj:
357 def __fspath__(self):
358 return temp_dir
359
360 self._assert_cwd(temp_dir, sys.executable, cwd=_PathLikeObj())
361
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700362 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700363 def test_cwd_with_relative_arg(self):
364 # Check that Popen looks for args[0] relative to cwd if args[0]
365 # is relative.
366 python_dir, python_base = self._split_python_path()
367 rel_python = os.path.join(os.curdir, python_base)
368 with support.temp_cwd() as wrong_dir:
369 # Before calling with the correct cwd, confirm that the call fails
370 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700371 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700372 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700373 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700374 [rel_python], cwd=wrong_dir)
375 python_dir = self._normalize_cwd(python_dir)
376 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
377
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700378 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700379 def test_cwd_with_relative_executable(self):
380 # Check that Popen looks for executable relative to cwd if executable
381 # is relative (and that executable takes precedence over args[0]).
382 python_dir, python_base = self._split_python_path()
383 rel_python = os.path.join(os.curdir, python_base)
384 doesntexist = "somethingyoudonthave"
385 with support.temp_cwd() as wrong_dir:
386 # Before calling with the correct cwd, confirm that the call fails
387 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700388 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700389 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700390 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700391 [doesntexist], executable=rel_python,
392 cwd=wrong_dir)
393 python_dir = self._normalize_cwd(python_dir)
394 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
395 cwd=python_dir)
396
397 def test_cwd_with_absolute_arg(self):
398 # Check that Popen can find the executable when the cwd is wrong
399 # if args[0] is an absolute path.
400 python_dir, python_base = self._split_python_path()
401 abs_python = os.path.join(python_dir, python_base)
402 rel_python = os.path.join(os.curdir, python_base)
Berker Peksagce643912015-05-06 06:33:17 +0300403 with support.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700404 # Before calling with an absolute path, confirm that using a
405 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700406 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700407 [rel_python], cwd=wrong_dir)
408 wrong_dir = self._normalize_cwd(wrong_dir)
409 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
410
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100411 @unittest.skipIf(sys.base_prefix != sys.prefix,
412 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000413 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700414 python_dir, python_base = self._split_python_path()
415 python_dir = self._normalize_cwd(python_dir)
416 self._assert_cwd(python_dir, "somethingyoudonthave",
417 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000418
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100419 @unittest.skipIf(sys.base_prefix != sys.prefix,
420 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000421 @unittest.skipIf(sysconfig.is_python_build(),
422 "need an installed Python. See #7774")
423 def test_executable_without_cwd(self):
424 # For a normal installation, it should work without 'cwd'
425 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700426 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
427 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000428
429 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000430 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000431 p = subprocess.Popen([sys.executable, "-c",
432 'import sys; sys.exit(sys.stdin.read() == "pear")'],
433 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000434 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000435 p.stdin.close()
436 p.wait()
437 self.assertEqual(p.returncode, 1)
438
439 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000440 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000441 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000442 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000443 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000444 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000445 os.lseek(d, 0, 0)
446 p = subprocess.Popen([sys.executable, "-c",
447 'import sys; sys.exit(sys.stdin.read() == "pear")'],
448 stdin=d)
449 p.wait()
450 self.assertEqual(p.returncode, 1)
451
452 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000453 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000454 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000455 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000456 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000457 tf.seek(0)
458 p = subprocess.Popen([sys.executable, "-c",
459 'import sys; sys.exit(sys.stdin.read() == "pear")'],
460 stdin=tf)
461 p.wait()
462 self.assertEqual(p.returncode, 1)
463
464 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000465 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000466 p = subprocess.Popen([sys.executable, "-c",
467 'import sys; sys.stdout.write("orange")'],
468 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200469 with p:
470 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000471
472 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000473 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000474 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000475 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000476 d = tf.fileno()
477 p = subprocess.Popen([sys.executable, "-c",
478 'import sys; sys.stdout.write("orange")'],
479 stdout=d)
480 p.wait()
481 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000482 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000483
484 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000485 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000486 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000487 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000488 p = subprocess.Popen([sys.executable, "-c",
489 'import sys; sys.stdout.write("orange")'],
490 stdout=tf)
491 p.wait()
492 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000493 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000494
495 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000496 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000497 p = subprocess.Popen([sys.executable, "-c",
498 'import sys; sys.stderr.write("strawberry")'],
499 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200500 with p:
501 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000502
503 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000504 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000505 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000506 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000507 d = tf.fileno()
508 p = subprocess.Popen([sys.executable, "-c",
509 'import sys; sys.stderr.write("strawberry")'],
510 stderr=d)
511 p.wait()
512 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000513 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000514
515 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000516 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000517 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000518 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000519 p = subprocess.Popen([sys.executable, "-c",
520 'import sys; sys.stderr.write("strawberry")'],
521 stderr=tf)
522 p.wait()
523 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000524 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000525
Martin Panterc7635892016-05-13 01:54:44 +0000526 def test_stderr_redirect_with_no_stdout_redirect(self):
527 # test stderr=STDOUT while stdout=None (not set)
528
529 # - grandchild prints to stderr
530 # - child redirects grandchild's stderr to its stdout
531 # - the parent should get grandchild's stderr in child's stdout
532 p = subprocess.Popen([sys.executable, "-c",
533 'import sys, subprocess;'
534 'rc = subprocess.call([sys.executable, "-c",'
535 ' "import sys;"'
536 ' "sys.stderr.write(\'42\')"],'
537 ' stderr=subprocess.STDOUT);'
538 'sys.exit(rc)'],
539 stdout=subprocess.PIPE,
540 stderr=subprocess.PIPE)
541 stdout, stderr = p.communicate()
542 #NOTE: stdout should get stderr from grandchild
543 self.assertStderrEqual(stdout, b'42')
544 self.assertStderrEqual(stderr, b'') # should be empty
545 self.assertEqual(p.returncode, 0)
546
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000547 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000548 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000549 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000550 'import sys;'
551 'sys.stdout.write("apple");'
552 'sys.stdout.flush();'
553 'sys.stderr.write("orange")'],
554 stdout=subprocess.PIPE,
555 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200556 with p:
557 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000558
559 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000560 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000561 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000562 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000563 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000564 'import sys;'
565 'sys.stdout.write("apple");'
566 'sys.stdout.flush();'
567 'sys.stderr.write("orange")'],
568 stdout=tf,
569 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000570 p.wait()
571 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000572 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000573
Thomas Wouters89f507f2006-12-13 04:49:30 +0000574 def test_stdout_filedes_of_stdout(self):
575 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200576 # To avoid printing the text on stdout, we do something similar to
577 # test_stdout_none (see above). The parent subprocess calls the child
578 # subprocess passing stdout=1, and this test uses stdout=PIPE in
579 # order to capture and check the output of the parent. See #11963.
580 code = ('import sys, subprocess; '
581 'rc = subprocess.call([sys.executable, "-c", '
582 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
583 'b\'test with stdout=1\'))"], stdout=1); '
584 'assert rc == 18')
585 p = subprocess.Popen([sys.executable, "-c", code],
586 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
587 self.addCleanup(p.stdout.close)
588 self.addCleanup(p.stderr.close)
589 out, err = p.communicate()
590 self.assertEqual(p.returncode, 0, err)
591 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000592
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200593 def test_stdout_devnull(self):
594 p = subprocess.Popen([sys.executable, "-c",
595 'for i in range(10240):'
596 'print("x" * 1024)'],
597 stdout=subprocess.DEVNULL)
598 p.wait()
599 self.assertEqual(p.stdout, None)
600
601 def test_stderr_devnull(self):
602 p = subprocess.Popen([sys.executable, "-c",
603 'import sys\n'
604 'for i in range(10240):'
605 'sys.stderr.write("x" * 1024)'],
606 stderr=subprocess.DEVNULL)
607 p.wait()
608 self.assertEqual(p.stderr, None)
609
610 def test_stdin_devnull(self):
611 p = subprocess.Popen([sys.executable, "-c",
612 'import sys;'
613 'sys.stdin.read(1)'],
614 stdin=subprocess.DEVNULL)
615 p.wait()
616 self.assertEqual(p.stdin, None)
617
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000618 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000619 newenv = os.environ.copy()
620 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200621 with subprocess.Popen([sys.executable, "-c",
622 'import sys,os;'
623 'sys.stdout.write(os.getenv("FRUIT"))'],
624 stdout=subprocess.PIPE,
625 env=newenv) as p:
626 stdout, stderr = p.communicate()
627 self.assertEqual(stdout, b"orange")
628
Victor Stinner62d51182011-06-23 01:02:25 +0200629 # Windows requires at least the SYSTEMROOT environment variable to start
630 # Python
631 @unittest.skipIf(sys.platform == 'win32',
632 'cannot test an empty env on Windows')
Gregory P. Smithb3512482017-05-30 14:40:37 -0700633 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
634 'The Python shared library cannot be loaded '
635 'with an empty environment.')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200636 def test_empty_env(self):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700637 """Verify that env={} is as empty as possible."""
638
Gregory P. Smith85aba232017-05-30 16:21:47 -0700639 def is_env_var_to_ignore(n):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700640 """Determine if an environment variable is under our control."""
641 # This excludes some __CF_* and VERSIONER_* keys MacOS insists
642 # on adding even when the environment in exec is empty.
643 # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist.
Gregory P. Smith85aba232017-05-30 16:21:47 -0700644 return ('VERSIONER' in n or '__CF' in n or # MacOS
Nick Coghlan6ea41862017-06-11 13:16:15 +1000645 n == 'LD_PRELOAD' or n.startswith('SANDBOX') or # Gentoo
646 n == 'LC_CTYPE') # Locale coercion triggered
Gregory P. Smithb3512482017-05-30 14:40:37 -0700647
Victor Stinnerf1512a22011-06-21 17:18:38 +0200648 with subprocess.Popen([sys.executable, "-c",
Gregory P. Smithb3512482017-05-30 14:40:37 -0700649 'import os; print(list(os.environ.keys()))'],
650 stdout=subprocess.PIPE, env={}) as p:
Victor Stinnerf1512a22011-06-21 17:18:38 +0200651 stdout, stderr = p.communicate()
Gregory P. Smithb3512482017-05-30 14:40:37 -0700652 child_env_names = eval(stdout.strip())
653 self.assertIsInstance(child_env_names, list)
654 child_env_names = [k for k in child_env_names
655 if not is_env_var_to_ignore(k)]
656 self.assertEqual(child_env_names, [])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000657
Serhiy Storchakad174d242017-06-23 19:39:27 +0300658 def test_invalid_cmd(self):
659 # null character in the command name
660 cmd = sys.executable + '\0'
661 with self.assertRaises(ValueError):
662 subprocess.Popen([cmd, "-c", "pass"])
663
664 # null character in the command argument
665 with self.assertRaises(ValueError):
666 subprocess.Popen([sys.executable, "-c", "pass#\0"])
667
668 def test_invalid_env(self):
669 # null character in the enviroment variable name
670 newenv = os.environ.copy()
671 newenv["FRUIT\0VEGETABLE"] = "cabbage"
672 with self.assertRaises(ValueError):
673 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
674
675 # null character in the enviroment variable value
676 newenv = os.environ.copy()
677 newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
678 with self.assertRaises(ValueError):
679 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
680
681 # equal character in the enviroment variable name
682 newenv = os.environ.copy()
683 newenv["FRUIT=ORANGE"] = "lemon"
684 with self.assertRaises(ValueError):
685 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
686
687 # equal character in the enviroment variable value
688 newenv = os.environ.copy()
689 newenv["FRUIT"] = "orange=lemon"
690 with subprocess.Popen([sys.executable, "-c",
691 'import sys, os;'
692 'sys.stdout.write(os.getenv("FRUIT"))'],
693 stdout=subprocess.PIPE,
694 env=newenv) as p:
695 stdout, stderr = p.communicate()
696 self.assertEqual(stdout, b"orange=lemon")
697
Peter Astrandcbac93c2005-03-03 20:24:28 +0000698 def test_communicate_stdin(self):
699 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000700 'import sys;'
701 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000702 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000703 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000704 self.assertEqual(p.returncode, 1)
705
706 def test_communicate_stdout(self):
707 p = subprocess.Popen([sys.executable, "-c",
708 'import sys; sys.stdout.write("pineapple")'],
709 stdout=subprocess.PIPE)
710 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000711 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000712 self.assertEqual(stderr, None)
713
714 def test_communicate_stderr(self):
715 p = subprocess.Popen([sys.executable, "-c",
716 'import sys; sys.stderr.write("pineapple")'],
717 stderr=subprocess.PIPE)
718 (stdout, stderr) = p.communicate()
719 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000720 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000721
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000722 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000723 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000724 'import sys,os;'
725 'sys.stderr.write("pineapple");'
726 'sys.stdout.write(sys.stdin.read())'],
727 stdin=subprocess.PIPE,
728 stdout=subprocess.PIPE,
729 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000730 self.addCleanup(p.stdout.close)
731 self.addCleanup(p.stderr.close)
732 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000733 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000734 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000735 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000736
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400737 def test_communicate_timeout(self):
738 p = subprocess.Popen([sys.executable, "-c",
739 'import sys,os,time;'
740 'sys.stderr.write("pineapple\\n");'
741 'time.sleep(1);'
742 'sys.stderr.write("pear\\n");'
743 'sys.stdout.write(sys.stdin.read())'],
744 universal_newlines=True,
745 stdin=subprocess.PIPE,
746 stdout=subprocess.PIPE,
747 stderr=subprocess.PIPE)
748 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
749 timeout=0.3)
750 # Make sure we can keep waiting for it, and that we get the whole output
751 # after it completes.
752 (stdout, stderr) = p.communicate()
753 self.assertEqual(stdout, "banana")
754 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
755
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700756 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200757 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400758 p = subprocess.Popen([sys.executable, "-c",
759 'import sys,os,time;'
760 'sys.stdout.write("a" * (64 * 1024));'
761 'time.sleep(0.2);'
762 'sys.stdout.write("a" * (64 * 1024));'
763 'time.sleep(0.2);'
764 'sys.stdout.write("a" * (64 * 1024));'
765 'time.sleep(0.2);'
766 'sys.stdout.write("a" * (64 * 1024));'],
767 stdout=subprocess.PIPE)
768 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
769 (stdout, _) = p.communicate()
770 self.assertEqual(len(stdout), 4 * 64 * 1024)
771
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000772 # Test for the fd leak reported in http://bugs.python.org/issue2791.
773 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000774 for stdin_pipe in (False, True):
775 for stdout_pipe in (False, True):
776 for stderr_pipe in (False, True):
777 options = {}
778 if stdin_pipe:
779 options['stdin'] = subprocess.PIPE
780 if stdout_pipe:
781 options['stdout'] = subprocess.PIPE
782 if stderr_pipe:
783 options['stderr'] = subprocess.PIPE
784 if not options:
785 continue
786 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
787 p.communicate()
788 if p.stdin is not None:
789 self.assertTrue(p.stdin.closed)
790 if p.stdout is not None:
791 self.assertTrue(p.stdout.closed)
792 if p.stderr is not None:
793 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000794
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000795 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000796 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000797 p = subprocess.Popen([sys.executable, "-c",
798 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000799 (stdout, stderr) = p.communicate()
800 self.assertEqual(stdout, None)
801 self.assertEqual(stderr, None)
802
803 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000804 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000805 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000806 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000807 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000808 os.close(x)
809 os.close(y)
810 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000811 'import sys,os;'
812 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200813 'sys.stderr.write("x" * %d);'
814 'sys.stdout.write(sys.stdin.read())' %
815 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000816 stdin=subprocess.PIPE,
817 stdout=subprocess.PIPE,
818 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000819 self.addCleanup(p.stdout.close)
820 self.addCleanup(p.stderr.close)
821 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200822 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000823 (stdout, stderr) = p.communicate(string_to_write)
824 self.assertEqual(stdout, string_to_write)
825
826 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000827 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000828 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000829 'import sys,os;'
830 'sys.stdout.write(sys.stdin.read())'],
831 stdin=subprocess.PIPE,
832 stdout=subprocess.PIPE,
833 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000834 self.addCleanup(p.stdout.close)
835 self.addCleanup(p.stderr.close)
836 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000837 p.stdin.write(b"banana")
838 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000839 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000840 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000841
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000842 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000843 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000844 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200845 'buf = sys.stdout.buffer;'
846 'buf.write(sys.stdin.readline().encode());'
847 'buf.flush();'
848 'buf.write(b"line2\\n");'
849 'buf.flush();'
850 'buf.write(sys.stdin.read().encode());'
851 'buf.flush();'
852 'buf.write(b"line4\\n");'
853 'buf.flush();'
854 'buf.write(b"line5\\r\\n");'
855 'buf.flush();'
856 'buf.write(b"line6\\r");'
857 'buf.flush();'
858 'buf.write(b"\\nline7");'
859 'buf.flush();'
860 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200861 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000862 stdout=subprocess.PIPE,
863 universal_newlines=1)
Victor Stinner7438c612016-05-20 12:43:15 +0200864 with p:
865 p.stdin.write("line1\n")
866 p.stdin.flush()
867 self.assertEqual(p.stdout.readline(), "line1\n")
868 p.stdin.write("line3\n")
869 p.stdin.close()
870 self.addCleanup(p.stdout.close)
871 self.assertEqual(p.stdout.readline(),
872 "line2\n")
873 self.assertEqual(p.stdout.read(6),
874 "line3\n")
875 self.assertEqual(p.stdout.read(),
876 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000877
878 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000879 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000880 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000881 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200882 'buf = sys.stdout.buffer;'
883 'buf.write(b"line2\\n");'
884 'buf.flush();'
885 'buf.write(b"line4\\n");'
886 'buf.flush();'
887 'buf.write(b"line5\\r\\n");'
888 'buf.flush();'
889 'buf.write(b"line6\\r");'
890 'buf.flush();'
891 'buf.write(b"\\nline7");'
892 'buf.flush();'
893 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200894 stderr=subprocess.PIPE,
895 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000896 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000897 self.addCleanup(p.stdout.close)
898 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000899 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200900 self.assertEqual(stdout,
901 "line2\nline4\nline5\nline6\nline7\nline8")
902
903 def test_universal_newlines_communicate_stdin(self):
904 # universal newlines through communicate(), with only stdin
905 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300906 'import sys,os;' + SETBINARY + textwrap.dedent('''
907 s = sys.stdin.readline()
908 assert s == "line1\\n", repr(s)
909 s = sys.stdin.read()
910 assert s == "line3\\n", repr(s)
911 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200912 stdin=subprocess.PIPE,
913 universal_newlines=1)
914 (stdout, stderr) = p.communicate("line1\nline3\n")
915 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000916
Andrew Svetlovf3765072012-08-14 18:35:17 +0300917 def test_universal_newlines_communicate_input_none(self):
918 # Test communicate(input=None) with universal newlines.
919 #
920 # We set stdout to PIPE because, as of this writing, a different
921 # code path is tested when the number of pipes is zero or one.
922 p = subprocess.Popen([sys.executable, "-c", "pass"],
923 stdin=subprocess.PIPE,
924 stdout=subprocess.PIPE,
925 universal_newlines=True)
926 p.communicate()
927 self.assertEqual(p.returncode, 0)
928
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300929 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300930 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300931 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300932 'import sys,os;' + SETBINARY + textwrap.dedent('''
933 s = sys.stdin.buffer.readline()
934 sys.stdout.buffer.write(s)
935 sys.stdout.buffer.write(b"line2\\r")
936 sys.stderr.buffer.write(b"eline2\\n")
937 s = sys.stdin.buffer.read()
938 sys.stdout.buffer.write(s)
939 sys.stdout.buffer.write(b"line4\\n")
940 sys.stdout.buffer.write(b"line5\\r\\n")
941 sys.stderr.buffer.write(b"eline6\\r")
942 sys.stderr.buffer.write(b"eline7\\r\\nz")
943 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300944 stdin=subprocess.PIPE,
945 stderr=subprocess.PIPE,
946 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300947 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300948 self.addCleanup(p.stdout.close)
949 self.addCleanup(p.stderr.close)
950 (stdout, stderr) = p.communicate("line1\nline3\n")
951 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300952 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300953 # Python debug build push something like "[42442 refs]\n"
954 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300955 # Don't use assertStderrEqual because it strips CR and LF from output.
956 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300957
Andrew Svetlov82860712012-08-19 22:13:41 +0300958 def test_universal_newlines_communicate_encodings(self):
959 # Check that universal newlines mode works for various encodings,
960 # in particular for encodings in the UTF-16 and UTF-32 families.
961 # See issue #15595.
962 #
963 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
964 # without, and UTF-16 and UTF-32.
965 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +0300966 code = ("import sys; "
967 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
968 encoding)
969 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -0700970 # We set stdin to be non-None because, as of this writing,
971 # a different code path is used when the number of pipes is
972 # zero or one.
973 popen = subprocess.Popen(args,
974 stdin=subprocess.PIPE,
975 stdout=subprocess.PIPE,
976 encoding=encoding)
977 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +0300978 self.assertEqual(stdout, '1\n2\n3\n4')
979
Steve Dower050acae2016-09-06 20:16:17 -0700980 def test_communicate_errors(self):
981 for errors, expected in [
982 ('ignore', ''),
983 ('replace', '\ufffd\ufffd'),
984 ('surrogateescape', '\udc80\udc80'),
985 ('backslashreplace', '\\x80\\x80'),
986 ]:
987 code = ("import sys; "
988 r"sys.stdout.buffer.write(b'[\x80\x80]')")
989 args = [sys.executable, '-c', code]
990 # We set stdin to be non-None because, as of this writing,
991 # a different code path is used when the number of pipes is
992 # zero or one.
993 popen = subprocess.Popen(args,
994 stdin=subprocess.PIPE,
995 stdout=subprocess.PIPE,
996 encoding='utf-8',
997 errors=errors)
998 stdout, stderr = popen.communicate(input='')
999 self.assertEqual(stdout, '[{}]'.format(expected))
1000
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001001 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +00001002 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +00001003 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +00001004 max_handles = 1026 # too much for most UNIX systems
1005 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +00001006 max_handles = 2050 # too much for (at least some) Windows setups
1007 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001008 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +00001009 try:
1010 for i in range(max_handles):
1011 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001012 tmpfile = os.path.join(tmpdir, support.TESTFN)
1013 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +00001014 except OSError as e:
1015 if e.errno != errno.EMFILE:
1016 raise
1017 break
1018 else:
1019 self.skipTest("failed to reach the file descriptor limit "
1020 "(tried %d)" % max_handles)
1021 # Close a couple of them (should be enough for a subprocess)
1022 for i in range(10):
1023 os.close(handles.pop())
1024 # Loop creating some subprocesses. If one of them leaks some fds,
1025 # the next loop iteration will fail by reaching the max fd limit.
1026 for i in range(15):
1027 p = subprocess.Popen([sys.executable, "-c",
1028 "import sys;"
1029 "sys.stdout.write(sys.stdin.read())"],
1030 stdin=subprocess.PIPE,
1031 stdout=subprocess.PIPE,
1032 stderr=subprocess.PIPE)
1033 data = p.communicate(b"lime")[0]
1034 self.assertEqual(data, b"lime")
1035 finally:
1036 for h in handles:
1037 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001038 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001039
1040 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001041 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
1042 '"a b c" d e')
1043 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
1044 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +00001045 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
1046 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001047 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
1048 'a\\\\\\b "de fg" h')
1049 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
1050 'a\\\\\\"b c d')
1051 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
1052 '"a\\\\b c" d e')
1053 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
1054 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001055 self.assertEqual(subprocess.list2cmdline(['ab', '']),
1056 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001057
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001058 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001059 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +02001060 "import os; os.read(0, 1)"],
1061 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001062 self.addCleanup(p.stdin.close)
1063 self.assertIsNone(p.poll())
1064 os.write(p.stdin.fileno(), b'A')
1065 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001066 # Subsequent invocations should just return the returncode
1067 self.assertEqual(p.poll(), 0)
1068
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001069 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001070 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001071 self.assertEqual(p.wait(), 0)
1072 # Subsequent invocations should just return the returncode
1073 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001074
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001075 def test_wait_timeout(self):
1076 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001077 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001078 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001079 p.wait(timeout=0.0001)
1080 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -04001081 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
1082 # time to start.
1083 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001084
Peter Astrand738131d2004-11-30 21:04:45 +00001085 def test_invalid_bufsize(self):
1086 # an invalid type of the bufsize argument should raise
1087 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001088 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +00001089 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001090
Guido van Rossum46a05a72007-06-07 21:56:45 +00001091 def test_bufsize_is_none(self):
1092 # bufsize=None should be the same as bufsize=0.
1093 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
1094 self.assertEqual(p.wait(), 0)
1095 # Again with keyword arg
1096 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
1097 self.assertEqual(p.wait(), 0)
1098
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001099 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1100 # subprocess may deadlock with bufsize=1, see issue #21332
1101 with subprocess.Popen([sys.executable, "-c", "import sys;"
1102 "sys.stdout.write(sys.stdin.readline());"
1103 "sys.stdout.flush()"],
1104 stdin=subprocess.PIPE,
1105 stdout=subprocess.PIPE,
1106 stderr=subprocess.DEVNULL,
1107 bufsize=1,
1108 universal_newlines=universal_newlines) as p:
1109 p.stdin.write(line) # expect that it flushes the line in text mode
1110 os.close(p.stdin.fileno()) # close it without flushing the buffer
1111 read_line = p.stdout.readline()
1112 try:
1113 p.stdin.close()
1114 except OSError:
1115 pass
1116 p.stdin = None
1117 self.assertEqual(p.returncode, 0)
1118 self.assertEqual(read_line, expected)
1119
1120 def test_bufsize_equal_one_text_mode(self):
1121 # line is flushed in text mode with bufsize=1.
1122 # we should get the full line in return
1123 line = "line\n"
1124 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1125
1126 def test_bufsize_equal_one_binary_mode(self):
1127 # line is not flushed in binary mode with bufsize=1.
1128 # we should get empty response
1129 line = b'line' + os.linesep.encode() # assume ascii-based locale
1130 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
1131
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001132 def test_leaking_fds_on_error(self):
1133 # see bug #5179: Popen leaks file descriptors to PIPEs if
1134 # the child fails to execute; this will eventually exhaust
1135 # the maximum number of open fds. 1024 seems a very common
1136 # value for that limit, but Windows has 2048, so we loop
1137 # 1024 times (each call leaked two fds).
1138 for i in range(1024):
Andrew Svetlov3438fa42012-12-17 23:35:18 +02001139 with self.assertRaises(OSError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001140 subprocess.Popen(['nonexisting_i_hope'],
1141 stdout=subprocess.PIPE,
1142 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -04001143 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -04001144 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001145 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001146
Antoine Pitroua8392712013-08-30 23:38:13 +02001147 @unittest.skipIf(threading is None, "threading required")
1148 def test_double_close_on_error(self):
1149 # Issue #18851
1150 fds = []
1151 def open_fds():
1152 for i in range(20):
1153 fds.extend(os.pipe())
1154 time.sleep(0.001)
1155 t = threading.Thread(target=open_fds)
1156 t.start()
1157 try:
1158 with self.assertRaises(EnvironmentError):
1159 subprocess.Popen(['nonexisting_i_hope'],
1160 stdin=subprocess.PIPE,
1161 stdout=subprocess.PIPE,
1162 stderr=subprocess.PIPE)
1163 finally:
1164 t.join()
1165 exc = None
1166 for fd in fds:
1167 # If a double close occurred, some of those fds will
1168 # already have been closed by mistake, and os.close()
1169 # here will raise.
1170 try:
1171 os.close(fd)
1172 except OSError as e:
1173 exc = e
1174 if exc is not None:
1175 raise exc
1176
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001177 @unittest.skipIf(threading is None, "threading required")
1178 def test_threadsafe_wait(self):
1179 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1180 proc = subprocess.Popen([sys.executable, '-c',
1181 'import time; time.sleep(12)'])
1182 self.assertEqual(proc.returncode, None)
1183 results = []
1184
1185 def kill_proc_timer_thread():
1186 results.append(('thread-start-poll-result', proc.poll()))
1187 # terminate it from the thread and wait for the result.
1188 proc.kill()
1189 proc.wait()
1190 results.append(('thread-after-kill-and-wait', proc.returncode))
1191 # this wait should be a no-op given the above.
1192 proc.wait()
1193 results.append(('thread-after-second-wait', proc.returncode))
1194
1195 # This is a timing sensitive test, the failure mode is
1196 # triggered when both the main thread and this thread are in
1197 # the wait() call at once. The delay here is to allow the
1198 # main thread to most likely be blocked in its wait() call.
1199 t = threading.Timer(0.2, kill_proc_timer_thread)
1200 t.start()
1201
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001202 if mswindows:
1203 expected_errorcode = 1
1204 else:
1205 # Should be -9 because of the proc.kill() from the thread.
1206 expected_errorcode = -9
1207
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001208 # Wait for the process to finish; the thread should kill it
1209 # long before it finishes on its own. Supplying a timeout
1210 # triggers a different code path for better coverage.
1211 proc.wait(timeout=20)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001212 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001213 msg="unexpected result in wait from main thread")
1214
1215 # This should be a no-op with no change in returncode.
1216 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001217 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001218 msg="unexpected result in second main wait.")
1219
1220 t.join()
1221 # Ensure that all of the thread results are as expected.
1222 # When a race condition occurs in wait(), the returncode could
1223 # be set by the wrong thread that doesn't actually have it
1224 # leading to an incorrect value.
1225 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001226 ('thread-after-kill-and-wait', expected_errorcode),
1227 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001228 results)
1229
Victor Stinnerb3693582010-05-21 20:13:12 +00001230 def test_issue8780(self):
1231 # Ensure that stdout is inherited from the parent
1232 # if stdout=PIPE is not used
1233 code = ';'.join((
1234 'import subprocess, sys',
1235 'retcode = subprocess.call('
1236 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1237 'assert retcode == 0'))
1238 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001239 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001240
Tim Goldenaf5ac392010-08-06 13:03:56 +00001241 def test_handles_closed_on_exception(self):
1242 # If CreateProcess exits with an error, ensure the
1243 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001244 ifhandle, ifname = tempfile.mkstemp()
1245 ofhandle, ofname = tempfile.mkstemp()
1246 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001247 try:
1248 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1249 stderr=efhandle)
1250 except OSError:
1251 os.close(ifhandle)
1252 os.remove(ifname)
1253 os.close(ofhandle)
1254 os.remove(ofname)
1255 os.close(efhandle)
1256 os.remove(efname)
1257 self.assertFalse(os.path.exists(ifname))
1258 self.assertFalse(os.path.exists(ofname))
1259 self.assertFalse(os.path.exists(efname))
1260
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001261 def test_communicate_epipe(self):
1262 # Issue 10963: communicate() should hide EPIPE
1263 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1264 stdin=subprocess.PIPE,
1265 stdout=subprocess.PIPE,
1266 stderr=subprocess.PIPE)
1267 self.addCleanup(p.stdout.close)
1268 self.addCleanup(p.stderr.close)
1269 self.addCleanup(p.stdin.close)
1270 p.communicate(b"x" * 2**20)
1271
1272 def test_communicate_epipe_only_stdin(self):
1273 # Issue 10963: communicate() should hide EPIPE
1274 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1275 stdin=subprocess.PIPE)
1276 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001277 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001278 p.communicate(b"x" * 2**20)
1279
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001280 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1281 "Requires signal.SIGUSR1")
1282 @unittest.skipUnless(hasattr(os, 'kill'),
1283 "Requires os.kill")
1284 @unittest.skipUnless(hasattr(os, 'getppid'),
1285 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001286 def test_communicate_eintr(self):
1287 # Issue #12493: communicate() should handle EINTR
1288 def handler(signum, frame):
1289 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001290 old_handler = signal.signal(signal.SIGUSR1, handler)
1291 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001292
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001293 args = [sys.executable, "-c",
1294 'import os, signal;'
1295 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001296 for stream in ('stdout', 'stderr'):
1297 kw = {stream: subprocess.PIPE}
1298 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001299 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001300 process.communicate()
1301
Tim Peterse718f612004-10-12 21:51:32 +00001302
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001303 # This test is Linux-ish specific for simplicity to at least have
1304 # some coverage. It is not a platform specific bug.
1305 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1306 "Linux specific")
1307 def test_failed_child_execute_fd_leak(self):
1308 """Test for the fork() failure fd leak reported in issue16327."""
1309 fd_directory = '/proc/%d/fd' % os.getpid()
1310 fds_before_popen = os.listdir(fd_directory)
1311 with self.assertRaises(PopenTestException):
1312 PopenExecuteChildRaises(
1313 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
1314 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1315
1316 # NOTE: This test doesn't verify that the real _execute_child
1317 # does not close the file descriptors itself on the way out
1318 # during an exception. Code inspection has confirmed that.
1319
1320 fds_after_exception = os.listdir(fd_directory)
1321 self.assertEqual(fds_before_popen, fds_after_exception)
1322
Gregory P. Smith6e730002015-04-14 16:14:25 -07001323
1324class RunFuncTestCase(BaseTestCase):
1325 def run_python(self, code, **kwargs):
1326 """Run Python code in a subprocess using subprocess.run"""
1327 argv = [sys.executable, "-c", code]
1328 return subprocess.run(argv, **kwargs)
1329
1330 def test_returncode(self):
1331 # call() function with sequence argument
1332 cp = self.run_python("import sys; sys.exit(47)")
1333 self.assertEqual(cp.returncode, 47)
1334 with self.assertRaises(subprocess.CalledProcessError):
1335 cp.check_returncode()
1336
1337 def test_check(self):
1338 with self.assertRaises(subprocess.CalledProcessError) as c:
1339 self.run_python("import sys; sys.exit(47)", check=True)
1340 self.assertEqual(c.exception.returncode, 47)
1341
1342 def test_check_zero(self):
1343 # check_returncode shouldn't raise when returncode is zero
1344 cp = self.run_python("import sys; sys.exit(0)", check=True)
1345 self.assertEqual(cp.returncode, 0)
1346
1347 def test_timeout(self):
1348 # run() function with timeout argument; we want to test that the child
1349 # process gets killed when the timeout expires. If the child isn't
1350 # killed, this call will deadlock since subprocess.run waits for the
1351 # child.
1352 with self.assertRaises(subprocess.TimeoutExpired):
1353 self.run_python("while True: pass", timeout=0.0001)
1354
1355 def test_capture_stdout(self):
1356 # capture stdout with zero return code
1357 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1358 self.assertIn(b'BDFL', cp.stdout)
1359
1360 def test_capture_stderr(self):
1361 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1362 stderr=subprocess.PIPE)
1363 self.assertIn(b'BDFL', cp.stderr)
1364
1365 def test_check_output_stdin_arg(self):
1366 # run() can be called with stdin set to a file
1367 tf = tempfile.TemporaryFile()
1368 self.addCleanup(tf.close)
1369 tf.write(b'pear')
1370 tf.seek(0)
1371 cp = self.run_python(
1372 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1373 stdin=tf, stdout=subprocess.PIPE)
1374 self.assertIn(b'PEAR', cp.stdout)
1375
1376 def test_check_output_input_arg(self):
1377 # check_output() can be called with input set to a string
1378 cp = self.run_python(
1379 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1380 input=b'pear', stdout=subprocess.PIPE)
1381 self.assertIn(b'PEAR', cp.stdout)
1382
1383 def test_check_output_stdin_with_input_arg(self):
1384 # run() refuses to accept 'stdin' with 'input'
1385 tf = tempfile.TemporaryFile()
1386 self.addCleanup(tf.close)
1387 tf.write(b'pear')
1388 tf.seek(0)
1389 with self.assertRaises(ValueError,
1390 msg="Expected ValueError when stdin and input args supplied.") as c:
1391 output = self.run_python("print('will not be run')",
1392 stdin=tf, input=b'hare')
1393 self.assertIn('stdin', c.exception.args[0])
1394 self.assertIn('input', c.exception.args[0])
1395
1396 def test_check_output_timeout(self):
1397 with self.assertRaises(subprocess.TimeoutExpired) as c:
1398 cp = self.run_python((
1399 "import sys, time\n"
1400 "sys.stdout.write('BDFL')\n"
1401 "sys.stdout.flush()\n"
1402 "time.sleep(3600)"),
1403 # Some heavily loaded buildbots (sparc Debian 3.x) require
1404 # this much time to start and print.
1405 timeout=3, stdout=subprocess.PIPE)
1406 self.assertEqual(c.exception.output, b'BDFL')
1407 # output is aliased to stdout
1408 self.assertEqual(c.exception.stdout, b'BDFL')
1409
1410 def test_run_kwargs(self):
1411 newenv = os.environ.copy()
1412 newenv["FRUIT"] = "banana"
1413 cp = self.run_python(('import sys, os;'
1414 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1415 env=newenv)
1416 self.assertEqual(cp.returncode, 33)
1417
1418
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001419@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001420class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001421
Gregory P. Smith5591b022012-10-10 03:34:47 -07001422 def setUp(self):
1423 super().setUp()
1424 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1425
1426 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001427 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001428 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001429 except OSError as e:
1430 # This avoids hard coding the errno value or the OS perror()
1431 # string and instead capture the exception that we want to see
1432 # below for comparison.
1433 desired_exception = e
Gregory P. Smith5591b022012-10-10 03:34:47 -07001434 desired_exception.strerror += ': ' + repr(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001435 else:
Martin Pantereb995702016-07-28 01:11:04 +00001436 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001437 self._nonexistent_dir)
1438 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001439
Gregory P. Smith5591b022012-10-10 03:34:47 -07001440 def test_exception_cwd(self):
1441 """Test error in the child raised in the parent for a bad cwd."""
1442 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001443 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001444 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001445 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001446 except OSError as e:
1447 # Test that the child process chdir failure actually makes
1448 # it up to the parent process as the correct exception.
1449 self.assertEqual(desired_exception.errno, e.errno)
1450 self.assertEqual(desired_exception.strerror, e.strerror)
1451 else:
1452 self.fail("Expected OSError: %s" % desired_exception)
1453
Gregory P. Smith5591b022012-10-10 03:34:47 -07001454 def test_exception_bad_executable(self):
1455 """Test error in the child raised in the parent for a bad executable."""
1456 desired_exception = self._get_chdir_exception()
1457 try:
1458 p = subprocess.Popen([sys.executable, "-c", ""],
1459 executable=self._nonexistent_dir)
1460 except OSError as e:
1461 # Test that the child process exec failure actually makes
1462 # it up to the parent process as the correct exception.
1463 self.assertEqual(desired_exception.errno, e.errno)
1464 self.assertEqual(desired_exception.strerror, e.strerror)
1465 else:
1466 self.fail("Expected OSError: %s" % desired_exception)
1467
1468 def test_exception_bad_args_0(self):
1469 """Test error in the child raised in the parent for a bad args[0]."""
1470 desired_exception = self._get_chdir_exception()
1471 try:
1472 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1473 except OSError as e:
1474 # Test that the child process exec failure actually makes
1475 # it up to the parent process as the correct exception.
1476 self.assertEqual(desired_exception.errno, e.errno)
1477 self.assertEqual(desired_exception.strerror, e.strerror)
1478 else:
1479 self.fail("Expected OSError: %s" % desired_exception)
1480
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001481 def test_restore_signals(self):
1482 # Code coverage for both values of restore_signals to make sure it
1483 # at least does not blow up.
1484 # A test for behavior would be complex. Contributions welcome.
1485 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1486 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1487
1488 def test_start_new_session(self):
1489 # For code coverage of calling setsid(). We don't care if we get an
1490 # EPERM error from it depending on the test execution environment, that
1491 # still indicates that it was called.
1492 try:
1493 output = subprocess.check_output(
1494 [sys.executable, "-c",
1495 "import os; print(os.getpgid(os.getpid()))"],
1496 start_new_session=True)
1497 except OSError as e:
1498 if e.errno != errno.EPERM:
1499 raise
1500 else:
1501 parent_pgid = os.getpgid(os.getpid())
1502 child_pgid = int(output)
1503 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001504
1505 def test_run_abort(self):
1506 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001507 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001508 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001509 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001510 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001511 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001512
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001513 def test_CalledProcessError_str_signal(self):
1514 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
1515 error_string = str(err)
1516 # We're relying on the repr() of the signal.Signals intenum to provide
1517 # the word signal, the signal name and the numeric value.
1518 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00001519 # We're not being specific about the signal name as some signals have
1520 # multiple names and which name is revealed can vary.
1521 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001522 self.assertIn(str(signal.SIGABRT), error_string)
1523
1524 def test_CalledProcessError_str_unknown_signal(self):
1525 err = subprocess.CalledProcessError(-9876543, "fake cmd")
1526 error_string = str(err)
1527 self.assertIn("unknown signal 9876543.", error_string)
1528
1529 def test_CalledProcessError_str_non_zero(self):
1530 err = subprocess.CalledProcessError(2, "fake cmd")
1531 error_string = str(err)
1532 self.assertIn("non-zero exit status 2.", error_string)
1533
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001534 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001535 # DISCLAIMER: Setting environment variables is *not* a good use
1536 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001537 p = subprocess.Popen([sys.executable, "-c",
1538 'import sys,os;'
1539 'sys.stdout.write(os.getenv("FRUIT"))'],
1540 stdout=subprocess.PIPE,
1541 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02001542 with p:
1543 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001544
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001545 def test_preexec_exception(self):
1546 def raise_it():
1547 raise ValueError("What if two swallows carried a coconut?")
1548 try:
1549 p = subprocess.Popen([sys.executable, "-c", ""],
1550 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001551 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001552 self.assertTrue(
1553 subprocess._posixsubprocess,
1554 "Expected a ValueError from the preexec_fn")
1555 except ValueError as e:
1556 self.assertIn("coconut", e.args[0])
1557 else:
1558 self.fail("Exception raised by preexec_fn did not make it "
1559 "to the parent process.")
1560
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001561 class _TestExecuteChildPopen(subprocess.Popen):
1562 """Used to test behavior at the end of _execute_child."""
1563 def __init__(self, testcase, *args, **kwargs):
1564 self._testcase = testcase
1565 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001566
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001567 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001568 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001569 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001570 finally:
1571 # Open a bunch of file descriptors and verify that
1572 # none of them are the same as the ones the Popen
1573 # instance is using for stdin/stdout/stderr.
1574 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1575 for _ in range(8)]
1576 try:
1577 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001578 self._testcase.assertNotIn(
1579 fd, (self.stdin.fileno(), self.stdout.fileno(),
1580 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001581 msg="At least one fd was closed early.")
1582 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01001583 for fd in devzero_fds:
1584 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001585
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001586 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1587 def test_preexec_errpipe_does_not_double_close_pipes(self):
1588 """Issue16140: Don't double close pipes on preexec error."""
1589
1590 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08001591 raise subprocess.SubprocessError(
1592 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001593
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08001594 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001595 self._TestExecuteChildPopen(
1596 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001597 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1598 stderr=subprocess.PIPE, preexec_fn=raise_it)
1599
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001600 def test_preexec_gc_module_failure(self):
1601 # This tests the code that disables garbage collection if the child
1602 # process will execute any Python.
1603 def raise_runtime_error():
1604 raise RuntimeError("this shouldn't escape")
1605 enabled = gc.isenabled()
1606 orig_gc_disable = gc.disable
1607 orig_gc_isenabled = gc.isenabled
1608 try:
1609 gc.disable()
1610 self.assertFalse(gc.isenabled())
1611 subprocess.call([sys.executable, '-c', ''],
1612 preexec_fn=lambda: None)
1613 self.assertFalse(gc.isenabled(),
1614 "Popen enabled gc when it shouldn't.")
1615
1616 gc.enable()
1617 self.assertTrue(gc.isenabled())
1618 subprocess.call([sys.executable, '-c', ''],
1619 preexec_fn=lambda: None)
1620 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1621
1622 gc.disable = raise_runtime_error
1623 self.assertRaises(RuntimeError, subprocess.Popen,
1624 [sys.executable, '-c', ''],
1625 preexec_fn=lambda: None)
1626
1627 del gc.isenabled # force an AttributeError
1628 self.assertRaises(AttributeError, subprocess.Popen,
1629 [sys.executable, '-c', ''],
1630 preexec_fn=lambda: None)
1631 finally:
1632 gc.disable = orig_gc_disable
1633 gc.isenabled = orig_gc_isenabled
1634 if not enabled:
1635 gc.disable()
1636
Martin Panterf7fdbda2015-12-05 09:51:52 +00001637 @unittest.skipIf(
1638 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00001639 def test_preexec_fork_failure(self):
1640 # The internal code did not preserve the previous exception when
1641 # re-enabling garbage collection
1642 try:
1643 from resource import getrlimit, setrlimit, RLIMIT_NPROC
1644 except ImportError as err:
1645 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
1646 limits = getrlimit(RLIMIT_NPROC)
1647 [_, hard] = limits
1648 setrlimit(RLIMIT_NPROC, (0, hard))
1649 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00001650 try:
Martin Panterafdd5132015-11-30 02:21:41 +00001651 subprocess.call([sys.executable, '-c', ''],
1652 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00001653 except BlockingIOError:
1654 # Forking should raise EAGAIN, translated to BlockingIOError
1655 pass
1656 else:
1657 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00001658
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001659 def test_args_string(self):
1660 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03001661 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001662 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001663 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001664 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001665 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1666 sys.executable)
1667 os.chmod(fname, 0o700)
1668 p = subprocess.Popen(fname)
1669 p.wait()
1670 os.remove(fname)
1671 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001672
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001673 def test_invalid_args(self):
1674 # invalid arguments should raise ValueError
1675 self.assertRaises(ValueError, subprocess.call,
1676 [sys.executable, "-c",
1677 "import sys; sys.exit(47)"],
1678 startupinfo=47)
1679 self.assertRaises(ValueError, subprocess.call,
1680 [sys.executable, "-c",
1681 "import sys; sys.exit(47)"],
1682 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001683
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001684 def test_shell_sequence(self):
1685 # Run command through the shell (sequence)
1686 newenv = os.environ.copy()
1687 newenv["FRUIT"] = "apple"
1688 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1689 stdout=subprocess.PIPE,
1690 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001691 with p:
1692 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001693
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001694 def test_shell_string(self):
1695 # Run command through the shell (string)
1696 newenv = os.environ.copy()
1697 newenv["FRUIT"] = "apple"
1698 p = subprocess.Popen("echo $FRUIT", shell=1,
1699 stdout=subprocess.PIPE,
1700 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001701 with p:
1702 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001703
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001704 def test_call_string(self):
1705 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03001706 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001707 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001708 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001709 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001710 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1711 sys.executable)
1712 os.chmod(fname, 0o700)
1713 rc = subprocess.call(fname)
1714 os.remove(fname)
1715 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001716
Stefan Krah9542cc62010-07-19 14:20:53 +00001717 def test_specific_shell(self):
1718 # Issue #9265: Incorrect name passed as arg[0].
1719 shells = []
1720 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1721 for name in ['bash', 'ksh']:
1722 sh = os.path.join(prefix, name)
1723 if os.path.isfile(sh):
1724 shells.append(sh)
1725 if not shells: # Will probably work for any shell but csh.
1726 self.skipTest("bash or ksh required for this test")
1727 sh = '/bin/sh'
1728 if os.path.isfile(sh) and not os.path.islink(sh):
1729 # Test will fail if /bin/sh is a symlink to csh.
1730 shells.append(sh)
1731 for sh in shells:
1732 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1733 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02001734 with p:
1735 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00001736
Florent Xicluna4886d242010-03-08 13:27:26 +00001737 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001738 # Do not inherit file handles from the parent.
1739 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07001740 # Also set the SIGINT handler to the default to make sure it's not
1741 # being ignored (some tests rely on that.)
1742 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
1743 try:
1744 p = subprocess.Popen([sys.executable, "-c", """if 1:
1745 import sys, time
1746 sys.stdout.write('x\\n')
1747 sys.stdout.flush()
1748 time.sleep(30)
1749 """],
1750 close_fds=True,
1751 stdin=subprocess.PIPE,
1752 stdout=subprocess.PIPE,
1753 stderr=subprocess.PIPE)
1754 finally:
1755 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001756 # Wait for the interpreter to be completely initialized before
1757 # sending any signal.
1758 p.stdout.read(1)
1759 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001760 return p
1761
Charles-François Natali53221e32013-01-12 16:52:20 +01001762 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1763 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001764 def _kill_dead_process(self, method, *args):
1765 # Do not inherit file handles from the parent.
1766 # It should fix failures on some platforms.
1767 p = subprocess.Popen([sys.executable, "-c", """if 1:
1768 import sys, time
1769 sys.stdout.write('x\\n')
1770 sys.stdout.flush()
1771 """],
1772 close_fds=True,
1773 stdin=subprocess.PIPE,
1774 stdout=subprocess.PIPE,
1775 stderr=subprocess.PIPE)
1776 # Wait for the interpreter to be completely initialized before
1777 # sending any signal.
1778 p.stdout.read(1)
1779 # The process should end after this
1780 time.sleep(1)
1781 # This shouldn't raise even though the child is now dead
1782 getattr(p, method)(*args)
1783 p.communicate()
1784
Florent Xicluna4886d242010-03-08 13:27:26 +00001785 def test_send_signal(self):
1786 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001787 _, stderr = p.communicate()
1788 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001789 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001790
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001791 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001792 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001793 _, stderr = p.communicate()
1794 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001795 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001796
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001797 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001798 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001799 _, stderr = p.communicate()
1800 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001801 self.assertEqual(p.wait(), -signal.SIGTERM)
1802
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001803 def test_send_signal_dead(self):
1804 # Sending a signal to a dead process
1805 self._kill_dead_process('send_signal', signal.SIGINT)
1806
1807 def test_kill_dead(self):
1808 # Killing a dead process
1809 self._kill_dead_process('kill')
1810
1811 def test_terminate_dead(self):
1812 # Terminating a dead process
1813 self._kill_dead_process('terminate')
1814
Victor Stinnerdaf45552013-08-28 00:53:59 +02001815 def _save_fds(self, save_fds):
1816 fds = []
1817 for fd in save_fds:
1818 inheritable = os.get_inheritable(fd)
1819 saved = os.dup(fd)
1820 fds.append((fd, saved, inheritable))
1821 return fds
1822
1823 def _restore_fds(self, fds):
1824 for fd, saved, inheritable in fds:
1825 os.dup2(saved, fd, inheritable=inheritable)
1826 os.close(saved)
1827
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001828 def check_close_std_fds(self, fds):
1829 # Issue #9905: test that subprocess pipes still work properly with
1830 # some standard fds closed
1831 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02001832 saved_fds = self._save_fds(fds)
1833 for fd, saved, inheritable in saved_fds:
1834 if fd == 0:
1835 stdin = saved
1836 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001837 try:
1838 for fd in fds:
1839 os.close(fd)
1840 out, err = subprocess.Popen([sys.executable, "-c",
1841 'import sys;'
1842 'sys.stdout.write("apple");'
1843 'sys.stdout.flush();'
1844 'sys.stderr.write("orange")'],
1845 stdin=stdin,
1846 stdout=subprocess.PIPE,
1847 stderr=subprocess.PIPE).communicate()
1848 err = support.strip_python_stderr(err)
1849 self.assertEqual((out, err), (b'apple', b'orange'))
1850 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001851 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001852
1853 def test_close_fd_0(self):
1854 self.check_close_std_fds([0])
1855
1856 def test_close_fd_1(self):
1857 self.check_close_std_fds([1])
1858
1859 def test_close_fd_2(self):
1860 self.check_close_std_fds([2])
1861
1862 def test_close_fds_0_1(self):
1863 self.check_close_std_fds([0, 1])
1864
1865 def test_close_fds_0_2(self):
1866 self.check_close_std_fds([0, 2])
1867
1868 def test_close_fds_1_2(self):
1869 self.check_close_std_fds([1, 2])
1870
1871 def test_close_fds_0_1_2(self):
1872 # Issue #10806: test that subprocess pipes still work properly with
1873 # all standard fds closed.
1874 self.check_close_std_fds([0, 1, 2])
1875
Gregory P. Smith53dd8162013-12-01 16:03:24 -08001876 def test_small_errpipe_write_fd(self):
1877 """Issue #15798: Popen should work when stdio fds are available."""
1878 new_stdin = os.dup(0)
1879 new_stdout = os.dup(1)
1880 try:
1881 os.close(0)
1882 os.close(1)
1883
1884 # Side test: if errpipe_write fails to have its CLOEXEC
1885 # flag set this should cause the parent to think the exec
1886 # failed. Extremely unlikely: everyone supports CLOEXEC.
1887 subprocess.Popen([
1888 sys.executable, "-c",
1889 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
1890 finally:
1891 # Restore original stdin and stdout
1892 os.dup2(new_stdin, 0)
1893 os.dup2(new_stdout, 1)
1894 os.close(new_stdin)
1895 os.close(new_stdout)
1896
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001897 def test_remapping_std_fds(self):
1898 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03001899 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001900 try:
1901 temp_fds = [fd for fd, fname in temps]
1902
1903 # unlink the files -- we won't need to reopen them
1904 for fd, fname in temps:
1905 os.unlink(fname)
1906
1907 # write some data to what will become stdin, and rewind
1908 os.write(temp_fds[1], b"STDIN")
1909 os.lseek(temp_fds[1], 0, 0)
1910
1911 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02001912 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001913 try:
1914 # duplicate the file objects over the standard fd's
1915 for fd, temp_fd in enumerate(temp_fds):
1916 os.dup2(temp_fd, fd)
1917
1918 # now use those files in the "wrong" order, so that subprocess
1919 # has to rearrange them in the child
1920 p = subprocess.Popen([sys.executable, "-c",
1921 'import sys; got = sys.stdin.read();'
1922 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1923 stdin=temp_fds[1],
1924 stdout=temp_fds[2],
1925 stderr=temp_fds[0])
1926 p.wait()
1927 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001928 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001929
1930 for fd in temp_fds:
1931 os.lseek(fd, 0, 0)
1932
1933 out = os.read(temp_fds[2], 1024)
1934 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1935 self.assertEqual(out, b"got STDIN")
1936 self.assertEqual(err, b"err")
1937
1938 finally:
1939 for fd in temp_fds:
1940 os.close(fd)
1941
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001942 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1943 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03001944 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001945 temp_fds = [fd for fd, fname in temps]
1946 try:
1947 # unlink the files -- we won't need to reopen them
1948 for fd, fname in temps:
1949 os.unlink(fname)
1950
1951 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02001952 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001953 try:
1954 # duplicate the temp files over the standard fd's 0, 1, 2
1955 for fd, temp_fd in enumerate(temp_fds):
1956 os.dup2(temp_fd, fd)
1957
1958 # write some data to what will become stdin, and rewind
1959 os.write(stdin_no, b"STDIN")
1960 os.lseek(stdin_no, 0, 0)
1961
1962 # now use those files in the given order, so that subprocess
1963 # has to rearrange them in the child
1964 p = subprocess.Popen([sys.executable, "-c",
1965 'import sys; got = sys.stdin.read();'
1966 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1967 stdin=stdin_no,
1968 stdout=stdout_no,
1969 stderr=stderr_no)
1970 p.wait()
1971
1972 for fd in temp_fds:
1973 os.lseek(fd, 0, 0)
1974
1975 out = os.read(stdout_no, 1024)
1976 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1977 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001978 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001979
1980 self.assertEqual(out, b"got STDIN")
1981 self.assertEqual(err, b"err")
1982
1983 finally:
1984 for fd in temp_fds:
1985 os.close(fd)
1986
1987 # When duping fds, if there arises a situation where one of the fds is
1988 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1989 # This tests all combinations of this.
1990 def test_swap_fds(self):
1991 self.check_swap_fds(0, 1, 2)
1992 self.check_swap_fds(0, 2, 1)
1993 self.check_swap_fds(1, 0, 2)
1994 self.check_swap_fds(1, 2, 0)
1995 self.check_swap_fds(2, 0, 1)
1996 self.check_swap_fds(2, 1, 0)
1997
Victor Stinner13bb71c2010-04-23 21:41:56 +00001998 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001999 def prepare():
2000 raise ValueError("surrogate:\uDCff")
2001
2002 try:
2003 subprocess.call(
2004 [sys.executable, "-c", "pass"],
2005 preexec_fn=prepare)
2006 except ValueError as err:
2007 # Pure Python implementations keeps the message
2008 self.assertIsNone(subprocess._posixsubprocess)
2009 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002010 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00002011 # _posixsubprocess uses a default message
2012 self.assertIsNotNone(subprocess._posixsubprocess)
2013 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
2014 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002015 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00002016
Victor Stinner13bb71c2010-04-23 21:41:56 +00002017 def test_undecodable_env(self):
2018 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01002019 encoded_value = value.encode("ascii", "surrogateescape")
2020
Victor Stinner13bb71c2010-04-23 21:41:56 +00002021 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002022 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002023 env = os.environ.copy()
2024 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01002025 # Use C locale to get ASCII for the locale encoding to force
Victor Stinner89f3ad12010-10-14 10:43:31 +00002026 # surrogate-escaping of \xFF in the child process; otherwise it can
2027 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00002028 env['LC_ALL'] = 'C'
Victor Stinner5323fb02013-11-19 23:46:06 +01002029 if sys.platform.startswith("aix"):
2030 # On AIX, the C locale uses the Latin1 encoding
2031 decoded_value = encoded_value.decode("latin1", "surrogateescape")
2032 else:
2033 # On other UNIXes, the C locale uses the ASCII encoding
2034 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002035 stdout = subprocess.check_output(
2036 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002037 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002038 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002039 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002040
2041 # test bytes
2042 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002043 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002044 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01002045 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002046 stdout = subprocess.check_output(
2047 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002048 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002049 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002050 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002051
Victor Stinnerb745a742010-05-18 17:17:23 +00002052 def test_bytes_program(self):
2053 abs_program = os.fsencode(sys.executable)
2054 path, program = os.path.split(sys.executable)
2055 program = os.fsencode(program)
2056
2057 # absolute bytes path
2058 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00002059 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002060
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002061 # absolute bytes path as a string
2062 cmd = b"'" + abs_program + b"' -c pass"
2063 exitcode = subprocess.call(cmd, shell=True)
2064 self.assertEqual(exitcode, 0)
2065
Victor Stinnerb745a742010-05-18 17:17:23 +00002066 # bytes program, unicode PATH
2067 env = os.environ.copy()
2068 env["PATH"] = path
2069 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002070 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002071
2072 # bytes program, bytes PATH
2073 envb = os.environb.copy()
2074 envb[b"PATH"] = os.fsencode(path)
2075 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002076 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002077
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002078 def test_pipe_cloexec(self):
2079 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2080 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2081
2082 p1 = subprocess.Popen([sys.executable, sleeper],
2083 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2084 stderr=subprocess.PIPE, close_fds=False)
2085
2086 self.addCleanup(p1.communicate, b'')
2087
2088 p2 = subprocess.Popen([sys.executable, fd_status],
2089 stdout=subprocess.PIPE, close_fds=False)
2090
2091 output, error = p2.communicate()
2092 result_fds = set(map(int, output.split(b',')))
2093 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2094 p1.stderr.fileno()])
2095
2096 self.assertFalse(result_fds & unwanted_fds,
2097 "Expected no fds from %r to be open in child, "
2098 "found %r" %
2099 (unwanted_fds, result_fds & unwanted_fds))
2100
2101 def test_pipe_cloexec_real_tools(self):
2102 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2103 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2104
2105 subdata = b'zxcvbn'
2106 data = subdata * 4 + b'\n'
2107
2108 p1 = subprocess.Popen([sys.executable, qcat],
2109 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2110 close_fds=False)
2111
2112 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2113 stdin=p1.stdout, stdout=subprocess.PIPE,
2114 close_fds=False)
2115
2116 self.addCleanup(p1.wait)
2117 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002118 def kill_p1():
2119 try:
2120 p1.terminate()
2121 except ProcessLookupError:
2122 pass
2123 def kill_p2():
2124 try:
2125 p2.terminate()
2126 except ProcessLookupError:
2127 pass
2128 self.addCleanup(kill_p1)
2129 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002130
2131 p1.stdin.write(data)
2132 p1.stdin.close()
2133
2134 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2135
2136 self.assertTrue(readfiles, "The child hung")
2137 self.assertEqual(p2.stdout.read(), data)
2138
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002139 p1.stdout.close()
2140 p2.stdout.close()
2141
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002142 def test_close_fds(self):
2143 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2144
2145 fds = os.pipe()
2146 self.addCleanup(os.close, fds[0])
2147 self.addCleanup(os.close, fds[1])
2148
2149 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002150 # add a bunch more fds
2151 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002152 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002153 self.addCleanup(os.close, fd)
2154 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002155
Victor Stinnerdaf45552013-08-28 00:53:59 +02002156 for fd in open_fds:
2157 os.set_inheritable(fd, True)
2158
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002159 p = subprocess.Popen([sys.executable, fd_status],
2160 stdout=subprocess.PIPE, close_fds=False)
2161 output, ignored = p.communicate()
2162 remaining_fds = set(map(int, output.split(b',')))
2163
2164 self.assertEqual(remaining_fds & open_fds, open_fds,
2165 "Some fds were closed")
2166
2167 p = subprocess.Popen([sys.executable, fd_status],
2168 stdout=subprocess.PIPE, close_fds=True)
2169 output, ignored = p.communicate()
2170 remaining_fds = set(map(int, output.split(b',')))
2171
2172 self.assertFalse(remaining_fds & open_fds,
2173 "Some fds were left open")
2174 self.assertIn(1, remaining_fds, "Subprocess failed")
2175
Gregory P. Smith8facece2012-01-21 14:01:08 -08002176 # Keep some of the fd's we opened open in the subprocess.
2177 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2178 fds_to_keep = set(open_fds.pop() for _ in range(8))
2179 p = subprocess.Popen([sys.executable, fd_status],
2180 stdout=subprocess.PIPE, close_fds=True,
2181 pass_fds=())
2182 output, ignored = p.communicate()
2183 remaining_fds = set(map(int, output.split(b',')))
2184
2185 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
2186 "Some fds not in pass_fds were left open")
2187 self.assertIn(1, remaining_fds, "Subprocess failed")
2188
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002189
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002190 @unittest.skipIf(sys.platform.startswith("freebsd") and
2191 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2192 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002193 def test_close_fds_when_max_fd_is_lowered(self):
2194 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2195 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2196
Gregory P. Smith634aa682014-06-15 17:51:04 -07002197 # This launches the meat of the test in a child process to
2198 # avoid messing with the larger unittest processes maximum
2199 # number of file descriptors.
2200 # This process launches:
2201 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2202 # a bunch of high open fds above the new lower rlimit.
2203 # Those are reported via stdout before launching a new
2204 # process with close_fds=False to run the actual test:
2205 # +--> The TEST: This one launches a fd_status.py
2206 # subprocess with close_fds=True so we can find out if
2207 # any of the fds above the lowered rlimit are still open.
2208 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2209 '''
2210 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002211 open_fds = set()
2212 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002213 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002214 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002215 open_fds.add(fd)
2216
2217 # Leave a two pairs of low ones available for use by the
2218 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002219 # We also leave 10 more open as some Python buildbots run into
2220 # "too many open files" errors during the test if we do not.
2221 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002222 os.close(fd)
2223 open_fds.remove(fd)
2224
2225 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002226 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002227 os.set_inheritable(fd, True)
2228
2229 max_fd_open = max(open_fds)
2230
Gregory P. Smith634aa682014-06-15 17:51:04 -07002231 # Communicate the open_fds to the parent unittest.TestCase process.
2232 print(','.join(map(str, sorted(open_fds))))
2233 sys.stdout.flush()
2234
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002235 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2236 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002237 # 29 is lower than the highest fds we are leaving open.
2238 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002239 # Launch a new Python interpreter with our low fd rlim_cur that
2240 # inherits open fds above that limit. It then uses subprocess
2241 # with close_fds=True to get a report of open fds in the child.
2242 # An explicit list of fds to check is passed to fd_status.py as
2243 # letting fd_status rely on its default logic would miss the
2244 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002245 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002246 [sys.executable, '-c',
2247 textwrap.dedent("""
2248 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002249 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002250 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002251 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002252 """.format(max_fd=max_fd_open+1))],
2253 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002254 finally:
2255 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002256 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002257
2258 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002259 output_lines = output.splitlines()
2260 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002261 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002262 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2263 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002264
Gregory P. Smith634aa682014-06-15 17:51:04 -07002265 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002266 msg="Some fds were left open.")
2267
2268
Victor Stinner88701e22011-06-01 13:13:04 +02002269 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2270 # descriptor of a pipe closed in the parent process is valid in the
2271 # child process according to fstat(), but the mode of the file
2272 # descriptor is invalid, and read or write raise an error.
2273 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002274 def test_pass_fds(self):
2275 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2276
2277 open_fds = set()
2278
2279 for x in range(5):
2280 fds = os.pipe()
2281 self.addCleanup(os.close, fds[0])
2282 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002283 os.set_inheritable(fds[0], True)
2284 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002285 open_fds.update(fds)
2286
2287 for fd in open_fds:
2288 p = subprocess.Popen([sys.executable, fd_status],
2289 stdout=subprocess.PIPE, close_fds=True,
2290 pass_fds=(fd, ))
2291 output, ignored = p.communicate()
2292
2293 remaining_fds = set(map(int, output.split(b',')))
2294 to_be_closed = open_fds - {fd}
2295
2296 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2297 self.assertFalse(remaining_fds & to_be_closed,
2298 "fd to be closed passed")
2299
2300 # pass_fds overrides close_fds with a warning.
2301 with self.assertWarns(RuntimeWarning) as context:
2302 self.assertFalse(subprocess.call(
2303 [sys.executable, "-c", "import sys; sys.exit(0)"],
2304 close_fds=False, pass_fds=(fd, )))
2305 self.assertIn('overriding close_fds', str(context.warning))
2306
Victor Stinnerdaf45552013-08-28 00:53:59 +02002307 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002308 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002309
2310 inheritable, non_inheritable = os.pipe()
2311 self.addCleanup(os.close, inheritable)
2312 self.addCleanup(os.close, non_inheritable)
2313 os.set_inheritable(inheritable, True)
2314 os.set_inheritable(non_inheritable, False)
2315 pass_fds = (inheritable, non_inheritable)
2316 args = [sys.executable, script]
2317 args += list(map(str, pass_fds))
2318
2319 p = subprocess.Popen(args,
2320 stdout=subprocess.PIPE, close_fds=True,
2321 pass_fds=pass_fds)
2322 output, ignored = p.communicate()
2323 fds = set(map(int, output.split(b',')))
2324
2325 # the inheritable file descriptor must be inherited, so its inheritable
2326 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002327 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002328
2329 # inheritable flag must not be changed in the parent process
2330 self.assertEqual(os.get_inheritable(inheritable), True)
2331 self.assertEqual(os.get_inheritable(non_inheritable), False)
2332
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002333 def test_stdout_stdin_are_single_inout_fd(self):
2334 with io.open(os.devnull, "r+") as inout:
2335 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2336 stdout=inout, stdin=inout)
2337 p.wait()
2338
2339 def test_stdout_stderr_are_single_inout_fd(self):
2340 with io.open(os.devnull, "r+") as inout:
2341 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2342 stdout=inout, stderr=inout)
2343 p.wait()
2344
2345 def test_stderr_stdin_are_single_inout_fd(self):
2346 with io.open(os.devnull, "r+") as inout:
2347 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2348 stderr=inout, stdin=inout)
2349 p.wait()
2350
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002351 def test_wait_when_sigchild_ignored(self):
2352 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2353 sigchild_ignore = support.findfile("sigchild_ignore.py",
2354 subdir="subprocessdata")
2355 p = subprocess.Popen([sys.executable, sigchild_ignore],
2356 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2357 stdout, stderr = p.communicate()
2358 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002359 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002360 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002361
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002362 def test_select_unbuffered(self):
2363 # Issue #11459: bufsize=0 should really set the pipes as
2364 # unbuffered (and therefore let select() work properly).
2365 select = support.import_module("select")
2366 p = subprocess.Popen([sys.executable, "-c",
2367 'import sys;'
2368 'sys.stdout.write("apple")'],
2369 stdout=subprocess.PIPE,
2370 bufsize=0)
2371 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002372 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002373 try:
2374 self.assertEqual(f.read(4), b"appl")
2375 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2376 finally:
2377 p.wait()
2378
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002379 def test_zombie_fast_process_del(self):
2380 # Issue #12650: on Unix, if Popen.__del__() was called before the
2381 # process exited, it wouldn't be added to subprocess._active, and would
2382 # remain a zombie.
2383 # spawn a Popen, and delete its reference before it exits
2384 p = subprocess.Popen([sys.executable, "-c",
2385 'import sys, time;'
2386 'time.sleep(0.2)'],
2387 stdout=subprocess.PIPE,
2388 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002389 self.addCleanup(p.stdout.close)
2390 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002391 ident = id(p)
2392 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002393 with support.check_warnings(('', ResourceWarning)):
2394 p = None
2395
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002396 # check that p is in the active processes list
2397 self.assertIn(ident, [id(o) for o in subprocess._active])
2398
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002399 def test_leak_fast_process_del_killed(self):
2400 # Issue #12650: on Unix, if Popen.__del__() was called before the
2401 # process exited, and the process got killed by a signal, it would never
2402 # be removed from subprocess._active, which triggered a FD and memory
2403 # leak.
2404 # spawn a Popen, delete its reference and kill it
2405 p = subprocess.Popen([sys.executable, "-c",
2406 'import time;'
2407 'time.sleep(3)'],
2408 stdout=subprocess.PIPE,
2409 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002410 self.addCleanup(p.stdout.close)
2411 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002412 ident = id(p)
2413 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002414 with support.check_warnings(('', ResourceWarning)):
2415 p = None
2416
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002417 os.kill(pid, signal.SIGKILL)
2418 # check that p is in the active processes list
2419 self.assertIn(ident, [id(o) for o in subprocess._active])
2420
2421 # let some time for the process to exit, and create a new Popen: this
2422 # should trigger the wait() of p
2423 time.sleep(0.2)
Andrew Svetlov3438fa42012-12-17 23:35:18 +02002424 with self.assertRaises(OSError) as c:
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002425 with subprocess.Popen(['nonexisting_i_hope'],
2426 stdout=subprocess.PIPE,
2427 stderr=subprocess.PIPE) as proc:
2428 pass
2429 # p should have been wait()ed on, and removed from the _active list
2430 self.assertRaises(OSError, os.waitpid, pid, 0)
2431 self.assertNotIn(ident, [id(o) for o in subprocess._active])
2432
Charles-François Natali249cdc32013-08-25 18:24:45 +02002433 def test_close_fds_after_preexec(self):
2434 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2435
2436 # this FD is used as dup2() target by preexec_fn, and should be closed
2437 # in the child process
2438 fd = os.dup(1)
2439 self.addCleanup(os.close, fd)
2440
2441 p = subprocess.Popen([sys.executable, fd_status],
2442 stdout=subprocess.PIPE, close_fds=True,
2443 preexec_fn=lambda: os.dup2(1, fd))
2444 output, ignored = p.communicate()
2445
2446 remaining_fds = set(map(int, output.split(b',')))
2447
2448 self.assertNotIn(fd, remaining_fds)
2449
Victor Stinner8f437aa2014-10-05 17:25:19 +02002450 @support.cpython_only
2451 def test_fork_exec(self):
2452 # Issue #22290: fork_exec() must not crash on memory allocation failure
2453 # or other errors
2454 import _posixsubprocess
2455 gc_enabled = gc.isenabled()
2456 try:
2457 # Use a preexec function and enable the garbage collector
2458 # to force fork_exec() to re-enable the garbage collector
2459 # on error.
2460 func = lambda: None
2461 gc.enable()
2462
Victor Stinner8f437aa2014-10-05 17:25:19 +02002463 for args, exe_list, cwd, env_list in (
2464 (123, [b"exe"], None, [b"env"]),
2465 ([b"arg"], 123, None, [b"env"]),
2466 ([b"arg"], [b"exe"], 123, [b"env"]),
2467 ([b"arg"], [b"exe"], None, 123),
2468 ):
2469 with self.assertRaises(TypeError):
2470 _posixsubprocess.fork_exec(
2471 args, exe_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002472 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02002473 -1, -1, -1, -1,
2474 1, 2, 3, 4,
2475 True, True, func)
2476 finally:
2477 if not gc_enabled:
2478 gc.disable()
2479
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002480 @support.cpython_only
2481 def test_fork_exec_sorted_fd_sanity_check(self):
2482 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
2483 import _posixsubprocess
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002484 class BadInt:
2485 first = True
2486 def __init__(self, value):
2487 self.value = value
2488 def __int__(self):
2489 if self.first:
2490 self.first = False
2491 return self.value
2492 raise ValueError
2493
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002494 gc_enabled = gc.isenabled()
2495 try:
2496 gc.enable()
2497
2498 for fds_to_keep in (
2499 (-1, 2, 3, 4, 5), # Negative number.
2500 ('str', 4), # Not an int.
2501 (18, 23, 42, 2**63), # Out of range.
2502 (5, 4), # Not sorted.
2503 (6, 7, 7, 8), # Duplicate.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002504 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002505 ):
2506 with self.assertRaises(
2507 ValueError,
2508 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
2509 _posixsubprocess.fork_exec(
2510 [b"false"], [b"false"],
2511 True, fds_to_keep, None, [b"env"],
2512 -1, -1, -1, -1,
2513 1, 2, 3, 4,
2514 True, True, None)
2515 self.assertIn('fds_to_keep', str(c.exception))
2516 finally:
2517 if not gc_enabled:
2518 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02002519
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00002520 def test_communicate_BrokenPipeError_stdin_close(self):
2521 # By not setting stdout or stderr or a timeout we force the fast path
2522 # that just calls _stdin_write() internally due to our mock.
2523 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2524 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2525 mock_proc_stdin.close.side_effect = BrokenPipeError
2526 proc.communicate() # Should swallow BrokenPipeError from close.
2527 mock_proc_stdin.close.assert_called_with()
2528
2529 def test_communicate_BrokenPipeError_stdin_write(self):
2530 # By not setting stdout or stderr or a timeout we force the fast path
2531 # that just calls _stdin_write() internally due to our mock.
2532 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2533 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2534 mock_proc_stdin.write.side_effect = BrokenPipeError
2535 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
2536 mock_proc_stdin.write.assert_called_once_with(b'stuff')
2537 mock_proc_stdin.close.assert_called_once_with()
2538
2539 def test_communicate_BrokenPipeError_stdin_flush(self):
2540 # Setting stdin and stdout forces the ._communicate() code path.
2541 # python -h exits faster than python -c pass (but spams stdout).
2542 proc = subprocess.Popen([sys.executable, '-h'],
2543 stdin=subprocess.PIPE,
2544 stdout=subprocess.PIPE)
2545 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
2546 open(os.devnull, 'wb') as dev_null:
2547 mock_proc_stdin.flush.side_effect = BrokenPipeError
2548 # because _communicate registers a selector using proc.stdin...
2549 mock_proc_stdin.fileno.return_value = dev_null.fileno()
2550 # _communicate() should swallow BrokenPipeError from flush.
2551 proc.communicate(b'stuff')
2552 mock_proc_stdin.flush.assert_called_once_with()
2553
2554 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
2555 # Setting stdin and stdout forces the ._communicate() code path.
2556 # python -h exits faster than python -c pass (but spams stdout).
2557 proc = subprocess.Popen([sys.executable, '-h'],
2558 stdin=subprocess.PIPE,
2559 stdout=subprocess.PIPE)
2560 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2561 mock_proc_stdin.close.side_effect = BrokenPipeError
2562 # _communicate() should swallow BrokenPipeError from close.
2563 proc.communicate(timeout=999)
2564 mock_proc_stdin.close.assert_called_once_with()
2565
Victor Stinnercdee3f12017-06-26 17:23:03 +02002566 @unittest.skipIf(not ctypes, 'ctypes module required')
2567 @unittest.skipIf(not sys.executable, 'Test requires sys.executable')
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002568 def test_child_terminated_in_stopped_state(self):
2569 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
2570 PTRACE_TRACEME = 0 # From glibc and MacOS (PT_TRACE_ME).
Gregory P. Smith56bc3b72017-05-23 07:49:13 -07002571 libc_name = ctypes.util.find_library('c')
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002572 libc = ctypes.CDLL(libc_name)
2573 if not hasattr(libc, 'ptrace'):
Victor Stinnercdee3f12017-06-26 17:23:03 +02002574 raise unittest.SkipTest('ptrace() required')
2575
2576 code = textwrap.dedent(f"""
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002577 import ctypes
Victor Stinnercdee3f12017-06-26 17:23:03 +02002578 import faulthandler
2579 from test.support import SuppressCrashReport
2580
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002581 libc = ctypes.CDLL({libc_name!r})
2582 libc.ptrace({PTRACE_TRACEME}, 0, 0)
Victor Stinnercdee3f12017-06-26 17:23:03 +02002583 """)
2584
2585 child = subprocess.Popen([sys.executable, '-c', code])
2586 if child.wait() != 0:
2587 raise unittest.SkipTest('ptrace() failed - unable to test')
2588
2589 code += textwrap.dedent(f"""
2590 with SuppressCrashReport():
2591 # Crash the process
2592 faulthandler._sigsegv()
2593 """)
2594 child = subprocess.Popen([sys.executable, '-c', code])
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002595 try:
2596 returncode = child.wait()
Victor Stinnercdee3f12017-06-26 17:23:03 +02002597 except:
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002598 child.kill() # Clean up the hung stopped process.
Victor Stinnercdee3f12017-06-26 17:23:03 +02002599 raise
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002600 self.assertNotEqual(0, returncode)
2601 self.assertLess(returncode, 0) # signal death, likely SIGSEGV.
2602
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002603
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002604@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00002605class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002606
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002607 def test_startupinfo(self):
2608 # startupinfo argument
2609 # We uses hardcoded constants, because we do not want to
2610 # depend on win32all.
2611 STARTF_USESHOWWINDOW = 1
2612 SW_MAXIMIZE = 3
2613 startupinfo = subprocess.STARTUPINFO()
2614 startupinfo.dwFlags = STARTF_USESHOWWINDOW
2615 startupinfo.wShowWindow = SW_MAXIMIZE
2616 # Since Python is a console process, it won't be affected
2617 # by wShowWindow, but the argument should be silently
2618 # ignored
2619 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002620 startupinfo=startupinfo)
2621
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05302622 def test_startupinfo_keywords(self):
2623 # startupinfo argument
2624 # We use hardcoded constants, because we do not want to
2625 # depend on win32all.
2626 STARTF_USERSHOWWINDOW = 1
2627 SW_MAXIMIZE = 3
2628 startupinfo = subprocess.STARTUPINFO(
2629 dwFlags=STARTF_USERSHOWWINDOW,
2630 wShowWindow=SW_MAXIMIZE
2631 )
2632 # Since Python is a console process, it won't be affected
2633 # by wShowWindow, but the argument should be silently
2634 # ignored
2635 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
2636 startupinfo=startupinfo)
2637
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002638 def test_creationflags(self):
2639 # creationflags argument
2640 CREATE_NEW_CONSOLE = 16
2641 sys.stderr.write(" a DOS box should flash briefly ...\n")
2642 subprocess.call(sys.executable +
2643 ' -c "import time; time.sleep(0.25)"',
2644 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002645
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002646 def test_invalid_args(self):
2647 # invalid arguments should raise ValueError
2648 self.assertRaises(ValueError, subprocess.call,
2649 [sys.executable, "-c",
2650 "import sys; sys.exit(47)"],
2651 preexec_fn=lambda: 1)
2652 self.assertRaises(ValueError, subprocess.call,
2653 [sys.executable, "-c",
2654 "import sys; sys.exit(47)"],
2655 stdout=subprocess.PIPE,
2656 close_fds=True)
2657
2658 def test_close_fds(self):
2659 # close file descriptors
2660 rc = subprocess.call([sys.executable, "-c",
2661 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002662 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002663 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002664
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002665 def test_shell_sequence(self):
2666 # Run command through the shell (sequence)
2667 newenv = os.environ.copy()
2668 newenv["FRUIT"] = "physalis"
2669 p = subprocess.Popen(["set"], shell=1,
2670 stdout=subprocess.PIPE,
2671 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002672 with p:
2673 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00002674
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002675 def test_shell_string(self):
2676 # Run command through the shell (string)
2677 newenv = os.environ.copy()
2678 newenv["FRUIT"] = "physalis"
2679 p = subprocess.Popen("set", shell=1,
2680 stdout=subprocess.PIPE,
2681 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002682 with p:
2683 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002684
Steve Dower050acae2016-09-06 20:16:17 -07002685 def test_shell_encodings(self):
2686 # Run command through the shell (string)
2687 for enc in ['ansi', 'oem']:
2688 newenv = os.environ.copy()
2689 newenv["FRUIT"] = "physalis"
2690 p = subprocess.Popen("set", shell=1,
2691 stdout=subprocess.PIPE,
2692 env=newenv,
2693 encoding=enc)
2694 with p:
2695 self.assertIn("physalis", p.stdout.read(), enc)
2696
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002697 def test_call_string(self):
2698 # call() function with string argument on Windows
2699 rc = subprocess.call(sys.executable +
2700 ' -c "import sys; sys.exit(47)"')
2701 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002702
Florent Xicluna4886d242010-03-08 13:27:26 +00002703 def _kill_process(self, method, *args):
2704 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00002705 p = subprocess.Popen([sys.executable, "-c", """if 1:
2706 import sys, time
2707 sys.stdout.write('x\\n')
2708 sys.stdout.flush()
2709 time.sleep(30)
2710 """],
2711 stdin=subprocess.PIPE,
2712 stdout=subprocess.PIPE,
2713 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002714 with p:
2715 # Wait for the interpreter to be completely initialized before
2716 # sending any signal.
2717 p.stdout.read(1)
2718 getattr(p, method)(*args)
2719 _, stderr = p.communicate()
2720 self.assertStderrEqual(stderr, b'')
2721 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00002722 self.assertNotEqual(returncode, 0)
2723
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002724 def _kill_dead_process(self, method, *args):
2725 p = subprocess.Popen([sys.executable, "-c", """if 1:
2726 import sys, time
2727 sys.stdout.write('x\\n')
2728 sys.stdout.flush()
2729 sys.exit(42)
2730 """],
2731 stdin=subprocess.PIPE,
2732 stdout=subprocess.PIPE,
2733 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002734 with p:
2735 # Wait for the interpreter to be completely initialized before
2736 # sending any signal.
2737 p.stdout.read(1)
2738 # The process should end after this
2739 time.sleep(1)
2740 # This shouldn't raise even though the child is now dead
2741 getattr(p, method)(*args)
2742 _, stderr = p.communicate()
2743 self.assertStderrEqual(stderr, b'')
2744 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002745 self.assertEqual(rc, 42)
2746
Florent Xicluna4886d242010-03-08 13:27:26 +00002747 def test_send_signal(self):
2748 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00002749
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002750 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002751 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00002752
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002753 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002754 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00002755
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002756 def test_send_signal_dead(self):
2757 self._kill_dead_process('send_signal', signal.SIGTERM)
2758
2759 def test_kill_dead(self):
2760 self._kill_dead_process('kill')
2761
2762 def test_terminate_dead(self):
2763 self._kill_dead_process('terminate')
2764
Martin Panter23172bd2016-04-16 11:28:10 +00002765class MiscTests(unittest.TestCase):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002766 def test_getoutput(self):
2767 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
2768 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
2769 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00002770
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002771 # we use mkdtemp in the next line to create an empty directory
2772 # under our exclusive control; from that, we can invent a pathname
2773 # that we _know_ won't exist. This is guaranteed to fail.
2774 dir = None
2775 try:
2776 dir = tempfile.mkdtemp()
2777 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00002778 status, output = subprocess.getstatusoutput(
2779 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002780 self.assertNotEqual(status, 0)
2781 finally:
2782 if dir is not None:
2783 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00002784
Gregory P. Smithace55862015-04-07 15:57:54 -07002785 def test__all__(self):
2786 """Ensure that __all__ is populated properly."""
Martin Panter528619b2016-04-16 23:42:37 +00002787 intentionally_excluded = {"list2cmdline", "Handle"}
Gregory P. Smithace55862015-04-07 15:57:54 -07002788 exported = set(subprocess.__all__)
2789 possible_exports = set()
2790 import types
2791 for name, value in subprocess.__dict__.items():
2792 if name.startswith('_'):
2793 continue
2794 if isinstance(value, (types.ModuleType,)):
2795 continue
2796 possible_exports.add(name)
2797 self.assertEqual(exported, possible_exports - intentionally_excluded)
2798
2799
Martin Panter23172bd2016-04-16 11:28:10 +00002800@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
2801 "Test needs selectors.PollSelector")
2802class ProcessTestCaseNoPoll(ProcessTestCase):
2803 def setUp(self):
2804 self.orig_selector = subprocess._PopenSelector
2805 subprocess._PopenSelector = selectors.SelectSelector
2806 ProcessTestCase.setUp(self)
2807
2808 def tearDown(self):
2809 subprocess._PopenSelector = self.orig_selector
2810 ProcessTestCase.tearDown(self)
2811
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002812
Tim Golden126c2962010-08-11 14:20:40 +00002813@unittest.skipUnless(mswindows, "Windows-specific tests")
2814class CommandsWithSpaces (BaseTestCase):
2815
2816 def setUp(self):
2817 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03002818 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00002819 self.fname = fname.lower ()
2820 os.write(f, b"import sys;"
2821 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
2822 )
2823 os.close(f)
2824
2825 def tearDown(self):
2826 os.remove(self.fname)
2827 super().tearDown()
2828
2829 def with_spaces(self, *args, **kwargs):
2830 kwargs['stdout'] = subprocess.PIPE
2831 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02002832 with p:
2833 self.assertEqual(
2834 p.stdout.read ().decode("mbcs"),
2835 "2 [%r, 'ab cd']" % self.fname
2836 )
Tim Golden126c2962010-08-11 14:20:40 +00002837
2838 def test_shell_string_with_spaces(self):
2839 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002840 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2841 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002842
2843 def test_shell_sequence_with_spaces(self):
2844 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002845 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002846
2847 def test_noshell_string_with_spaces(self):
2848 # call() function with string argument with spaces on Windows
2849 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2850 "ab cd"))
2851
2852 def test_noshell_sequence_with_spaces(self):
2853 # call() function with sequence argument with spaces on Windows
2854 self.with_spaces([sys.executable, self.fname, "ab cd"])
2855
Brian Curtin79cdb662010-12-03 02:46:02 +00002856
Georg Brandla86b2622012-02-20 21:34:57 +01002857class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00002858
2859 def test_pipe(self):
2860 with subprocess.Popen([sys.executable, "-c",
2861 "import sys;"
2862 "sys.stdout.write('stdout');"
2863 "sys.stderr.write('stderr');"],
2864 stdout=subprocess.PIPE,
2865 stderr=subprocess.PIPE) as proc:
2866 self.assertEqual(proc.stdout.read(), b"stdout")
2867 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2868
2869 self.assertTrue(proc.stdout.closed)
2870 self.assertTrue(proc.stderr.closed)
2871
2872 def test_returncode(self):
2873 with subprocess.Popen([sys.executable, "-c",
2874 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002875 pass
2876 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002877 self.assertEqual(proc.returncode, 100)
2878
2879 def test_communicate_stdin(self):
2880 with subprocess.Popen([sys.executable, "-c",
2881 "import sys;"
2882 "sys.exit(sys.stdin.read() == 'context')"],
2883 stdin=subprocess.PIPE) as proc:
2884 proc.communicate(b"context")
2885 self.assertEqual(proc.returncode, 1)
2886
2887 def test_invalid_args(self):
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +01002888 with self.assertRaises((FileNotFoundError, PermissionError)) as c:
Brian Curtin79cdb662010-12-03 02:46:02 +00002889 with subprocess.Popen(['nonexisting_i_hope'],
2890 stdout=subprocess.PIPE,
2891 stderr=subprocess.PIPE) as proc:
2892 pass
2893
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002894 def test_broken_pipe_cleanup(self):
2895 """Broken pipe error should not prevent wait() (Issue 21619)"""
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002896 proc = subprocess.Popen([sys.executable, '-c', 'pass'],
Victor Stinner20f4bd42015-03-05 02:38:41 +01002897 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01002898 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002899 proc = proc.__enter__()
2900 # Prepare to send enough data to overflow any OS pipe buffering and
2901 # guarantee a broken pipe error. Data is held in BufferedWriter
2902 # buffer until closed.
2903 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002904 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002905 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02002906 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002907 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002908 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002909
Brian Curtin79cdb662010-12-03 02:46:02 +00002910
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002911if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002912 unittest.main()