blob: be9e7834d9b368a5cf5f8dd4c643c19bed54b3d6 [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')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200633 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200634 'the python library cannot be loaded '
635 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200636 def test_empty_env(self):
637 with subprocess.Popen([sys.executable, "-c",
638 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200639 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200640 stdout=subprocess.PIPE,
641 env={}) as p:
642 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200643 self.assertIn(stdout.strip(),
644 (b"[]",
645 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
646 # environment
647 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000648
Peter Astrandcbac93c2005-03-03 20:24:28 +0000649 def test_communicate_stdin(self):
650 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000651 'import sys;'
652 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000653 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000654 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000655 self.assertEqual(p.returncode, 1)
656
657 def test_communicate_stdout(self):
658 p = subprocess.Popen([sys.executable, "-c",
659 'import sys; sys.stdout.write("pineapple")'],
660 stdout=subprocess.PIPE)
661 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000662 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000663 self.assertEqual(stderr, None)
664
665 def test_communicate_stderr(self):
666 p = subprocess.Popen([sys.executable, "-c",
667 'import sys; sys.stderr.write("pineapple")'],
668 stderr=subprocess.PIPE)
669 (stdout, stderr) = p.communicate()
670 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000671 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000672
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000673 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000674 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000675 'import sys,os;'
676 'sys.stderr.write("pineapple");'
677 'sys.stdout.write(sys.stdin.read())'],
678 stdin=subprocess.PIPE,
679 stdout=subprocess.PIPE,
680 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000681 self.addCleanup(p.stdout.close)
682 self.addCleanup(p.stderr.close)
683 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000684 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000685 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000686 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000687
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400688 def test_communicate_timeout(self):
689 p = subprocess.Popen([sys.executable, "-c",
690 'import sys,os,time;'
691 'sys.stderr.write("pineapple\\n");'
692 'time.sleep(1);'
693 'sys.stderr.write("pear\\n");'
694 'sys.stdout.write(sys.stdin.read())'],
695 universal_newlines=True,
696 stdin=subprocess.PIPE,
697 stdout=subprocess.PIPE,
698 stderr=subprocess.PIPE)
699 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
700 timeout=0.3)
701 # Make sure we can keep waiting for it, and that we get the whole output
702 # after it completes.
703 (stdout, stderr) = p.communicate()
704 self.assertEqual(stdout, "banana")
705 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
706
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700707 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200708 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400709 p = subprocess.Popen([sys.executable, "-c",
710 'import sys,os,time;'
711 'sys.stdout.write("a" * (64 * 1024));'
712 'time.sleep(0.2);'
713 'sys.stdout.write("a" * (64 * 1024));'
714 'time.sleep(0.2);'
715 'sys.stdout.write("a" * (64 * 1024));'
716 'time.sleep(0.2);'
717 'sys.stdout.write("a" * (64 * 1024));'],
718 stdout=subprocess.PIPE)
719 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
720 (stdout, _) = p.communicate()
721 self.assertEqual(len(stdout), 4 * 64 * 1024)
722
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000723 # Test for the fd leak reported in http://bugs.python.org/issue2791.
724 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000725 for stdin_pipe in (False, True):
726 for stdout_pipe in (False, True):
727 for stderr_pipe in (False, True):
728 options = {}
729 if stdin_pipe:
730 options['stdin'] = subprocess.PIPE
731 if stdout_pipe:
732 options['stdout'] = subprocess.PIPE
733 if stderr_pipe:
734 options['stderr'] = subprocess.PIPE
735 if not options:
736 continue
737 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
738 p.communicate()
739 if p.stdin is not None:
740 self.assertTrue(p.stdin.closed)
741 if p.stdout is not None:
742 self.assertTrue(p.stdout.closed)
743 if p.stderr is not None:
744 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000745
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000746 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000747 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000748 p = subprocess.Popen([sys.executable, "-c",
749 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000750 (stdout, stderr) = p.communicate()
751 self.assertEqual(stdout, None)
752 self.assertEqual(stderr, None)
753
754 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000755 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000756 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000757 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000758 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000759 os.close(x)
760 os.close(y)
761 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000762 'import sys,os;'
763 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200764 'sys.stderr.write("x" * %d);'
765 'sys.stdout.write(sys.stdin.read())' %
766 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000767 stdin=subprocess.PIPE,
768 stdout=subprocess.PIPE,
769 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000770 self.addCleanup(p.stdout.close)
771 self.addCleanup(p.stderr.close)
772 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200773 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000774 (stdout, stderr) = p.communicate(string_to_write)
775 self.assertEqual(stdout, string_to_write)
776
777 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000778 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000779 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000780 'import sys,os;'
781 'sys.stdout.write(sys.stdin.read())'],
782 stdin=subprocess.PIPE,
783 stdout=subprocess.PIPE,
784 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000785 self.addCleanup(p.stdout.close)
786 self.addCleanup(p.stderr.close)
787 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000788 p.stdin.write(b"banana")
789 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000790 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000791 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000792
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000793 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000794 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000795 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200796 'buf = sys.stdout.buffer;'
797 'buf.write(sys.stdin.readline().encode());'
798 'buf.flush();'
799 'buf.write(b"line2\\n");'
800 'buf.flush();'
801 'buf.write(sys.stdin.read().encode());'
802 'buf.flush();'
803 'buf.write(b"line4\\n");'
804 'buf.flush();'
805 'buf.write(b"line5\\r\\n");'
806 'buf.flush();'
807 'buf.write(b"line6\\r");'
808 'buf.flush();'
809 'buf.write(b"\\nline7");'
810 'buf.flush();'
811 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200812 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000813 stdout=subprocess.PIPE,
814 universal_newlines=1)
Victor Stinner7438c612016-05-20 12:43:15 +0200815 with p:
816 p.stdin.write("line1\n")
817 p.stdin.flush()
818 self.assertEqual(p.stdout.readline(), "line1\n")
819 p.stdin.write("line3\n")
820 p.stdin.close()
821 self.addCleanup(p.stdout.close)
822 self.assertEqual(p.stdout.readline(),
823 "line2\n")
824 self.assertEqual(p.stdout.read(6),
825 "line3\n")
826 self.assertEqual(p.stdout.read(),
827 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000828
829 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000830 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000831 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000832 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200833 'buf = sys.stdout.buffer;'
834 'buf.write(b"line2\\n");'
835 'buf.flush();'
836 'buf.write(b"line4\\n");'
837 'buf.flush();'
838 'buf.write(b"line5\\r\\n");'
839 'buf.flush();'
840 'buf.write(b"line6\\r");'
841 'buf.flush();'
842 'buf.write(b"\\nline7");'
843 'buf.flush();'
844 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200845 stderr=subprocess.PIPE,
846 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000847 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000848 self.addCleanup(p.stdout.close)
849 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000850 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200851 self.assertEqual(stdout,
852 "line2\nline4\nline5\nline6\nline7\nline8")
853
854 def test_universal_newlines_communicate_stdin(self):
855 # universal newlines through communicate(), with only stdin
856 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300857 'import sys,os;' + SETBINARY + textwrap.dedent('''
858 s = sys.stdin.readline()
859 assert s == "line1\\n", repr(s)
860 s = sys.stdin.read()
861 assert s == "line3\\n", repr(s)
862 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200863 stdin=subprocess.PIPE,
864 universal_newlines=1)
865 (stdout, stderr) = p.communicate("line1\nline3\n")
866 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000867
Andrew Svetlovf3765072012-08-14 18:35:17 +0300868 def test_universal_newlines_communicate_input_none(self):
869 # Test communicate(input=None) with universal newlines.
870 #
871 # We set stdout to PIPE because, as of this writing, a different
872 # code path is tested when the number of pipes is zero or one.
873 p = subprocess.Popen([sys.executable, "-c", "pass"],
874 stdin=subprocess.PIPE,
875 stdout=subprocess.PIPE,
876 universal_newlines=True)
877 p.communicate()
878 self.assertEqual(p.returncode, 0)
879
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300880 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300881 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300882 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300883 'import sys,os;' + SETBINARY + textwrap.dedent('''
884 s = sys.stdin.buffer.readline()
885 sys.stdout.buffer.write(s)
886 sys.stdout.buffer.write(b"line2\\r")
887 sys.stderr.buffer.write(b"eline2\\n")
888 s = sys.stdin.buffer.read()
889 sys.stdout.buffer.write(s)
890 sys.stdout.buffer.write(b"line4\\n")
891 sys.stdout.buffer.write(b"line5\\r\\n")
892 sys.stderr.buffer.write(b"eline6\\r")
893 sys.stderr.buffer.write(b"eline7\\r\\nz")
894 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300895 stdin=subprocess.PIPE,
896 stderr=subprocess.PIPE,
897 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300898 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300899 self.addCleanup(p.stdout.close)
900 self.addCleanup(p.stderr.close)
901 (stdout, stderr) = p.communicate("line1\nline3\n")
902 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300903 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300904 # Python debug build push something like "[42442 refs]\n"
905 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300906 # Don't use assertStderrEqual because it strips CR and LF from output.
907 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300908
Andrew Svetlov82860712012-08-19 22:13:41 +0300909 def test_universal_newlines_communicate_encodings(self):
910 # Check that universal newlines mode works for various encodings,
911 # in particular for encodings in the UTF-16 and UTF-32 families.
912 # See issue #15595.
913 #
914 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
915 # without, and UTF-16 and UTF-32.
916 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +0300917 code = ("import sys; "
918 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
919 encoding)
920 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -0700921 # We set stdin to be non-None because, as of this writing,
922 # a different code path is used when the number of pipes is
923 # zero or one.
924 popen = subprocess.Popen(args,
925 stdin=subprocess.PIPE,
926 stdout=subprocess.PIPE,
927 encoding=encoding)
928 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +0300929 self.assertEqual(stdout, '1\n2\n3\n4')
930
Steve Dower050acae2016-09-06 20:16:17 -0700931 def test_communicate_errors(self):
932 for errors, expected in [
933 ('ignore', ''),
934 ('replace', '\ufffd\ufffd'),
935 ('surrogateescape', '\udc80\udc80'),
936 ('backslashreplace', '\\x80\\x80'),
937 ]:
938 code = ("import sys; "
939 r"sys.stdout.buffer.write(b'[\x80\x80]')")
940 args = [sys.executable, '-c', code]
941 # We set stdin to be non-None because, as of this writing,
942 # a different code path is used when the number of pipes is
943 # zero or one.
944 popen = subprocess.Popen(args,
945 stdin=subprocess.PIPE,
946 stdout=subprocess.PIPE,
947 encoding='utf-8',
948 errors=errors)
949 stdout, stderr = popen.communicate(input='')
950 self.assertEqual(stdout, '[{}]'.format(expected))
951
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000952 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000953 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000954 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000955 max_handles = 1026 # too much for most UNIX systems
956 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000957 max_handles = 2050 # too much for (at least some) Windows setups
958 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400959 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000960 try:
961 for i in range(max_handles):
962 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400963 tmpfile = os.path.join(tmpdir, support.TESTFN)
964 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000965 except OSError as e:
966 if e.errno != errno.EMFILE:
967 raise
968 break
969 else:
970 self.skipTest("failed to reach the file descriptor limit "
971 "(tried %d)" % max_handles)
972 # Close a couple of them (should be enough for a subprocess)
973 for i in range(10):
974 os.close(handles.pop())
975 # Loop creating some subprocesses. If one of them leaks some fds,
976 # the next loop iteration will fail by reaching the max fd limit.
977 for i in range(15):
978 p = subprocess.Popen([sys.executable, "-c",
979 "import sys;"
980 "sys.stdout.write(sys.stdin.read())"],
981 stdin=subprocess.PIPE,
982 stdout=subprocess.PIPE,
983 stderr=subprocess.PIPE)
984 data = p.communicate(b"lime")[0]
985 self.assertEqual(data, b"lime")
986 finally:
987 for h in handles:
988 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400989 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000990
991 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000992 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
993 '"a b c" d e')
994 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
995 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000996 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
997 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000998 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
999 'a\\\\\\b "de fg" h')
1000 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
1001 'a\\\\\\"b c d')
1002 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
1003 '"a\\\\b c" d e')
1004 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
1005 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001006 self.assertEqual(subprocess.list2cmdline(['ab', '']),
1007 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001008
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001009 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001010 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +02001011 "import os; os.read(0, 1)"],
1012 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001013 self.addCleanup(p.stdin.close)
1014 self.assertIsNone(p.poll())
1015 os.write(p.stdin.fileno(), b'A')
1016 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001017 # Subsequent invocations should just return the returncode
1018 self.assertEqual(p.poll(), 0)
1019
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001020 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001021 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001022 self.assertEqual(p.wait(), 0)
1023 # Subsequent invocations should just return the returncode
1024 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001025
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001026 def test_wait_timeout(self):
1027 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001028 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001029 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001030 p.wait(timeout=0.0001)
1031 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -04001032 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
1033 # time to start.
1034 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001035
Peter Astrand738131d2004-11-30 21:04:45 +00001036 def test_invalid_bufsize(self):
1037 # an invalid type of the bufsize argument should raise
1038 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001039 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +00001040 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001041
Guido van Rossum46a05a72007-06-07 21:56:45 +00001042 def test_bufsize_is_none(self):
1043 # bufsize=None should be the same as bufsize=0.
1044 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
1045 self.assertEqual(p.wait(), 0)
1046 # Again with keyword arg
1047 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
1048 self.assertEqual(p.wait(), 0)
1049
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001050 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1051 # subprocess may deadlock with bufsize=1, see issue #21332
1052 with subprocess.Popen([sys.executable, "-c", "import sys;"
1053 "sys.stdout.write(sys.stdin.readline());"
1054 "sys.stdout.flush()"],
1055 stdin=subprocess.PIPE,
1056 stdout=subprocess.PIPE,
1057 stderr=subprocess.DEVNULL,
1058 bufsize=1,
1059 universal_newlines=universal_newlines) as p:
1060 p.stdin.write(line) # expect that it flushes the line in text mode
1061 os.close(p.stdin.fileno()) # close it without flushing the buffer
1062 read_line = p.stdout.readline()
1063 try:
1064 p.stdin.close()
1065 except OSError:
1066 pass
1067 p.stdin = None
1068 self.assertEqual(p.returncode, 0)
1069 self.assertEqual(read_line, expected)
1070
1071 def test_bufsize_equal_one_text_mode(self):
1072 # line is flushed in text mode with bufsize=1.
1073 # we should get the full line in return
1074 line = "line\n"
1075 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1076
1077 def test_bufsize_equal_one_binary_mode(self):
1078 # line is not flushed in binary mode with bufsize=1.
1079 # we should get empty response
1080 line = b'line' + os.linesep.encode() # assume ascii-based locale
1081 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
1082
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001083 def test_leaking_fds_on_error(self):
1084 # see bug #5179: Popen leaks file descriptors to PIPEs if
1085 # the child fails to execute; this will eventually exhaust
1086 # the maximum number of open fds. 1024 seems a very common
1087 # value for that limit, but Windows has 2048, so we loop
1088 # 1024 times (each call leaked two fds).
1089 for i in range(1024):
Andrew Svetlov3438fa42012-12-17 23:35:18 +02001090 with self.assertRaises(OSError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001091 subprocess.Popen(['nonexisting_i_hope'],
1092 stdout=subprocess.PIPE,
1093 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -04001094 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -04001095 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001096 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001097
Antoine Pitroua8392712013-08-30 23:38:13 +02001098 @unittest.skipIf(threading is None, "threading required")
1099 def test_double_close_on_error(self):
1100 # Issue #18851
1101 fds = []
1102 def open_fds():
1103 for i in range(20):
1104 fds.extend(os.pipe())
1105 time.sleep(0.001)
1106 t = threading.Thread(target=open_fds)
1107 t.start()
1108 try:
1109 with self.assertRaises(EnvironmentError):
1110 subprocess.Popen(['nonexisting_i_hope'],
1111 stdin=subprocess.PIPE,
1112 stdout=subprocess.PIPE,
1113 stderr=subprocess.PIPE)
1114 finally:
1115 t.join()
1116 exc = None
1117 for fd in fds:
1118 # If a double close occurred, some of those fds will
1119 # already have been closed by mistake, and os.close()
1120 # here will raise.
1121 try:
1122 os.close(fd)
1123 except OSError as e:
1124 exc = e
1125 if exc is not None:
1126 raise exc
1127
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001128 @unittest.skipIf(threading is None, "threading required")
1129 def test_threadsafe_wait(self):
1130 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1131 proc = subprocess.Popen([sys.executable, '-c',
1132 'import time; time.sleep(12)'])
1133 self.assertEqual(proc.returncode, None)
1134 results = []
1135
1136 def kill_proc_timer_thread():
1137 results.append(('thread-start-poll-result', proc.poll()))
1138 # terminate it from the thread and wait for the result.
1139 proc.kill()
1140 proc.wait()
1141 results.append(('thread-after-kill-and-wait', proc.returncode))
1142 # this wait should be a no-op given the above.
1143 proc.wait()
1144 results.append(('thread-after-second-wait', proc.returncode))
1145
1146 # This is a timing sensitive test, the failure mode is
1147 # triggered when both the main thread and this thread are in
1148 # the wait() call at once. The delay here is to allow the
1149 # main thread to most likely be blocked in its wait() call.
1150 t = threading.Timer(0.2, kill_proc_timer_thread)
1151 t.start()
1152
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001153 if mswindows:
1154 expected_errorcode = 1
1155 else:
1156 # Should be -9 because of the proc.kill() from the thread.
1157 expected_errorcode = -9
1158
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001159 # Wait for the process to finish; the thread should kill it
1160 # long before it finishes on its own. Supplying a timeout
1161 # triggers a different code path for better coverage.
1162 proc.wait(timeout=20)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001163 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001164 msg="unexpected result in wait from main thread")
1165
1166 # This should be a no-op with no change in returncode.
1167 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001168 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001169 msg="unexpected result in second main wait.")
1170
1171 t.join()
1172 # Ensure that all of the thread results are as expected.
1173 # When a race condition occurs in wait(), the returncode could
1174 # be set by the wrong thread that doesn't actually have it
1175 # leading to an incorrect value.
1176 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001177 ('thread-after-kill-and-wait', expected_errorcode),
1178 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001179 results)
1180
Victor Stinnerb3693582010-05-21 20:13:12 +00001181 def test_issue8780(self):
1182 # Ensure that stdout is inherited from the parent
1183 # if stdout=PIPE is not used
1184 code = ';'.join((
1185 'import subprocess, sys',
1186 'retcode = subprocess.call('
1187 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1188 'assert retcode == 0'))
1189 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001190 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001191
Tim Goldenaf5ac392010-08-06 13:03:56 +00001192 def test_handles_closed_on_exception(self):
1193 # If CreateProcess exits with an error, ensure the
1194 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001195 ifhandle, ifname = tempfile.mkstemp()
1196 ofhandle, ofname = tempfile.mkstemp()
1197 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001198 try:
1199 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1200 stderr=efhandle)
1201 except OSError:
1202 os.close(ifhandle)
1203 os.remove(ifname)
1204 os.close(ofhandle)
1205 os.remove(ofname)
1206 os.close(efhandle)
1207 os.remove(efname)
1208 self.assertFalse(os.path.exists(ifname))
1209 self.assertFalse(os.path.exists(ofname))
1210 self.assertFalse(os.path.exists(efname))
1211
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001212 def test_communicate_epipe(self):
1213 # Issue 10963: communicate() should hide EPIPE
1214 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1215 stdin=subprocess.PIPE,
1216 stdout=subprocess.PIPE,
1217 stderr=subprocess.PIPE)
1218 self.addCleanup(p.stdout.close)
1219 self.addCleanup(p.stderr.close)
1220 self.addCleanup(p.stdin.close)
1221 p.communicate(b"x" * 2**20)
1222
1223 def test_communicate_epipe_only_stdin(self):
1224 # Issue 10963: communicate() should hide EPIPE
1225 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1226 stdin=subprocess.PIPE)
1227 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001228 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001229 p.communicate(b"x" * 2**20)
1230
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001231 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1232 "Requires signal.SIGUSR1")
1233 @unittest.skipUnless(hasattr(os, 'kill'),
1234 "Requires os.kill")
1235 @unittest.skipUnless(hasattr(os, 'getppid'),
1236 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001237 def test_communicate_eintr(self):
1238 # Issue #12493: communicate() should handle EINTR
1239 def handler(signum, frame):
1240 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001241 old_handler = signal.signal(signal.SIGUSR1, handler)
1242 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001243
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001244 args = [sys.executable, "-c",
1245 'import os, signal;'
1246 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001247 for stream in ('stdout', 'stderr'):
1248 kw = {stream: subprocess.PIPE}
1249 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001250 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001251 process.communicate()
1252
Tim Peterse718f612004-10-12 21:51:32 +00001253
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001254 # This test is Linux-ish specific for simplicity to at least have
1255 # some coverage. It is not a platform specific bug.
1256 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1257 "Linux specific")
1258 def test_failed_child_execute_fd_leak(self):
1259 """Test for the fork() failure fd leak reported in issue16327."""
1260 fd_directory = '/proc/%d/fd' % os.getpid()
1261 fds_before_popen = os.listdir(fd_directory)
1262 with self.assertRaises(PopenTestException):
1263 PopenExecuteChildRaises(
1264 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
1265 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1266
1267 # NOTE: This test doesn't verify that the real _execute_child
1268 # does not close the file descriptors itself on the way out
1269 # during an exception. Code inspection has confirmed that.
1270
1271 fds_after_exception = os.listdir(fd_directory)
1272 self.assertEqual(fds_before_popen, fds_after_exception)
1273
Gregory P. Smith6e730002015-04-14 16:14:25 -07001274
1275class RunFuncTestCase(BaseTestCase):
1276 def run_python(self, code, **kwargs):
1277 """Run Python code in a subprocess using subprocess.run"""
1278 argv = [sys.executable, "-c", code]
1279 return subprocess.run(argv, **kwargs)
1280
1281 def test_returncode(self):
1282 # call() function with sequence argument
1283 cp = self.run_python("import sys; sys.exit(47)")
1284 self.assertEqual(cp.returncode, 47)
1285 with self.assertRaises(subprocess.CalledProcessError):
1286 cp.check_returncode()
1287
1288 def test_check(self):
1289 with self.assertRaises(subprocess.CalledProcessError) as c:
1290 self.run_python("import sys; sys.exit(47)", check=True)
1291 self.assertEqual(c.exception.returncode, 47)
1292
1293 def test_check_zero(self):
1294 # check_returncode shouldn't raise when returncode is zero
1295 cp = self.run_python("import sys; sys.exit(0)", check=True)
1296 self.assertEqual(cp.returncode, 0)
1297
1298 def test_timeout(self):
1299 # run() function with timeout argument; we want to test that the child
1300 # process gets killed when the timeout expires. If the child isn't
1301 # killed, this call will deadlock since subprocess.run waits for the
1302 # child.
1303 with self.assertRaises(subprocess.TimeoutExpired):
1304 self.run_python("while True: pass", timeout=0.0001)
1305
1306 def test_capture_stdout(self):
1307 # capture stdout with zero return code
1308 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1309 self.assertIn(b'BDFL', cp.stdout)
1310
1311 def test_capture_stderr(self):
1312 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1313 stderr=subprocess.PIPE)
1314 self.assertIn(b'BDFL', cp.stderr)
1315
1316 def test_check_output_stdin_arg(self):
1317 # run() can be called with stdin set to a file
1318 tf = tempfile.TemporaryFile()
1319 self.addCleanup(tf.close)
1320 tf.write(b'pear')
1321 tf.seek(0)
1322 cp = self.run_python(
1323 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1324 stdin=tf, stdout=subprocess.PIPE)
1325 self.assertIn(b'PEAR', cp.stdout)
1326
1327 def test_check_output_input_arg(self):
1328 # check_output() can be called with input set to a string
1329 cp = self.run_python(
1330 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1331 input=b'pear', stdout=subprocess.PIPE)
1332 self.assertIn(b'PEAR', cp.stdout)
1333
1334 def test_check_output_stdin_with_input_arg(self):
1335 # run() refuses to accept 'stdin' with 'input'
1336 tf = tempfile.TemporaryFile()
1337 self.addCleanup(tf.close)
1338 tf.write(b'pear')
1339 tf.seek(0)
1340 with self.assertRaises(ValueError,
1341 msg="Expected ValueError when stdin and input args supplied.") as c:
1342 output = self.run_python("print('will not be run')",
1343 stdin=tf, input=b'hare')
1344 self.assertIn('stdin', c.exception.args[0])
1345 self.assertIn('input', c.exception.args[0])
1346
1347 def test_check_output_timeout(self):
1348 with self.assertRaises(subprocess.TimeoutExpired) as c:
1349 cp = self.run_python((
1350 "import sys, time\n"
1351 "sys.stdout.write('BDFL')\n"
1352 "sys.stdout.flush()\n"
1353 "time.sleep(3600)"),
1354 # Some heavily loaded buildbots (sparc Debian 3.x) require
1355 # this much time to start and print.
1356 timeout=3, stdout=subprocess.PIPE)
1357 self.assertEqual(c.exception.output, b'BDFL')
1358 # output is aliased to stdout
1359 self.assertEqual(c.exception.stdout, b'BDFL')
1360
1361 def test_run_kwargs(self):
1362 newenv = os.environ.copy()
1363 newenv["FRUIT"] = "banana"
1364 cp = self.run_python(('import sys, os;'
1365 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1366 env=newenv)
1367 self.assertEqual(cp.returncode, 33)
1368
1369
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001370@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001371class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001372
Gregory P. Smith5591b022012-10-10 03:34:47 -07001373 def setUp(self):
1374 super().setUp()
1375 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1376
1377 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001378 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001379 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001380 except OSError as e:
1381 # This avoids hard coding the errno value or the OS perror()
1382 # string and instead capture the exception that we want to see
1383 # below for comparison.
1384 desired_exception = e
Gregory P. Smith5591b022012-10-10 03:34:47 -07001385 desired_exception.strerror += ': ' + repr(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001386 else:
Martin Pantereb995702016-07-28 01:11:04 +00001387 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001388 self._nonexistent_dir)
1389 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001390
Gregory P. Smith5591b022012-10-10 03:34:47 -07001391 def test_exception_cwd(self):
1392 """Test error in the child raised in the parent for a bad cwd."""
1393 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001394 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001395 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001396 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001397 except OSError as e:
1398 # Test that the child process chdir failure actually makes
1399 # it up to the parent process as the correct exception.
1400 self.assertEqual(desired_exception.errno, e.errno)
1401 self.assertEqual(desired_exception.strerror, e.strerror)
1402 else:
1403 self.fail("Expected OSError: %s" % desired_exception)
1404
Gregory P. Smith5591b022012-10-10 03:34:47 -07001405 def test_exception_bad_executable(self):
1406 """Test error in the child raised in the parent for a bad executable."""
1407 desired_exception = self._get_chdir_exception()
1408 try:
1409 p = subprocess.Popen([sys.executable, "-c", ""],
1410 executable=self._nonexistent_dir)
1411 except OSError as e:
1412 # Test that the child process exec failure actually makes
1413 # it up to the parent process as the correct exception.
1414 self.assertEqual(desired_exception.errno, e.errno)
1415 self.assertEqual(desired_exception.strerror, e.strerror)
1416 else:
1417 self.fail("Expected OSError: %s" % desired_exception)
1418
1419 def test_exception_bad_args_0(self):
1420 """Test error in the child raised in the parent for a bad args[0]."""
1421 desired_exception = self._get_chdir_exception()
1422 try:
1423 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1424 except OSError as e:
1425 # Test that the child process exec failure actually makes
1426 # it up to the parent process as the correct exception.
1427 self.assertEqual(desired_exception.errno, e.errno)
1428 self.assertEqual(desired_exception.strerror, e.strerror)
1429 else:
1430 self.fail("Expected OSError: %s" % desired_exception)
1431
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001432 def test_restore_signals(self):
1433 # Code coverage for both values of restore_signals to make sure it
1434 # at least does not blow up.
1435 # A test for behavior would be complex. Contributions welcome.
1436 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1437 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1438
1439 def test_start_new_session(self):
1440 # For code coverage of calling setsid(). We don't care if we get an
1441 # EPERM error from it depending on the test execution environment, that
1442 # still indicates that it was called.
1443 try:
1444 output = subprocess.check_output(
1445 [sys.executable, "-c",
1446 "import os; print(os.getpgid(os.getpid()))"],
1447 start_new_session=True)
1448 except OSError as e:
1449 if e.errno != errno.EPERM:
1450 raise
1451 else:
1452 parent_pgid = os.getpgid(os.getpid())
1453 child_pgid = int(output)
1454 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001455
1456 def test_run_abort(self):
1457 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001458 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001459 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001460 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001461 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001462 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001463
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001464 def test_CalledProcessError_str_signal(self):
1465 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
1466 error_string = str(err)
1467 # We're relying on the repr() of the signal.Signals intenum to provide
1468 # the word signal, the signal name and the numeric value.
1469 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00001470 # We're not being specific about the signal name as some signals have
1471 # multiple names and which name is revealed can vary.
1472 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001473 self.assertIn(str(signal.SIGABRT), error_string)
1474
1475 def test_CalledProcessError_str_unknown_signal(self):
1476 err = subprocess.CalledProcessError(-9876543, "fake cmd")
1477 error_string = str(err)
1478 self.assertIn("unknown signal 9876543.", error_string)
1479
1480 def test_CalledProcessError_str_non_zero(self):
1481 err = subprocess.CalledProcessError(2, "fake cmd")
1482 error_string = str(err)
1483 self.assertIn("non-zero exit status 2.", error_string)
1484
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001485 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001486 # DISCLAIMER: Setting environment variables is *not* a good use
1487 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001488 p = subprocess.Popen([sys.executable, "-c",
1489 'import sys,os;'
1490 'sys.stdout.write(os.getenv("FRUIT"))'],
1491 stdout=subprocess.PIPE,
1492 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02001493 with p:
1494 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001495
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001496 def test_preexec_exception(self):
1497 def raise_it():
1498 raise ValueError("What if two swallows carried a coconut?")
1499 try:
1500 p = subprocess.Popen([sys.executable, "-c", ""],
1501 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001502 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001503 self.assertTrue(
1504 subprocess._posixsubprocess,
1505 "Expected a ValueError from the preexec_fn")
1506 except ValueError as e:
1507 self.assertIn("coconut", e.args[0])
1508 else:
1509 self.fail("Exception raised by preexec_fn did not make it "
1510 "to the parent process.")
1511
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001512 class _TestExecuteChildPopen(subprocess.Popen):
1513 """Used to test behavior at the end of _execute_child."""
1514 def __init__(self, testcase, *args, **kwargs):
1515 self._testcase = testcase
1516 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001517
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001518 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001519 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001520 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001521 finally:
1522 # Open a bunch of file descriptors and verify that
1523 # none of them are the same as the ones the Popen
1524 # instance is using for stdin/stdout/stderr.
1525 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1526 for _ in range(8)]
1527 try:
1528 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001529 self._testcase.assertNotIn(
1530 fd, (self.stdin.fileno(), self.stdout.fileno(),
1531 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001532 msg="At least one fd was closed early.")
1533 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01001534 for fd in devzero_fds:
1535 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001536
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001537 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1538 def test_preexec_errpipe_does_not_double_close_pipes(self):
1539 """Issue16140: Don't double close pipes on preexec error."""
1540
1541 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08001542 raise subprocess.SubprocessError(
1543 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001544
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08001545 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001546 self._TestExecuteChildPopen(
1547 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001548 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1549 stderr=subprocess.PIPE, preexec_fn=raise_it)
1550
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001551 def test_preexec_gc_module_failure(self):
1552 # This tests the code that disables garbage collection if the child
1553 # process will execute any Python.
1554 def raise_runtime_error():
1555 raise RuntimeError("this shouldn't escape")
1556 enabled = gc.isenabled()
1557 orig_gc_disable = gc.disable
1558 orig_gc_isenabled = gc.isenabled
1559 try:
1560 gc.disable()
1561 self.assertFalse(gc.isenabled())
1562 subprocess.call([sys.executable, '-c', ''],
1563 preexec_fn=lambda: None)
1564 self.assertFalse(gc.isenabled(),
1565 "Popen enabled gc when it shouldn't.")
1566
1567 gc.enable()
1568 self.assertTrue(gc.isenabled())
1569 subprocess.call([sys.executable, '-c', ''],
1570 preexec_fn=lambda: None)
1571 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1572
1573 gc.disable = raise_runtime_error
1574 self.assertRaises(RuntimeError, subprocess.Popen,
1575 [sys.executable, '-c', ''],
1576 preexec_fn=lambda: None)
1577
1578 del gc.isenabled # force an AttributeError
1579 self.assertRaises(AttributeError, subprocess.Popen,
1580 [sys.executable, '-c', ''],
1581 preexec_fn=lambda: None)
1582 finally:
1583 gc.disable = orig_gc_disable
1584 gc.isenabled = orig_gc_isenabled
1585 if not enabled:
1586 gc.disable()
1587
Martin Panterf7fdbda2015-12-05 09:51:52 +00001588 @unittest.skipIf(
1589 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00001590 def test_preexec_fork_failure(self):
1591 # The internal code did not preserve the previous exception when
1592 # re-enabling garbage collection
1593 try:
1594 from resource import getrlimit, setrlimit, RLIMIT_NPROC
1595 except ImportError as err:
1596 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
1597 limits = getrlimit(RLIMIT_NPROC)
1598 [_, hard] = limits
1599 setrlimit(RLIMIT_NPROC, (0, hard))
1600 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00001601 try:
Martin Panterafdd5132015-11-30 02:21:41 +00001602 subprocess.call([sys.executable, '-c', ''],
1603 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00001604 except BlockingIOError:
1605 # Forking should raise EAGAIN, translated to BlockingIOError
1606 pass
1607 else:
1608 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00001609
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001610 def test_args_string(self):
1611 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03001612 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001613 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001614 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001615 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001616 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1617 sys.executable)
1618 os.chmod(fname, 0o700)
1619 p = subprocess.Popen(fname)
1620 p.wait()
1621 os.remove(fname)
1622 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001623
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001624 def test_invalid_args(self):
1625 # invalid arguments should raise ValueError
1626 self.assertRaises(ValueError, subprocess.call,
1627 [sys.executable, "-c",
1628 "import sys; sys.exit(47)"],
1629 startupinfo=47)
1630 self.assertRaises(ValueError, subprocess.call,
1631 [sys.executable, "-c",
1632 "import sys; sys.exit(47)"],
1633 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001634
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001635 def test_shell_sequence(self):
1636 # Run command through the shell (sequence)
1637 newenv = os.environ.copy()
1638 newenv["FRUIT"] = "apple"
1639 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1640 stdout=subprocess.PIPE,
1641 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001642 with p:
1643 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001644
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001645 def test_shell_string(self):
1646 # Run command through the shell (string)
1647 newenv = os.environ.copy()
1648 newenv["FRUIT"] = "apple"
1649 p = subprocess.Popen("echo $FRUIT", shell=1,
1650 stdout=subprocess.PIPE,
1651 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001652 with p:
1653 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001654
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001655 def test_call_string(self):
1656 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03001657 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001658 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001659 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001660 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001661 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1662 sys.executable)
1663 os.chmod(fname, 0o700)
1664 rc = subprocess.call(fname)
1665 os.remove(fname)
1666 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001667
Stefan Krah9542cc62010-07-19 14:20:53 +00001668 def test_specific_shell(self):
1669 # Issue #9265: Incorrect name passed as arg[0].
1670 shells = []
1671 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1672 for name in ['bash', 'ksh']:
1673 sh = os.path.join(prefix, name)
1674 if os.path.isfile(sh):
1675 shells.append(sh)
1676 if not shells: # Will probably work for any shell but csh.
1677 self.skipTest("bash or ksh required for this test")
1678 sh = '/bin/sh'
1679 if os.path.isfile(sh) and not os.path.islink(sh):
1680 # Test will fail if /bin/sh is a symlink to csh.
1681 shells.append(sh)
1682 for sh in shells:
1683 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1684 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02001685 with p:
1686 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00001687
Florent Xicluna4886d242010-03-08 13:27:26 +00001688 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001689 # Do not inherit file handles from the parent.
1690 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07001691 # Also set the SIGINT handler to the default to make sure it's not
1692 # being ignored (some tests rely on that.)
1693 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
1694 try:
1695 p = subprocess.Popen([sys.executable, "-c", """if 1:
1696 import sys, time
1697 sys.stdout.write('x\\n')
1698 sys.stdout.flush()
1699 time.sleep(30)
1700 """],
1701 close_fds=True,
1702 stdin=subprocess.PIPE,
1703 stdout=subprocess.PIPE,
1704 stderr=subprocess.PIPE)
1705 finally:
1706 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001707 # Wait for the interpreter to be completely initialized before
1708 # sending any signal.
1709 p.stdout.read(1)
1710 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001711 return p
1712
Charles-François Natali53221e32013-01-12 16:52:20 +01001713 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1714 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001715 def _kill_dead_process(self, method, *args):
1716 # Do not inherit file handles from the parent.
1717 # It should fix failures on some platforms.
1718 p = subprocess.Popen([sys.executable, "-c", """if 1:
1719 import sys, time
1720 sys.stdout.write('x\\n')
1721 sys.stdout.flush()
1722 """],
1723 close_fds=True,
1724 stdin=subprocess.PIPE,
1725 stdout=subprocess.PIPE,
1726 stderr=subprocess.PIPE)
1727 # Wait for the interpreter to be completely initialized before
1728 # sending any signal.
1729 p.stdout.read(1)
1730 # The process should end after this
1731 time.sleep(1)
1732 # This shouldn't raise even though the child is now dead
1733 getattr(p, method)(*args)
1734 p.communicate()
1735
Florent Xicluna4886d242010-03-08 13:27:26 +00001736 def test_send_signal(self):
1737 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001738 _, stderr = p.communicate()
1739 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001740 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001741
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001742 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001743 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001744 _, stderr = p.communicate()
1745 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001746 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001747
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001748 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001749 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001750 _, stderr = p.communicate()
1751 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001752 self.assertEqual(p.wait(), -signal.SIGTERM)
1753
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001754 def test_send_signal_dead(self):
1755 # Sending a signal to a dead process
1756 self._kill_dead_process('send_signal', signal.SIGINT)
1757
1758 def test_kill_dead(self):
1759 # Killing a dead process
1760 self._kill_dead_process('kill')
1761
1762 def test_terminate_dead(self):
1763 # Terminating a dead process
1764 self._kill_dead_process('terminate')
1765
Victor Stinnerdaf45552013-08-28 00:53:59 +02001766 def _save_fds(self, save_fds):
1767 fds = []
1768 for fd in save_fds:
1769 inheritable = os.get_inheritable(fd)
1770 saved = os.dup(fd)
1771 fds.append((fd, saved, inheritable))
1772 return fds
1773
1774 def _restore_fds(self, fds):
1775 for fd, saved, inheritable in fds:
1776 os.dup2(saved, fd, inheritable=inheritable)
1777 os.close(saved)
1778
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001779 def check_close_std_fds(self, fds):
1780 # Issue #9905: test that subprocess pipes still work properly with
1781 # some standard fds closed
1782 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02001783 saved_fds = self._save_fds(fds)
1784 for fd, saved, inheritable in saved_fds:
1785 if fd == 0:
1786 stdin = saved
1787 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001788 try:
1789 for fd in fds:
1790 os.close(fd)
1791 out, err = subprocess.Popen([sys.executable, "-c",
1792 'import sys;'
1793 'sys.stdout.write("apple");'
1794 'sys.stdout.flush();'
1795 'sys.stderr.write("orange")'],
1796 stdin=stdin,
1797 stdout=subprocess.PIPE,
1798 stderr=subprocess.PIPE).communicate()
1799 err = support.strip_python_stderr(err)
1800 self.assertEqual((out, err), (b'apple', b'orange'))
1801 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001802 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001803
1804 def test_close_fd_0(self):
1805 self.check_close_std_fds([0])
1806
1807 def test_close_fd_1(self):
1808 self.check_close_std_fds([1])
1809
1810 def test_close_fd_2(self):
1811 self.check_close_std_fds([2])
1812
1813 def test_close_fds_0_1(self):
1814 self.check_close_std_fds([0, 1])
1815
1816 def test_close_fds_0_2(self):
1817 self.check_close_std_fds([0, 2])
1818
1819 def test_close_fds_1_2(self):
1820 self.check_close_std_fds([1, 2])
1821
1822 def test_close_fds_0_1_2(self):
1823 # Issue #10806: test that subprocess pipes still work properly with
1824 # all standard fds closed.
1825 self.check_close_std_fds([0, 1, 2])
1826
Gregory P. Smith53dd8162013-12-01 16:03:24 -08001827 def test_small_errpipe_write_fd(self):
1828 """Issue #15798: Popen should work when stdio fds are available."""
1829 new_stdin = os.dup(0)
1830 new_stdout = os.dup(1)
1831 try:
1832 os.close(0)
1833 os.close(1)
1834
1835 # Side test: if errpipe_write fails to have its CLOEXEC
1836 # flag set this should cause the parent to think the exec
1837 # failed. Extremely unlikely: everyone supports CLOEXEC.
1838 subprocess.Popen([
1839 sys.executable, "-c",
1840 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
1841 finally:
1842 # Restore original stdin and stdout
1843 os.dup2(new_stdin, 0)
1844 os.dup2(new_stdout, 1)
1845 os.close(new_stdin)
1846 os.close(new_stdout)
1847
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001848 def test_remapping_std_fds(self):
1849 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03001850 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001851 try:
1852 temp_fds = [fd for fd, fname in temps]
1853
1854 # unlink the files -- we won't need to reopen them
1855 for fd, fname in temps:
1856 os.unlink(fname)
1857
1858 # write some data to what will become stdin, and rewind
1859 os.write(temp_fds[1], b"STDIN")
1860 os.lseek(temp_fds[1], 0, 0)
1861
1862 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02001863 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001864 try:
1865 # duplicate the file objects over the standard fd's
1866 for fd, temp_fd in enumerate(temp_fds):
1867 os.dup2(temp_fd, fd)
1868
1869 # now use those files in the "wrong" order, so that subprocess
1870 # has to rearrange them in the child
1871 p = subprocess.Popen([sys.executable, "-c",
1872 'import sys; got = sys.stdin.read();'
1873 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1874 stdin=temp_fds[1],
1875 stdout=temp_fds[2],
1876 stderr=temp_fds[0])
1877 p.wait()
1878 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001879 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001880
1881 for fd in temp_fds:
1882 os.lseek(fd, 0, 0)
1883
1884 out = os.read(temp_fds[2], 1024)
1885 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1886 self.assertEqual(out, b"got STDIN")
1887 self.assertEqual(err, b"err")
1888
1889 finally:
1890 for fd in temp_fds:
1891 os.close(fd)
1892
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001893 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1894 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03001895 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001896 temp_fds = [fd for fd, fname in temps]
1897 try:
1898 # unlink the files -- we won't need to reopen them
1899 for fd, fname in temps:
1900 os.unlink(fname)
1901
1902 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02001903 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001904 try:
1905 # duplicate the temp files over the standard fd's 0, 1, 2
1906 for fd, temp_fd in enumerate(temp_fds):
1907 os.dup2(temp_fd, fd)
1908
1909 # write some data to what will become stdin, and rewind
1910 os.write(stdin_no, b"STDIN")
1911 os.lseek(stdin_no, 0, 0)
1912
1913 # now use those files in the given order, so that subprocess
1914 # has to rearrange them in the child
1915 p = subprocess.Popen([sys.executable, "-c",
1916 'import sys; got = sys.stdin.read();'
1917 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1918 stdin=stdin_no,
1919 stdout=stdout_no,
1920 stderr=stderr_no)
1921 p.wait()
1922
1923 for fd in temp_fds:
1924 os.lseek(fd, 0, 0)
1925
1926 out = os.read(stdout_no, 1024)
1927 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1928 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001929 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001930
1931 self.assertEqual(out, b"got STDIN")
1932 self.assertEqual(err, b"err")
1933
1934 finally:
1935 for fd in temp_fds:
1936 os.close(fd)
1937
1938 # When duping fds, if there arises a situation where one of the fds is
1939 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1940 # This tests all combinations of this.
1941 def test_swap_fds(self):
1942 self.check_swap_fds(0, 1, 2)
1943 self.check_swap_fds(0, 2, 1)
1944 self.check_swap_fds(1, 0, 2)
1945 self.check_swap_fds(1, 2, 0)
1946 self.check_swap_fds(2, 0, 1)
1947 self.check_swap_fds(2, 1, 0)
1948
Victor Stinner13bb71c2010-04-23 21:41:56 +00001949 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001950 def prepare():
1951 raise ValueError("surrogate:\uDCff")
1952
1953 try:
1954 subprocess.call(
1955 [sys.executable, "-c", "pass"],
1956 preexec_fn=prepare)
1957 except ValueError as err:
1958 # Pure Python implementations keeps the message
1959 self.assertIsNone(subprocess._posixsubprocess)
1960 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001961 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00001962 # _posixsubprocess uses a default message
1963 self.assertIsNotNone(subprocess._posixsubprocess)
1964 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1965 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001966 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00001967
Victor Stinner13bb71c2010-04-23 21:41:56 +00001968 def test_undecodable_env(self):
1969 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01001970 encoded_value = value.encode("ascii", "surrogateescape")
1971
Victor Stinner13bb71c2010-04-23 21:41:56 +00001972 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001973 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001974 env = os.environ.copy()
1975 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01001976 # Use C locale to get ASCII for the locale encoding to force
Victor Stinner89f3ad12010-10-14 10:43:31 +00001977 # surrogate-escaping of \xFF in the child process; otherwise it can
1978 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001979 env['LC_ALL'] = 'C'
Victor Stinner5323fb02013-11-19 23:46:06 +01001980 if sys.platform.startswith("aix"):
1981 # On AIX, the C locale uses the Latin1 encoding
1982 decoded_value = encoded_value.decode("latin1", "surrogateescape")
1983 else:
1984 # On other UNIXes, the C locale uses the ASCII encoding
1985 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001986 stdout = subprocess.check_output(
1987 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001988 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001989 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01001990 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001991
1992 # test bytes
1993 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001994 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001995 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01001996 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001997 stdout = subprocess.check_output(
1998 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001999 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002000 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002001 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002002
Victor Stinnerb745a742010-05-18 17:17:23 +00002003 def test_bytes_program(self):
2004 abs_program = os.fsencode(sys.executable)
2005 path, program = os.path.split(sys.executable)
2006 program = os.fsencode(program)
2007
2008 # absolute bytes path
2009 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00002010 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002011
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002012 # absolute bytes path as a string
2013 cmd = b"'" + abs_program + b"' -c pass"
2014 exitcode = subprocess.call(cmd, shell=True)
2015 self.assertEqual(exitcode, 0)
2016
Victor Stinnerb745a742010-05-18 17:17:23 +00002017 # bytes program, unicode PATH
2018 env = os.environ.copy()
2019 env["PATH"] = path
2020 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002021 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002022
2023 # bytes program, bytes PATH
2024 envb = os.environb.copy()
2025 envb[b"PATH"] = os.fsencode(path)
2026 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002027 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002028
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002029 def test_pipe_cloexec(self):
2030 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2031 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2032
2033 p1 = subprocess.Popen([sys.executable, sleeper],
2034 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2035 stderr=subprocess.PIPE, close_fds=False)
2036
2037 self.addCleanup(p1.communicate, b'')
2038
2039 p2 = subprocess.Popen([sys.executable, fd_status],
2040 stdout=subprocess.PIPE, close_fds=False)
2041
2042 output, error = p2.communicate()
2043 result_fds = set(map(int, output.split(b',')))
2044 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2045 p1.stderr.fileno()])
2046
2047 self.assertFalse(result_fds & unwanted_fds,
2048 "Expected no fds from %r to be open in child, "
2049 "found %r" %
2050 (unwanted_fds, result_fds & unwanted_fds))
2051
2052 def test_pipe_cloexec_real_tools(self):
2053 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2054 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2055
2056 subdata = b'zxcvbn'
2057 data = subdata * 4 + b'\n'
2058
2059 p1 = subprocess.Popen([sys.executable, qcat],
2060 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2061 close_fds=False)
2062
2063 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2064 stdin=p1.stdout, stdout=subprocess.PIPE,
2065 close_fds=False)
2066
2067 self.addCleanup(p1.wait)
2068 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002069 def kill_p1():
2070 try:
2071 p1.terminate()
2072 except ProcessLookupError:
2073 pass
2074 def kill_p2():
2075 try:
2076 p2.terminate()
2077 except ProcessLookupError:
2078 pass
2079 self.addCleanup(kill_p1)
2080 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002081
2082 p1.stdin.write(data)
2083 p1.stdin.close()
2084
2085 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2086
2087 self.assertTrue(readfiles, "The child hung")
2088 self.assertEqual(p2.stdout.read(), data)
2089
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002090 p1.stdout.close()
2091 p2.stdout.close()
2092
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002093 def test_close_fds(self):
2094 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2095
2096 fds = os.pipe()
2097 self.addCleanup(os.close, fds[0])
2098 self.addCleanup(os.close, fds[1])
2099
2100 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002101 # add a bunch more fds
2102 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002103 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002104 self.addCleanup(os.close, fd)
2105 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002106
Victor Stinnerdaf45552013-08-28 00:53:59 +02002107 for fd in open_fds:
2108 os.set_inheritable(fd, True)
2109
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002110 p = subprocess.Popen([sys.executable, fd_status],
2111 stdout=subprocess.PIPE, close_fds=False)
2112 output, ignored = p.communicate()
2113 remaining_fds = set(map(int, output.split(b',')))
2114
2115 self.assertEqual(remaining_fds & open_fds, open_fds,
2116 "Some fds were closed")
2117
2118 p = subprocess.Popen([sys.executable, fd_status],
2119 stdout=subprocess.PIPE, close_fds=True)
2120 output, ignored = p.communicate()
2121 remaining_fds = set(map(int, output.split(b',')))
2122
2123 self.assertFalse(remaining_fds & open_fds,
2124 "Some fds were left open")
2125 self.assertIn(1, remaining_fds, "Subprocess failed")
2126
Gregory P. Smith8facece2012-01-21 14:01:08 -08002127 # Keep some of the fd's we opened open in the subprocess.
2128 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2129 fds_to_keep = set(open_fds.pop() for _ in range(8))
2130 p = subprocess.Popen([sys.executable, fd_status],
2131 stdout=subprocess.PIPE, close_fds=True,
2132 pass_fds=())
2133 output, ignored = p.communicate()
2134 remaining_fds = set(map(int, output.split(b',')))
2135
2136 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
2137 "Some fds not in pass_fds were left open")
2138 self.assertIn(1, remaining_fds, "Subprocess failed")
2139
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002140
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002141 @unittest.skipIf(sys.platform.startswith("freebsd") and
2142 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2143 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002144 def test_close_fds_when_max_fd_is_lowered(self):
2145 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2146 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2147
Gregory P. Smith634aa682014-06-15 17:51:04 -07002148 # This launches the meat of the test in a child process to
2149 # avoid messing with the larger unittest processes maximum
2150 # number of file descriptors.
2151 # This process launches:
2152 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2153 # a bunch of high open fds above the new lower rlimit.
2154 # Those are reported via stdout before launching a new
2155 # process with close_fds=False to run the actual test:
2156 # +--> The TEST: This one launches a fd_status.py
2157 # subprocess with close_fds=True so we can find out if
2158 # any of the fds above the lowered rlimit are still open.
2159 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2160 '''
2161 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002162 open_fds = set()
2163 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002164 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002165 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002166 open_fds.add(fd)
2167
2168 # Leave a two pairs of low ones available for use by the
2169 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002170 # We also leave 10 more open as some Python buildbots run into
2171 # "too many open files" errors during the test if we do not.
2172 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002173 os.close(fd)
2174 open_fds.remove(fd)
2175
2176 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002177 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002178 os.set_inheritable(fd, True)
2179
2180 max_fd_open = max(open_fds)
2181
Gregory P. Smith634aa682014-06-15 17:51:04 -07002182 # Communicate the open_fds to the parent unittest.TestCase process.
2183 print(','.join(map(str, sorted(open_fds))))
2184 sys.stdout.flush()
2185
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002186 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2187 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002188 # 29 is lower than the highest fds we are leaving open.
2189 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002190 # Launch a new Python interpreter with our low fd rlim_cur that
2191 # inherits open fds above that limit. It then uses subprocess
2192 # with close_fds=True to get a report of open fds in the child.
2193 # An explicit list of fds to check is passed to fd_status.py as
2194 # letting fd_status rely on its default logic would miss the
2195 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002196 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002197 [sys.executable, '-c',
2198 textwrap.dedent("""
2199 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002200 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002201 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002202 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002203 """.format(max_fd=max_fd_open+1))],
2204 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002205 finally:
2206 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002207 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002208
2209 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002210 output_lines = output.splitlines()
2211 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002212 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002213 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2214 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002215
Gregory P. Smith634aa682014-06-15 17:51:04 -07002216 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002217 msg="Some fds were left open.")
2218
2219
Victor Stinner88701e22011-06-01 13:13:04 +02002220 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2221 # descriptor of a pipe closed in the parent process is valid in the
2222 # child process according to fstat(), but the mode of the file
2223 # descriptor is invalid, and read or write raise an error.
2224 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002225 def test_pass_fds(self):
2226 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2227
2228 open_fds = set()
2229
2230 for x in range(5):
2231 fds = os.pipe()
2232 self.addCleanup(os.close, fds[0])
2233 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002234 os.set_inheritable(fds[0], True)
2235 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002236 open_fds.update(fds)
2237
2238 for fd in open_fds:
2239 p = subprocess.Popen([sys.executable, fd_status],
2240 stdout=subprocess.PIPE, close_fds=True,
2241 pass_fds=(fd, ))
2242 output, ignored = p.communicate()
2243
2244 remaining_fds = set(map(int, output.split(b',')))
2245 to_be_closed = open_fds - {fd}
2246
2247 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2248 self.assertFalse(remaining_fds & to_be_closed,
2249 "fd to be closed passed")
2250
2251 # pass_fds overrides close_fds with a warning.
2252 with self.assertWarns(RuntimeWarning) as context:
2253 self.assertFalse(subprocess.call(
2254 [sys.executable, "-c", "import sys; sys.exit(0)"],
2255 close_fds=False, pass_fds=(fd, )))
2256 self.assertIn('overriding close_fds', str(context.warning))
2257
Victor Stinnerdaf45552013-08-28 00:53:59 +02002258 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002259 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002260
2261 inheritable, non_inheritable = os.pipe()
2262 self.addCleanup(os.close, inheritable)
2263 self.addCleanup(os.close, non_inheritable)
2264 os.set_inheritable(inheritable, True)
2265 os.set_inheritable(non_inheritable, False)
2266 pass_fds = (inheritable, non_inheritable)
2267 args = [sys.executable, script]
2268 args += list(map(str, pass_fds))
2269
2270 p = subprocess.Popen(args,
2271 stdout=subprocess.PIPE, close_fds=True,
2272 pass_fds=pass_fds)
2273 output, ignored = p.communicate()
2274 fds = set(map(int, output.split(b',')))
2275
2276 # the inheritable file descriptor must be inherited, so its inheritable
2277 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002278 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002279
2280 # inheritable flag must not be changed in the parent process
2281 self.assertEqual(os.get_inheritable(inheritable), True)
2282 self.assertEqual(os.get_inheritable(non_inheritable), False)
2283
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002284 def test_stdout_stdin_are_single_inout_fd(self):
2285 with io.open(os.devnull, "r+") as inout:
2286 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2287 stdout=inout, stdin=inout)
2288 p.wait()
2289
2290 def test_stdout_stderr_are_single_inout_fd(self):
2291 with io.open(os.devnull, "r+") as inout:
2292 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2293 stdout=inout, stderr=inout)
2294 p.wait()
2295
2296 def test_stderr_stdin_are_single_inout_fd(self):
2297 with io.open(os.devnull, "r+") as inout:
2298 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2299 stderr=inout, stdin=inout)
2300 p.wait()
2301
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002302 def test_wait_when_sigchild_ignored(self):
2303 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2304 sigchild_ignore = support.findfile("sigchild_ignore.py",
2305 subdir="subprocessdata")
2306 p = subprocess.Popen([sys.executable, sigchild_ignore],
2307 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2308 stdout, stderr = p.communicate()
2309 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002310 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002311 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002312
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002313 def test_select_unbuffered(self):
2314 # Issue #11459: bufsize=0 should really set the pipes as
2315 # unbuffered (and therefore let select() work properly).
2316 select = support.import_module("select")
2317 p = subprocess.Popen([sys.executable, "-c",
2318 'import sys;'
2319 'sys.stdout.write("apple")'],
2320 stdout=subprocess.PIPE,
2321 bufsize=0)
2322 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002323 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002324 try:
2325 self.assertEqual(f.read(4), b"appl")
2326 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2327 finally:
2328 p.wait()
2329
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002330 def test_zombie_fast_process_del(self):
2331 # Issue #12650: on Unix, if Popen.__del__() was called before the
2332 # process exited, it wouldn't be added to subprocess._active, and would
2333 # remain a zombie.
2334 # spawn a Popen, and delete its reference before it exits
2335 p = subprocess.Popen([sys.executable, "-c",
2336 'import sys, time;'
2337 'time.sleep(0.2)'],
2338 stdout=subprocess.PIPE,
2339 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002340 self.addCleanup(p.stdout.close)
2341 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002342 ident = id(p)
2343 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002344 with support.check_warnings(('', ResourceWarning)):
2345 p = None
2346
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002347 # check that p is in the active processes list
2348 self.assertIn(ident, [id(o) for o in subprocess._active])
2349
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002350 def test_leak_fast_process_del_killed(self):
2351 # Issue #12650: on Unix, if Popen.__del__() was called before the
2352 # process exited, and the process got killed by a signal, it would never
2353 # be removed from subprocess._active, which triggered a FD and memory
2354 # leak.
2355 # spawn a Popen, delete its reference and kill it
2356 p = subprocess.Popen([sys.executable, "-c",
2357 'import time;'
2358 'time.sleep(3)'],
2359 stdout=subprocess.PIPE,
2360 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002361 self.addCleanup(p.stdout.close)
2362 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002363 ident = id(p)
2364 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002365 with support.check_warnings(('', ResourceWarning)):
2366 p = None
2367
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002368 os.kill(pid, signal.SIGKILL)
2369 # check that p is in the active processes list
2370 self.assertIn(ident, [id(o) for o in subprocess._active])
2371
2372 # let some time for the process to exit, and create a new Popen: this
2373 # should trigger the wait() of p
2374 time.sleep(0.2)
Andrew Svetlov3438fa42012-12-17 23:35:18 +02002375 with self.assertRaises(OSError) as c:
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002376 with subprocess.Popen(['nonexisting_i_hope'],
2377 stdout=subprocess.PIPE,
2378 stderr=subprocess.PIPE) as proc:
2379 pass
2380 # p should have been wait()ed on, and removed from the _active list
2381 self.assertRaises(OSError, os.waitpid, pid, 0)
2382 self.assertNotIn(ident, [id(o) for o in subprocess._active])
2383
Charles-François Natali249cdc32013-08-25 18:24:45 +02002384 def test_close_fds_after_preexec(self):
2385 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2386
2387 # this FD is used as dup2() target by preexec_fn, and should be closed
2388 # in the child process
2389 fd = os.dup(1)
2390 self.addCleanup(os.close, fd)
2391
2392 p = subprocess.Popen([sys.executable, fd_status],
2393 stdout=subprocess.PIPE, close_fds=True,
2394 preexec_fn=lambda: os.dup2(1, fd))
2395 output, ignored = p.communicate()
2396
2397 remaining_fds = set(map(int, output.split(b',')))
2398
2399 self.assertNotIn(fd, remaining_fds)
2400
Victor Stinner8f437aa2014-10-05 17:25:19 +02002401 @support.cpython_only
2402 def test_fork_exec(self):
2403 # Issue #22290: fork_exec() must not crash on memory allocation failure
2404 # or other errors
2405 import _posixsubprocess
2406 gc_enabled = gc.isenabled()
2407 try:
2408 # Use a preexec function and enable the garbage collector
2409 # to force fork_exec() to re-enable the garbage collector
2410 # on error.
2411 func = lambda: None
2412 gc.enable()
2413
Victor Stinner8f437aa2014-10-05 17:25:19 +02002414 for args, exe_list, cwd, env_list in (
2415 (123, [b"exe"], None, [b"env"]),
2416 ([b"arg"], 123, None, [b"env"]),
2417 ([b"arg"], [b"exe"], 123, [b"env"]),
2418 ([b"arg"], [b"exe"], None, 123),
2419 ):
2420 with self.assertRaises(TypeError):
2421 _posixsubprocess.fork_exec(
2422 args, exe_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002423 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02002424 -1, -1, -1, -1,
2425 1, 2, 3, 4,
2426 True, True, func)
2427 finally:
2428 if not gc_enabled:
2429 gc.disable()
2430
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002431 @support.cpython_only
2432 def test_fork_exec_sorted_fd_sanity_check(self):
2433 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
2434 import _posixsubprocess
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002435 class BadInt:
2436 first = True
2437 def __init__(self, value):
2438 self.value = value
2439 def __int__(self):
2440 if self.first:
2441 self.first = False
2442 return self.value
2443 raise ValueError
2444
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002445 gc_enabled = gc.isenabled()
2446 try:
2447 gc.enable()
2448
2449 for fds_to_keep in (
2450 (-1, 2, 3, 4, 5), # Negative number.
2451 ('str', 4), # Not an int.
2452 (18, 23, 42, 2**63), # Out of range.
2453 (5, 4), # Not sorted.
2454 (6, 7, 7, 8), # Duplicate.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002455 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002456 ):
2457 with self.assertRaises(
2458 ValueError,
2459 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
2460 _posixsubprocess.fork_exec(
2461 [b"false"], [b"false"],
2462 True, fds_to_keep, None, [b"env"],
2463 -1, -1, -1, -1,
2464 1, 2, 3, 4,
2465 True, True, None)
2466 self.assertIn('fds_to_keep', str(c.exception))
2467 finally:
2468 if not gc_enabled:
2469 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02002470
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00002471 def test_communicate_BrokenPipeError_stdin_close(self):
2472 # By not setting stdout or stderr or a timeout we force the fast path
2473 # that just calls _stdin_write() internally due to our mock.
2474 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2475 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2476 mock_proc_stdin.close.side_effect = BrokenPipeError
2477 proc.communicate() # Should swallow BrokenPipeError from close.
2478 mock_proc_stdin.close.assert_called_with()
2479
2480 def test_communicate_BrokenPipeError_stdin_write(self):
2481 # By not setting stdout or stderr or a timeout we force the fast path
2482 # that just calls _stdin_write() internally due to our mock.
2483 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2484 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2485 mock_proc_stdin.write.side_effect = BrokenPipeError
2486 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
2487 mock_proc_stdin.write.assert_called_once_with(b'stuff')
2488 mock_proc_stdin.close.assert_called_once_with()
2489
2490 def test_communicate_BrokenPipeError_stdin_flush(self):
2491 # Setting stdin and stdout forces the ._communicate() code path.
2492 # python -h exits faster than python -c pass (but spams stdout).
2493 proc = subprocess.Popen([sys.executable, '-h'],
2494 stdin=subprocess.PIPE,
2495 stdout=subprocess.PIPE)
2496 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
2497 open(os.devnull, 'wb') as dev_null:
2498 mock_proc_stdin.flush.side_effect = BrokenPipeError
2499 # because _communicate registers a selector using proc.stdin...
2500 mock_proc_stdin.fileno.return_value = dev_null.fileno()
2501 # _communicate() should swallow BrokenPipeError from flush.
2502 proc.communicate(b'stuff')
2503 mock_proc_stdin.flush.assert_called_once_with()
2504
2505 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
2506 # Setting stdin and stdout forces the ._communicate() code path.
2507 # python -h exits faster than python -c pass (but spams stdout).
2508 proc = subprocess.Popen([sys.executable, '-h'],
2509 stdin=subprocess.PIPE,
2510 stdout=subprocess.PIPE)
2511 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2512 mock_proc_stdin.close.side_effect = BrokenPipeError
2513 # _communicate() should swallow BrokenPipeError from close.
2514 proc.communicate(timeout=999)
2515 mock_proc_stdin.close.assert_called_once_with()
2516
Gregory P. Smith1fa08bc2017-01-22 22:19:38 -08002517 @unittest.skipIf(not ctypes, 'ctypes module required.')
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002518 @unittest.skipIf(not sys.executable, 'Test requires sys.executable.')
2519 def test_child_terminated_in_stopped_state(self):
2520 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
2521 PTRACE_TRACEME = 0 # From glibc and MacOS (PT_TRACE_ME).
Gregory P. Smith56bc3b72017-05-23 07:49:13 -07002522 libc_name = ctypes.util.find_library('c')
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002523 libc = ctypes.CDLL(libc_name)
2524 if not hasattr(libc, 'ptrace'):
2525 raise unittest.SkipTest('ptrace() required.')
2526 test_ptrace = subprocess.Popen(
2527 [sys.executable, '-c', """if True:
2528 import ctypes
2529 libc = ctypes.CDLL({libc_name!r})
2530 libc.ptrace({PTRACE_TRACEME}, 0, 0)
2531 """.format(libc_name=libc_name, PTRACE_TRACEME=PTRACE_TRACEME)
2532 ])
2533 if test_ptrace.wait() != 0:
2534 raise unittest.SkipTest('ptrace() failed - unable to test.')
2535 child = subprocess.Popen(
2536 [sys.executable, '-c', """if True:
Gregory P. Smith56bc3b72017-05-23 07:49:13 -07002537 import ctypes, faulthandler
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002538 libc = ctypes.CDLL({libc_name!r})
2539 libc.ptrace({PTRACE_TRACEME}, 0, 0)
Gregory P. Smith56bc3b72017-05-23 07:49:13 -07002540 faulthandler._sigsegv() # Crash the process.
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002541 """.format(libc_name=libc_name, PTRACE_TRACEME=PTRACE_TRACEME)
2542 ])
2543 try:
2544 returncode = child.wait()
2545 except Exception as e:
2546 child.kill() # Clean up the hung stopped process.
2547 raise e
2548 self.assertNotEqual(0, returncode)
2549 self.assertLess(returncode, 0) # signal death, likely SIGSEGV.
2550
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002551
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002552@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00002553class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002554
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002555 def test_startupinfo(self):
2556 # startupinfo argument
2557 # We uses hardcoded constants, because we do not want to
2558 # depend on win32all.
2559 STARTF_USESHOWWINDOW = 1
2560 SW_MAXIMIZE = 3
2561 startupinfo = subprocess.STARTUPINFO()
2562 startupinfo.dwFlags = STARTF_USESHOWWINDOW
2563 startupinfo.wShowWindow = SW_MAXIMIZE
2564 # Since Python is a console process, it won't be affected
2565 # by wShowWindow, but the argument should be silently
2566 # ignored
2567 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002568 startupinfo=startupinfo)
2569
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05302570 def test_startupinfo_keywords(self):
2571 # startupinfo argument
2572 # We use hardcoded constants, because we do not want to
2573 # depend on win32all.
2574 STARTF_USERSHOWWINDOW = 1
2575 SW_MAXIMIZE = 3
2576 startupinfo = subprocess.STARTUPINFO(
2577 dwFlags=STARTF_USERSHOWWINDOW,
2578 wShowWindow=SW_MAXIMIZE
2579 )
2580 # Since Python is a console process, it won't be affected
2581 # by wShowWindow, but the argument should be silently
2582 # ignored
2583 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
2584 startupinfo=startupinfo)
2585
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002586 def test_creationflags(self):
2587 # creationflags argument
2588 CREATE_NEW_CONSOLE = 16
2589 sys.stderr.write(" a DOS box should flash briefly ...\n")
2590 subprocess.call(sys.executable +
2591 ' -c "import time; time.sleep(0.25)"',
2592 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002593
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002594 def test_invalid_args(self):
2595 # invalid arguments should raise ValueError
2596 self.assertRaises(ValueError, subprocess.call,
2597 [sys.executable, "-c",
2598 "import sys; sys.exit(47)"],
2599 preexec_fn=lambda: 1)
2600 self.assertRaises(ValueError, subprocess.call,
2601 [sys.executable, "-c",
2602 "import sys; sys.exit(47)"],
2603 stdout=subprocess.PIPE,
2604 close_fds=True)
2605
2606 def test_close_fds(self):
2607 # close file descriptors
2608 rc = subprocess.call([sys.executable, "-c",
2609 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002610 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002611 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002612
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002613 def test_shell_sequence(self):
2614 # Run command through the shell (sequence)
2615 newenv = os.environ.copy()
2616 newenv["FRUIT"] = "physalis"
2617 p = subprocess.Popen(["set"], shell=1,
2618 stdout=subprocess.PIPE,
2619 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002620 with p:
2621 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00002622
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002623 def test_shell_string(self):
2624 # Run command through the shell (string)
2625 newenv = os.environ.copy()
2626 newenv["FRUIT"] = "physalis"
2627 p = subprocess.Popen("set", shell=1,
2628 stdout=subprocess.PIPE,
2629 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002630 with p:
2631 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002632
Steve Dower050acae2016-09-06 20:16:17 -07002633 def test_shell_encodings(self):
2634 # Run command through the shell (string)
2635 for enc in ['ansi', 'oem']:
2636 newenv = os.environ.copy()
2637 newenv["FRUIT"] = "physalis"
2638 p = subprocess.Popen("set", shell=1,
2639 stdout=subprocess.PIPE,
2640 env=newenv,
2641 encoding=enc)
2642 with p:
2643 self.assertIn("physalis", p.stdout.read(), enc)
2644
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002645 def test_call_string(self):
2646 # call() function with string argument on Windows
2647 rc = subprocess.call(sys.executable +
2648 ' -c "import sys; sys.exit(47)"')
2649 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002650
Florent Xicluna4886d242010-03-08 13:27:26 +00002651 def _kill_process(self, method, *args):
2652 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00002653 p = subprocess.Popen([sys.executable, "-c", """if 1:
2654 import sys, time
2655 sys.stdout.write('x\\n')
2656 sys.stdout.flush()
2657 time.sleep(30)
2658 """],
2659 stdin=subprocess.PIPE,
2660 stdout=subprocess.PIPE,
2661 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002662 with p:
2663 # Wait for the interpreter to be completely initialized before
2664 # sending any signal.
2665 p.stdout.read(1)
2666 getattr(p, method)(*args)
2667 _, stderr = p.communicate()
2668 self.assertStderrEqual(stderr, b'')
2669 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00002670 self.assertNotEqual(returncode, 0)
2671
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002672 def _kill_dead_process(self, method, *args):
2673 p = subprocess.Popen([sys.executable, "-c", """if 1:
2674 import sys, time
2675 sys.stdout.write('x\\n')
2676 sys.stdout.flush()
2677 sys.exit(42)
2678 """],
2679 stdin=subprocess.PIPE,
2680 stdout=subprocess.PIPE,
2681 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002682 with p:
2683 # Wait for the interpreter to be completely initialized before
2684 # sending any signal.
2685 p.stdout.read(1)
2686 # The process should end after this
2687 time.sleep(1)
2688 # This shouldn't raise even though the child is now dead
2689 getattr(p, method)(*args)
2690 _, stderr = p.communicate()
2691 self.assertStderrEqual(stderr, b'')
2692 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002693 self.assertEqual(rc, 42)
2694
Florent Xicluna4886d242010-03-08 13:27:26 +00002695 def test_send_signal(self):
2696 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00002697
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002698 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002699 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00002700
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002701 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002702 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00002703
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002704 def test_send_signal_dead(self):
2705 self._kill_dead_process('send_signal', signal.SIGTERM)
2706
2707 def test_kill_dead(self):
2708 self._kill_dead_process('kill')
2709
2710 def test_terminate_dead(self):
2711 self._kill_dead_process('terminate')
2712
Martin Panter23172bd2016-04-16 11:28:10 +00002713class MiscTests(unittest.TestCase):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002714 def test_getoutput(self):
2715 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
2716 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
2717 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00002718
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002719 # we use mkdtemp in the next line to create an empty directory
2720 # under our exclusive control; from that, we can invent a pathname
2721 # that we _know_ won't exist. This is guaranteed to fail.
2722 dir = None
2723 try:
2724 dir = tempfile.mkdtemp()
2725 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00002726 status, output = subprocess.getstatusoutput(
2727 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002728 self.assertNotEqual(status, 0)
2729 finally:
2730 if dir is not None:
2731 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00002732
Gregory P. Smithace55862015-04-07 15:57:54 -07002733 def test__all__(self):
2734 """Ensure that __all__ is populated properly."""
Martin Panter528619b2016-04-16 23:42:37 +00002735 intentionally_excluded = {"list2cmdline", "Handle"}
Gregory P. Smithace55862015-04-07 15:57:54 -07002736 exported = set(subprocess.__all__)
2737 possible_exports = set()
2738 import types
2739 for name, value in subprocess.__dict__.items():
2740 if name.startswith('_'):
2741 continue
2742 if isinstance(value, (types.ModuleType,)):
2743 continue
2744 possible_exports.add(name)
2745 self.assertEqual(exported, possible_exports - intentionally_excluded)
2746
2747
Martin Panter23172bd2016-04-16 11:28:10 +00002748@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
2749 "Test needs selectors.PollSelector")
2750class ProcessTestCaseNoPoll(ProcessTestCase):
2751 def setUp(self):
2752 self.orig_selector = subprocess._PopenSelector
2753 subprocess._PopenSelector = selectors.SelectSelector
2754 ProcessTestCase.setUp(self)
2755
2756 def tearDown(self):
2757 subprocess._PopenSelector = self.orig_selector
2758 ProcessTestCase.tearDown(self)
2759
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002760
Tim Golden126c2962010-08-11 14:20:40 +00002761@unittest.skipUnless(mswindows, "Windows-specific tests")
2762class CommandsWithSpaces (BaseTestCase):
2763
2764 def setUp(self):
2765 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03002766 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00002767 self.fname = fname.lower ()
2768 os.write(f, b"import sys;"
2769 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
2770 )
2771 os.close(f)
2772
2773 def tearDown(self):
2774 os.remove(self.fname)
2775 super().tearDown()
2776
2777 def with_spaces(self, *args, **kwargs):
2778 kwargs['stdout'] = subprocess.PIPE
2779 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02002780 with p:
2781 self.assertEqual(
2782 p.stdout.read ().decode("mbcs"),
2783 "2 [%r, 'ab cd']" % self.fname
2784 )
Tim Golden126c2962010-08-11 14:20:40 +00002785
2786 def test_shell_string_with_spaces(self):
2787 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002788 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2789 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002790
2791 def test_shell_sequence_with_spaces(self):
2792 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002793 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002794
2795 def test_noshell_string_with_spaces(self):
2796 # call() function with string argument with spaces on Windows
2797 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2798 "ab cd"))
2799
2800 def test_noshell_sequence_with_spaces(self):
2801 # call() function with sequence argument with spaces on Windows
2802 self.with_spaces([sys.executable, self.fname, "ab cd"])
2803
Brian Curtin79cdb662010-12-03 02:46:02 +00002804
Georg Brandla86b2622012-02-20 21:34:57 +01002805class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00002806
2807 def test_pipe(self):
2808 with subprocess.Popen([sys.executable, "-c",
2809 "import sys;"
2810 "sys.stdout.write('stdout');"
2811 "sys.stderr.write('stderr');"],
2812 stdout=subprocess.PIPE,
2813 stderr=subprocess.PIPE) as proc:
2814 self.assertEqual(proc.stdout.read(), b"stdout")
2815 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2816
2817 self.assertTrue(proc.stdout.closed)
2818 self.assertTrue(proc.stderr.closed)
2819
2820 def test_returncode(self):
2821 with subprocess.Popen([sys.executable, "-c",
2822 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002823 pass
2824 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002825 self.assertEqual(proc.returncode, 100)
2826
2827 def test_communicate_stdin(self):
2828 with subprocess.Popen([sys.executable, "-c",
2829 "import sys;"
2830 "sys.exit(sys.stdin.read() == 'context')"],
2831 stdin=subprocess.PIPE) as proc:
2832 proc.communicate(b"context")
2833 self.assertEqual(proc.returncode, 1)
2834
2835 def test_invalid_args(self):
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +01002836 with self.assertRaises((FileNotFoundError, PermissionError)) as c:
Brian Curtin79cdb662010-12-03 02:46:02 +00002837 with subprocess.Popen(['nonexisting_i_hope'],
2838 stdout=subprocess.PIPE,
2839 stderr=subprocess.PIPE) as proc:
2840 pass
2841
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002842 def test_broken_pipe_cleanup(self):
2843 """Broken pipe error should not prevent wait() (Issue 21619)"""
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002844 proc = subprocess.Popen([sys.executable, '-c', 'pass'],
Victor Stinner20f4bd42015-03-05 02:38:41 +01002845 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01002846 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002847 proc = proc.__enter__()
2848 # Prepare to send enough data to overflow any OS pipe buffering and
2849 # guarantee a broken pipe error. Data is held in BufferedWriter
2850 # buffer until closed.
2851 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002852 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002853 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02002854 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002855 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002856 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002857
Brian Curtin79cdb662010-12-03 02:46:02 +00002858
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002859if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002860 unittest.main()