blob: d8d6d82713cdeda296198d329007491bfbe560cb [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
24
25try:
Antoine Pitroua8392712013-08-30 23:38:13 +020026 import threading
27except ImportError:
28 threading = None
Benjamin Peterson964561b2011-12-10 12:31:42 -050029
Steve Dower22d06982016-09-06 19:38:15 -070030if support.PGO:
31 raise unittest.SkipTest("test is not helpful for PGO")
32
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000033mswindows = (sys.platform == "win32")
34
35#
36# Depends on the following external programs: Python
37#
38
39if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000040 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
41 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000042else:
43 SETBINARY = ''
44
Florent Xiclunab1e94e82010-02-27 22:12:37 +000045
Florent Xiclunac049d872010-03-27 22:47:23 +000046class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000047 def setUp(self):
48 # Try to minimize the number of children we have so this test
49 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000050 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000051
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000052 def tearDown(self):
53 for inst in subprocess._active:
54 inst.wait()
55 subprocess._cleanup()
56 self.assertFalse(subprocess._active, "subprocess._active not empty")
57
Florent Xiclunab1e94e82010-02-27 22:12:37 +000058 def assertStderrEqual(self, stderr, expected, msg=None):
59 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
60 # shutdown time. That frustrates tests trying to check stderr produced
61 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000062 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040063 # strip_python_stderr also strips whitespace, so we do too.
64 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000065 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000066
Florent Xiclunac049d872010-03-27 22:47:23 +000067
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080068class PopenTestException(Exception):
69 pass
70
71
72class PopenExecuteChildRaises(subprocess.Popen):
73 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
74 _execute_child fails.
75 """
76 def _execute_child(self, *args, **kwargs):
77 raise PopenTestException("Forced Exception for Test")
78
79
Florent Xiclunac049d872010-03-27 22:47:23 +000080class ProcessTestCase(BaseTestCase):
81
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070082 def test_io_buffered_by_default(self):
83 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
84 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
85 stderr=subprocess.PIPE)
86 try:
87 self.assertIsInstance(p.stdin, io.BufferedIOBase)
88 self.assertIsInstance(p.stdout, io.BufferedIOBase)
89 self.assertIsInstance(p.stderr, io.BufferedIOBase)
90 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -070091 p.stdin.close()
92 p.stdout.close()
93 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070094 p.wait()
95
96 def test_io_unbuffered_works(self):
97 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
98 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
99 stderr=subprocess.PIPE, bufsize=0)
100 try:
101 self.assertIsInstance(p.stdin, io.RawIOBase)
102 self.assertIsInstance(p.stdout, io.RawIOBase)
103 self.assertIsInstance(p.stderr, io.RawIOBase)
104 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700105 p.stdin.close()
106 p.stdout.close()
107 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700108 p.wait()
109
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000110 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000111 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000112 rc = subprocess.call([sys.executable, "-c",
113 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000114 self.assertEqual(rc, 47)
115
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400116 def test_call_timeout(self):
117 # call() function with timeout argument; we want to test that the child
118 # process gets killed when the timeout expires. If the child isn't
119 # killed, this call will deadlock since subprocess.call waits for the
120 # child.
121 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
122 [sys.executable, "-c", "while True: pass"],
123 timeout=0.1)
124
Peter Astrand454f7672005-01-01 09:36:35 +0000125 def test_check_call_zero(self):
126 # check_call() function with zero return code
127 rc = subprocess.check_call([sys.executable, "-c",
128 "import sys; sys.exit(0)"])
129 self.assertEqual(rc, 0)
130
131 def test_check_call_nonzero(self):
132 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000133 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000134 subprocess.check_call([sys.executable, "-c",
135 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000136 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000137
Georg Brandlf9734072008-12-07 15:30:06 +0000138 def test_check_output(self):
139 # check_output() function with zero return code
140 output = subprocess.check_output(
141 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000142 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000143
144 def test_check_output_nonzero(self):
145 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000146 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000147 subprocess.check_output(
148 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000149 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000150
151 def test_check_output_stderr(self):
152 # check_output() function stderr redirected to stdout
153 output = subprocess.check_output(
154 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
155 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000156 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000157
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300158 def test_check_output_stdin_arg(self):
159 # check_output() can be called with stdin set to a file
160 tf = tempfile.TemporaryFile()
161 self.addCleanup(tf.close)
162 tf.write(b'pear')
163 tf.seek(0)
164 output = subprocess.check_output(
165 [sys.executable, "-c",
166 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
167 stdin=tf)
168 self.assertIn(b'PEAR', output)
169
170 def test_check_output_input_arg(self):
171 # check_output() can be called with input set to a string
172 output = subprocess.check_output(
173 [sys.executable, "-c",
174 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
175 input=b'pear')
176 self.assertIn(b'PEAR', output)
177
Georg Brandlf9734072008-12-07 15:30:06 +0000178 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300179 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000180 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000181 output = subprocess.check_output(
182 [sys.executable, "-c", "print('will not be run')"],
183 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000184 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000185 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000186
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300187 def test_check_output_stdin_with_input_arg(self):
188 # check_output() refuses to accept 'stdin' with 'input'
189 tf = tempfile.TemporaryFile()
190 self.addCleanup(tf.close)
191 tf.write(b'pear')
192 tf.seek(0)
193 with self.assertRaises(ValueError) as c:
194 output = subprocess.check_output(
195 [sys.executable, "-c", "print('will not be run')"],
196 stdin=tf, input=b'hare')
197 self.fail("Expected ValueError when stdin and input args supplied.")
198 self.assertIn('stdin', c.exception.args[0])
199 self.assertIn('input', c.exception.args[0])
200
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400201 def test_check_output_timeout(self):
202 # check_output() function with timeout arg
203 with self.assertRaises(subprocess.TimeoutExpired) as c:
204 output = subprocess.check_output(
205 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200206 "import sys, time\n"
207 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400208 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200209 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400210 # Some heavily loaded buildbots (sparc Debian 3.x) require
211 # this much time to start and print.
212 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400213 self.fail("Expected TimeoutExpired.")
214 self.assertEqual(c.exception.output, b'BDFL')
215
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000216 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000217 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000218 newenv = os.environ.copy()
219 newenv["FRUIT"] = "banana"
220 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000221 'import sys, os;'
222 'sys.exit(os.getenv("FRUIT")=="banana")'],
223 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000224 self.assertEqual(rc, 1)
225
Victor Stinner87b9bc32011-06-01 00:57:47 +0200226 def test_invalid_args(self):
227 # Popen() called with invalid arguments should raise TypeError
228 # but Popen.__del__ should not complain (issue #12085)
229 with support.captured_stderr() as s:
230 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
231 argcount = subprocess.Popen.__init__.__code__.co_argcount
232 too_many_args = [0] * (argcount + 1)
233 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
234 self.assertEqual(s.getvalue(), '')
235
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000236 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000237 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000238 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000239 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000240 self.addCleanup(p.stdout.close)
241 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000242 p.wait()
243 self.assertEqual(p.stdin, None)
244
245 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200246 # .stdout is None when not redirected, and the child's stdout will
247 # be inherited from the parent. In order to test this we run a
248 # subprocess in a subprocess:
249 # this_test
250 # \-- subprocess created by this test (parent)
251 # \-- subprocess created by the parent subprocess (child)
252 # The parent doesn't specify stdout, so the child will use the
253 # parent's stdout. This test checks that the message printed by the
254 # child goes to the parent stdout. The parent also checks that the
255 # child's stdout is None. See #11963.
256 code = ('import sys; from subprocess import Popen, PIPE;'
257 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
258 ' stdin=PIPE, stderr=PIPE);'
259 'p.wait(); assert p.stdout is None;')
260 p = subprocess.Popen([sys.executable, "-c", code],
261 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
262 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000263 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200264 out, err = p.communicate()
265 self.assertEqual(p.returncode, 0, err)
266 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000267
268 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000269 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000270 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000271 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000272 self.addCleanup(p.stdout.close)
273 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000274 p.wait()
275 self.assertEqual(p.stderr, None)
276
Chris Jerdonek776cb192012-10-08 15:56:43 -0700277 def _assert_python(self, pre_args, **kwargs):
278 # We include sys.exit() to prevent the test runner from hanging
279 # whenever python is found.
280 args = pre_args + ["import sys; sys.exit(47)"]
281 p = subprocess.Popen(args, **kwargs)
282 p.wait()
283 self.assertEqual(47, p.returncode)
284
285 def test_executable(self):
286 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700287 #
288 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
289 # determine where its standard library is, so we need the directory
290 # of args[0] to be valid for the Popen() call to Python to succeed.
291 # See also issue #16170 and issue #7774.
292 doesnotexist = os.path.join(os.path.dirname(sys.executable),
293 "doesnotexist")
294 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700295
296 def test_executable_takes_precedence(self):
297 # Check that the executable argument takes precedence over args[0].
298 #
299 # Verify first that the call succeeds without the executable arg.
300 pre_args = [sys.executable, "-c"]
301 self._assert_python(pre_args)
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +0100302 self.assertRaises((FileNotFoundError, PermissionError),
303 self._assert_python, pre_args,
Chris Jerdonek776cb192012-10-08 15:56:43 -0700304 executable="doesnotexist")
305
306 @unittest.skipIf(mswindows, "executable argument replaces shell")
307 def test_executable_replaces_shell(self):
308 # Check that the executable argument replaces the default shell
309 # when shell=True.
310 self._assert_python([], executable=sys.executable, shell=True)
311
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700312 # For use in the test_cwd* tests below.
313 def _normalize_cwd(self, cwd):
314 # Normalize an expected cwd (for Tru64 support).
315 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
316 # strings. See bug #1063571.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300317 with support.change_cwd(cwd):
318 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700319
320 # For use in the test_cwd* tests below.
321 def _split_python_path(self):
322 # Return normalized (python_dir, python_base).
323 python_path = os.path.realpath(sys.executable)
324 return os.path.split(python_path)
325
326 # For use in the test_cwd* tests below.
327 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
328 # Invoke Python via Popen, and assert that (1) the call succeeds,
329 # and that (2) the current working directory of the child process
330 # matches *expected_cwd*.
331 p = subprocess.Popen([python_arg, "-c",
332 "import os, sys; "
333 "sys.stdout.write(os.getcwd()); "
334 "sys.exit(47)"],
335 stdout=subprocess.PIPE,
336 **kwargs)
337 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000338 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700339 self.assertEqual(47, p.returncode)
340 normcase = os.path.normcase
341 self.assertEqual(normcase(expected_cwd),
342 normcase(p.stdout.read().decode("utf-8")))
343
344 def test_cwd(self):
345 # Check that cwd changes the cwd for the child process.
346 temp_dir = tempfile.gettempdir()
347 temp_dir = self._normalize_cwd(temp_dir)
348 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
349
Berker Peksag6b810032017-02-26 20:38:31 +0300350 def test_cwd_with_pathlike(self):
351 temp_dir = tempfile.gettempdir()
352 temp_dir = self._normalize_cwd(temp_dir)
353
354 class _PathLikeObj:
355 def __fspath__(self):
356 return temp_dir
357
358 self._assert_cwd(temp_dir, sys.executable, cwd=_PathLikeObj())
359
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700360 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700361 def test_cwd_with_relative_arg(self):
362 # Check that Popen looks for args[0] relative to cwd if args[0]
363 # is relative.
364 python_dir, python_base = self._split_python_path()
365 rel_python = os.path.join(os.curdir, python_base)
366 with support.temp_cwd() as wrong_dir:
367 # Before calling with the correct cwd, confirm that the call fails
368 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700369 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700370 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700371 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700372 [rel_python], cwd=wrong_dir)
373 python_dir = self._normalize_cwd(python_dir)
374 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
375
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700376 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700377 def test_cwd_with_relative_executable(self):
378 # Check that Popen looks for executable relative to cwd if executable
379 # is relative (and that executable takes precedence over args[0]).
380 python_dir, python_base = self._split_python_path()
381 rel_python = os.path.join(os.curdir, python_base)
382 doesntexist = "somethingyoudonthave"
383 with support.temp_cwd() as wrong_dir:
384 # Before calling with the correct cwd, confirm that the call fails
385 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700386 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700387 [doesntexist], executable=rel_python)
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,
390 cwd=wrong_dir)
391 python_dir = self._normalize_cwd(python_dir)
392 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
393 cwd=python_dir)
394
395 def test_cwd_with_absolute_arg(self):
396 # Check that Popen can find the executable when the cwd is wrong
397 # if args[0] is an absolute path.
398 python_dir, python_base = self._split_python_path()
399 abs_python = os.path.join(python_dir, python_base)
400 rel_python = os.path.join(os.curdir, python_base)
Berker Peksagce643912015-05-06 06:33:17 +0300401 with support.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700402 # Before calling with an absolute path, confirm that using a
403 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700404 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700405 [rel_python], cwd=wrong_dir)
406 wrong_dir = self._normalize_cwd(wrong_dir)
407 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
408
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100409 @unittest.skipIf(sys.base_prefix != sys.prefix,
410 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000411 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700412 python_dir, python_base = self._split_python_path()
413 python_dir = self._normalize_cwd(python_dir)
414 self._assert_cwd(python_dir, "somethingyoudonthave",
415 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000416
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100417 @unittest.skipIf(sys.base_prefix != sys.prefix,
418 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000419 @unittest.skipIf(sysconfig.is_python_build(),
420 "need an installed Python. See #7774")
421 def test_executable_without_cwd(self):
422 # For a normal installation, it should work without 'cwd'
423 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700424 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
425 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000426
427 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000428 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000429 p = subprocess.Popen([sys.executable, "-c",
430 'import sys; sys.exit(sys.stdin.read() == "pear")'],
431 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000432 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000433 p.stdin.close()
434 p.wait()
435 self.assertEqual(p.returncode, 1)
436
437 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000438 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000439 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000440 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000441 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000442 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000443 os.lseek(d, 0, 0)
444 p = subprocess.Popen([sys.executable, "-c",
445 'import sys; sys.exit(sys.stdin.read() == "pear")'],
446 stdin=d)
447 p.wait()
448 self.assertEqual(p.returncode, 1)
449
450 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000451 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000452 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000453 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000454 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000455 tf.seek(0)
456 p = subprocess.Popen([sys.executable, "-c",
457 'import sys; sys.exit(sys.stdin.read() == "pear")'],
458 stdin=tf)
459 p.wait()
460 self.assertEqual(p.returncode, 1)
461
462 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000463 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000464 p = subprocess.Popen([sys.executable, "-c",
465 'import sys; sys.stdout.write("orange")'],
466 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200467 with p:
468 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000469
470 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000471 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000472 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000473 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000474 d = tf.fileno()
475 p = subprocess.Popen([sys.executable, "-c",
476 'import sys; sys.stdout.write("orange")'],
477 stdout=d)
478 p.wait()
479 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000480 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000481
482 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000483 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000484 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000485 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000486 p = subprocess.Popen([sys.executable, "-c",
487 'import sys; sys.stdout.write("orange")'],
488 stdout=tf)
489 p.wait()
490 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000491 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000492
493 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000494 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000495 p = subprocess.Popen([sys.executable, "-c",
496 'import sys; sys.stderr.write("strawberry")'],
497 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200498 with p:
499 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000500
501 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000502 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000503 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000504 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000505 d = tf.fileno()
506 p = subprocess.Popen([sys.executable, "-c",
507 'import sys; sys.stderr.write("strawberry")'],
508 stderr=d)
509 p.wait()
510 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000511 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000512
513 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000514 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000515 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000516 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000517 p = subprocess.Popen([sys.executable, "-c",
518 'import sys; sys.stderr.write("strawberry")'],
519 stderr=tf)
520 p.wait()
521 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000522 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000523
Martin Panterc7635892016-05-13 01:54:44 +0000524 def test_stderr_redirect_with_no_stdout_redirect(self):
525 # test stderr=STDOUT while stdout=None (not set)
526
527 # - grandchild prints to stderr
528 # - child redirects grandchild's stderr to its stdout
529 # - the parent should get grandchild's stderr in child's stdout
530 p = subprocess.Popen([sys.executable, "-c",
531 'import sys, subprocess;'
532 'rc = subprocess.call([sys.executable, "-c",'
533 ' "import sys;"'
534 ' "sys.stderr.write(\'42\')"],'
535 ' stderr=subprocess.STDOUT);'
536 'sys.exit(rc)'],
537 stdout=subprocess.PIPE,
538 stderr=subprocess.PIPE)
539 stdout, stderr = p.communicate()
540 #NOTE: stdout should get stderr from grandchild
541 self.assertStderrEqual(stdout, b'42')
542 self.assertStderrEqual(stderr, b'') # should be empty
543 self.assertEqual(p.returncode, 0)
544
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000545 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000546 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000547 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000548 'import sys;'
549 'sys.stdout.write("apple");'
550 'sys.stdout.flush();'
551 'sys.stderr.write("orange")'],
552 stdout=subprocess.PIPE,
553 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200554 with p:
555 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000556
557 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000558 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000559 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000560 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000561 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000562 'import sys;'
563 'sys.stdout.write("apple");'
564 'sys.stdout.flush();'
565 'sys.stderr.write("orange")'],
566 stdout=tf,
567 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000568 p.wait()
569 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000570 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000571
Thomas Wouters89f507f2006-12-13 04:49:30 +0000572 def test_stdout_filedes_of_stdout(self):
573 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200574 # To avoid printing the text on stdout, we do something similar to
575 # test_stdout_none (see above). The parent subprocess calls the child
576 # subprocess passing stdout=1, and this test uses stdout=PIPE in
577 # order to capture and check the output of the parent. See #11963.
578 code = ('import sys, subprocess; '
579 'rc = subprocess.call([sys.executable, "-c", '
580 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
581 'b\'test with stdout=1\'))"], stdout=1); '
582 'assert rc == 18')
583 p = subprocess.Popen([sys.executable, "-c", code],
584 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
585 self.addCleanup(p.stdout.close)
586 self.addCleanup(p.stderr.close)
587 out, err = p.communicate()
588 self.assertEqual(p.returncode, 0, err)
589 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000590
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200591 def test_stdout_devnull(self):
592 p = subprocess.Popen([sys.executable, "-c",
593 'for i in range(10240):'
594 'print("x" * 1024)'],
595 stdout=subprocess.DEVNULL)
596 p.wait()
597 self.assertEqual(p.stdout, None)
598
599 def test_stderr_devnull(self):
600 p = subprocess.Popen([sys.executable, "-c",
601 'import sys\n'
602 'for i in range(10240):'
603 'sys.stderr.write("x" * 1024)'],
604 stderr=subprocess.DEVNULL)
605 p.wait()
606 self.assertEqual(p.stderr, None)
607
608 def test_stdin_devnull(self):
609 p = subprocess.Popen([sys.executable, "-c",
610 'import sys;'
611 'sys.stdin.read(1)'],
612 stdin=subprocess.DEVNULL)
613 p.wait()
614 self.assertEqual(p.stdin, None)
615
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000616 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000617 newenv = os.environ.copy()
618 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200619 with subprocess.Popen([sys.executable, "-c",
620 'import sys,os;'
621 'sys.stdout.write(os.getenv("FRUIT"))'],
622 stdout=subprocess.PIPE,
623 env=newenv) as p:
624 stdout, stderr = p.communicate()
625 self.assertEqual(stdout, b"orange")
626
Victor Stinner62d51182011-06-23 01:02:25 +0200627 # Windows requires at least the SYSTEMROOT environment variable to start
628 # Python
629 @unittest.skipIf(sys.platform == 'win32',
630 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200631 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200632 'the python library cannot be loaded '
633 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200634 def test_empty_env(self):
635 with subprocess.Popen([sys.executable, "-c",
636 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200637 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200638 stdout=subprocess.PIPE,
639 env={}) as p:
640 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200641 self.assertIn(stdout.strip(),
642 (b"[]",
643 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
644 # environment
645 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000646
Peter Astrandcbac93c2005-03-03 20:24:28 +0000647 def test_communicate_stdin(self):
648 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000649 'import sys;'
650 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000651 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000652 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000653 self.assertEqual(p.returncode, 1)
654
655 def test_communicate_stdout(self):
656 p = subprocess.Popen([sys.executable, "-c",
657 'import sys; sys.stdout.write("pineapple")'],
658 stdout=subprocess.PIPE)
659 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000660 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000661 self.assertEqual(stderr, None)
662
663 def test_communicate_stderr(self):
664 p = subprocess.Popen([sys.executable, "-c",
665 'import sys; sys.stderr.write("pineapple")'],
666 stderr=subprocess.PIPE)
667 (stdout, stderr) = p.communicate()
668 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000669 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000670
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000671 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000672 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000673 'import sys,os;'
674 'sys.stderr.write("pineapple");'
675 'sys.stdout.write(sys.stdin.read())'],
676 stdin=subprocess.PIPE,
677 stdout=subprocess.PIPE,
678 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000679 self.addCleanup(p.stdout.close)
680 self.addCleanup(p.stderr.close)
681 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000682 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000683 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000684 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000685
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400686 def test_communicate_timeout(self):
687 p = subprocess.Popen([sys.executable, "-c",
688 'import sys,os,time;'
689 'sys.stderr.write("pineapple\\n");'
690 'time.sleep(1);'
691 'sys.stderr.write("pear\\n");'
692 'sys.stdout.write(sys.stdin.read())'],
693 universal_newlines=True,
694 stdin=subprocess.PIPE,
695 stdout=subprocess.PIPE,
696 stderr=subprocess.PIPE)
697 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
698 timeout=0.3)
699 # Make sure we can keep waiting for it, and that we get the whole output
700 # after it completes.
701 (stdout, stderr) = p.communicate()
702 self.assertEqual(stdout, "banana")
703 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
704
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700705 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200706 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400707 p = subprocess.Popen([sys.executable, "-c",
708 'import sys,os,time;'
709 'sys.stdout.write("a" * (64 * 1024));'
710 'time.sleep(0.2);'
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 stdout=subprocess.PIPE)
717 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
718 (stdout, _) = p.communicate()
719 self.assertEqual(len(stdout), 4 * 64 * 1024)
720
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000721 # Test for the fd leak reported in http://bugs.python.org/issue2791.
722 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000723 for stdin_pipe in (False, True):
724 for stdout_pipe in (False, True):
725 for stderr_pipe in (False, True):
726 options = {}
727 if stdin_pipe:
728 options['stdin'] = subprocess.PIPE
729 if stdout_pipe:
730 options['stdout'] = subprocess.PIPE
731 if stderr_pipe:
732 options['stderr'] = subprocess.PIPE
733 if not options:
734 continue
735 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
736 p.communicate()
737 if p.stdin is not None:
738 self.assertTrue(p.stdin.closed)
739 if p.stdout is not None:
740 self.assertTrue(p.stdout.closed)
741 if p.stderr is not None:
742 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000743
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000744 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000745 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000746 p = subprocess.Popen([sys.executable, "-c",
747 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000748 (stdout, stderr) = p.communicate()
749 self.assertEqual(stdout, None)
750 self.assertEqual(stderr, None)
751
752 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000753 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000754 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000755 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000756 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000757 os.close(x)
758 os.close(y)
759 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000760 'import sys,os;'
761 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200762 'sys.stderr.write("x" * %d);'
763 'sys.stdout.write(sys.stdin.read())' %
764 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000765 stdin=subprocess.PIPE,
766 stdout=subprocess.PIPE,
767 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000768 self.addCleanup(p.stdout.close)
769 self.addCleanup(p.stderr.close)
770 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200771 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000772 (stdout, stderr) = p.communicate(string_to_write)
773 self.assertEqual(stdout, string_to_write)
774
775 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000776 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000777 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000778 'import sys,os;'
779 'sys.stdout.write(sys.stdin.read())'],
780 stdin=subprocess.PIPE,
781 stdout=subprocess.PIPE,
782 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000783 self.addCleanup(p.stdout.close)
784 self.addCleanup(p.stderr.close)
785 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000786 p.stdin.write(b"banana")
787 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000788 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000789 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000790
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000791 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000792 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000793 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200794 'buf = sys.stdout.buffer;'
795 'buf.write(sys.stdin.readline().encode());'
796 'buf.flush();'
797 'buf.write(b"line2\\n");'
798 'buf.flush();'
799 'buf.write(sys.stdin.read().encode());'
800 'buf.flush();'
801 'buf.write(b"line4\\n");'
802 'buf.flush();'
803 'buf.write(b"line5\\r\\n");'
804 'buf.flush();'
805 'buf.write(b"line6\\r");'
806 'buf.flush();'
807 'buf.write(b"\\nline7");'
808 'buf.flush();'
809 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200810 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000811 stdout=subprocess.PIPE,
812 universal_newlines=1)
Victor Stinner7438c612016-05-20 12:43:15 +0200813 with p:
814 p.stdin.write("line1\n")
815 p.stdin.flush()
816 self.assertEqual(p.stdout.readline(), "line1\n")
817 p.stdin.write("line3\n")
818 p.stdin.close()
819 self.addCleanup(p.stdout.close)
820 self.assertEqual(p.stdout.readline(),
821 "line2\n")
822 self.assertEqual(p.stdout.read(6),
823 "line3\n")
824 self.assertEqual(p.stdout.read(),
825 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000826
827 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000828 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000829 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000830 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200831 'buf = sys.stdout.buffer;'
832 'buf.write(b"line2\\n");'
833 'buf.flush();'
834 'buf.write(b"line4\\n");'
835 'buf.flush();'
836 'buf.write(b"line5\\r\\n");'
837 'buf.flush();'
838 'buf.write(b"line6\\r");'
839 'buf.flush();'
840 'buf.write(b"\\nline7");'
841 'buf.flush();'
842 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200843 stderr=subprocess.PIPE,
844 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000845 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000846 self.addCleanup(p.stdout.close)
847 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000848 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200849 self.assertEqual(stdout,
850 "line2\nline4\nline5\nline6\nline7\nline8")
851
852 def test_universal_newlines_communicate_stdin(self):
853 # universal newlines through communicate(), with only stdin
854 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300855 'import sys,os;' + SETBINARY + textwrap.dedent('''
856 s = sys.stdin.readline()
857 assert s == "line1\\n", repr(s)
858 s = sys.stdin.read()
859 assert s == "line3\\n", repr(s)
860 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200861 stdin=subprocess.PIPE,
862 universal_newlines=1)
863 (stdout, stderr) = p.communicate("line1\nline3\n")
864 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000865
Andrew Svetlovf3765072012-08-14 18:35:17 +0300866 def test_universal_newlines_communicate_input_none(self):
867 # Test communicate(input=None) with universal newlines.
868 #
869 # We set stdout to PIPE because, as of this writing, a different
870 # code path is tested when the number of pipes is zero or one.
871 p = subprocess.Popen([sys.executable, "-c", "pass"],
872 stdin=subprocess.PIPE,
873 stdout=subprocess.PIPE,
874 universal_newlines=True)
875 p.communicate()
876 self.assertEqual(p.returncode, 0)
877
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300878 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300879 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300880 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300881 'import sys,os;' + SETBINARY + textwrap.dedent('''
882 s = sys.stdin.buffer.readline()
883 sys.stdout.buffer.write(s)
884 sys.stdout.buffer.write(b"line2\\r")
885 sys.stderr.buffer.write(b"eline2\\n")
886 s = sys.stdin.buffer.read()
887 sys.stdout.buffer.write(s)
888 sys.stdout.buffer.write(b"line4\\n")
889 sys.stdout.buffer.write(b"line5\\r\\n")
890 sys.stderr.buffer.write(b"eline6\\r")
891 sys.stderr.buffer.write(b"eline7\\r\\nz")
892 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300893 stdin=subprocess.PIPE,
894 stderr=subprocess.PIPE,
895 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300896 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300897 self.addCleanup(p.stdout.close)
898 self.addCleanup(p.stderr.close)
899 (stdout, stderr) = p.communicate("line1\nline3\n")
900 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300901 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300902 # Python debug build push something like "[42442 refs]\n"
903 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300904 # Don't use assertStderrEqual because it strips CR and LF from output.
905 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300906
Andrew Svetlov82860712012-08-19 22:13:41 +0300907 def test_universal_newlines_communicate_encodings(self):
908 # Check that universal newlines mode works for various encodings,
909 # in particular for encodings in the UTF-16 and UTF-32 families.
910 # See issue #15595.
911 #
912 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
913 # without, and UTF-16 and UTF-32.
914 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +0300915 code = ("import sys; "
916 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
917 encoding)
918 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -0700919 # We set stdin to be non-None because, as of this writing,
920 # a different code path is used when the number of pipes is
921 # zero or one.
922 popen = subprocess.Popen(args,
923 stdin=subprocess.PIPE,
924 stdout=subprocess.PIPE,
925 encoding=encoding)
926 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +0300927 self.assertEqual(stdout, '1\n2\n3\n4')
928
Steve Dower050acae2016-09-06 20:16:17 -0700929 def test_communicate_errors(self):
930 for errors, expected in [
931 ('ignore', ''),
932 ('replace', '\ufffd\ufffd'),
933 ('surrogateescape', '\udc80\udc80'),
934 ('backslashreplace', '\\x80\\x80'),
935 ]:
936 code = ("import sys; "
937 r"sys.stdout.buffer.write(b'[\x80\x80]')")
938 args = [sys.executable, '-c', code]
939 # We set stdin to be non-None because, as of this writing,
940 # a different code path is used when the number of pipes is
941 # zero or one.
942 popen = subprocess.Popen(args,
943 stdin=subprocess.PIPE,
944 stdout=subprocess.PIPE,
945 encoding='utf-8',
946 errors=errors)
947 stdout, stderr = popen.communicate(input='')
948 self.assertEqual(stdout, '[{}]'.format(expected))
949
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000950 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000951 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000952 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000953 max_handles = 1026 # too much for most UNIX systems
954 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000955 max_handles = 2050 # too much for (at least some) Windows setups
956 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400957 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000958 try:
959 for i in range(max_handles):
960 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400961 tmpfile = os.path.join(tmpdir, support.TESTFN)
962 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000963 except OSError as e:
964 if e.errno != errno.EMFILE:
965 raise
966 break
967 else:
968 self.skipTest("failed to reach the file descriptor limit "
969 "(tried %d)" % max_handles)
970 # Close a couple of them (should be enough for a subprocess)
971 for i in range(10):
972 os.close(handles.pop())
973 # Loop creating some subprocesses. If one of them leaks some fds,
974 # the next loop iteration will fail by reaching the max fd limit.
975 for i in range(15):
976 p = subprocess.Popen([sys.executable, "-c",
977 "import sys;"
978 "sys.stdout.write(sys.stdin.read())"],
979 stdin=subprocess.PIPE,
980 stdout=subprocess.PIPE,
981 stderr=subprocess.PIPE)
982 data = p.communicate(b"lime")[0]
983 self.assertEqual(data, b"lime")
984 finally:
985 for h in handles:
986 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400987 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000988
989 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000990 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
991 '"a b c" d e')
992 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
993 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000994 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
995 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000996 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
997 'a\\\\\\b "de fg" h')
998 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
999 'a\\\\\\"b c d')
1000 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
1001 '"a\\\\b c" d e')
1002 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
1003 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001004 self.assertEqual(subprocess.list2cmdline(['ab', '']),
1005 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001006
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001007 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001008 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +02001009 "import os; os.read(0, 1)"],
1010 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001011 self.addCleanup(p.stdin.close)
1012 self.assertIsNone(p.poll())
1013 os.write(p.stdin.fileno(), b'A')
1014 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001015 # Subsequent invocations should just return the returncode
1016 self.assertEqual(p.poll(), 0)
1017
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001018 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001019 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001020 self.assertEqual(p.wait(), 0)
1021 # Subsequent invocations should just return the returncode
1022 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001023
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001024 def test_wait_timeout(self):
1025 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001026 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001027 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001028 p.wait(timeout=0.0001)
1029 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -04001030 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
1031 # time to start.
1032 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001033
Gregory P. Smithf0e98c52016-11-20 16:25:14 -08001034 def test_wait_endtime(self):
1035 """Confirm that the deprecated endtime parameter warns."""
1036 p = subprocess.Popen([sys.executable, "-c", "pass"])
1037 try:
1038 with self.assertWarns(DeprecationWarning) as warn_cm:
1039 p.wait(endtime=time.time()+0.01)
1040 except subprocess.TimeoutExpired:
1041 pass # We're not testing endtime timeout behavior.
1042 finally:
1043 p.kill()
1044 self.assertIn('test_subprocess.py', warn_cm.filename)
1045 self.assertIn('endtime', str(warn_cm.warning))
1046
Peter Astrand738131d2004-11-30 21:04:45 +00001047 def test_invalid_bufsize(self):
1048 # an invalid type of the bufsize argument should raise
1049 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001050 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +00001051 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001052
Guido van Rossum46a05a72007-06-07 21:56:45 +00001053 def test_bufsize_is_none(self):
1054 # bufsize=None should be the same as bufsize=0.
1055 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
1056 self.assertEqual(p.wait(), 0)
1057 # Again with keyword arg
1058 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
1059 self.assertEqual(p.wait(), 0)
1060
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001061 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1062 # subprocess may deadlock with bufsize=1, see issue #21332
1063 with subprocess.Popen([sys.executable, "-c", "import sys;"
1064 "sys.stdout.write(sys.stdin.readline());"
1065 "sys.stdout.flush()"],
1066 stdin=subprocess.PIPE,
1067 stdout=subprocess.PIPE,
1068 stderr=subprocess.DEVNULL,
1069 bufsize=1,
1070 universal_newlines=universal_newlines) as p:
1071 p.stdin.write(line) # expect that it flushes the line in text mode
1072 os.close(p.stdin.fileno()) # close it without flushing the buffer
1073 read_line = p.stdout.readline()
1074 try:
1075 p.stdin.close()
1076 except OSError:
1077 pass
1078 p.stdin = None
1079 self.assertEqual(p.returncode, 0)
1080 self.assertEqual(read_line, expected)
1081
1082 def test_bufsize_equal_one_text_mode(self):
1083 # line is flushed in text mode with bufsize=1.
1084 # we should get the full line in return
1085 line = "line\n"
1086 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1087
1088 def test_bufsize_equal_one_binary_mode(self):
1089 # line is not flushed in binary mode with bufsize=1.
1090 # we should get empty response
1091 line = b'line' + os.linesep.encode() # assume ascii-based locale
1092 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
1093
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001094 def test_leaking_fds_on_error(self):
1095 # see bug #5179: Popen leaks file descriptors to PIPEs if
1096 # the child fails to execute; this will eventually exhaust
1097 # the maximum number of open fds. 1024 seems a very common
1098 # value for that limit, but Windows has 2048, so we loop
1099 # 1024 times (each call leaked two fds).
1100 for i in range(1024):
Andrew Svetlov3438fa42012-12-17 23:35:18 +02001101 with self.assertRaises(OSError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001102 subprocess.Popen(['nonexisting_i_hope'],
1103 stdout=subprocess.PIPE,
1104 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -04001105 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -04001106 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001107 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001108
Antoine Pitroua8392712013-08-30 23:38:13 +02001109 @unittest.skipIf(threading is None, "threading required")
1110 def test_double_close_on_error(self):
1111 # Issue #18851
1112 fds = []
1113 def open_fds():
1114 for i in range(20):
1115 fds.extend(os.pipe())
1116 time.sleep(0.001)
1117 t = threading.Thread(target=open_fds)
1118 t.start()
1119 try:
1120 with self.assertRaises(EnvironmentError):
1121 subprocess.Popen(['nonexisting_i_hope'],
1122 stdin=subprocess.PIPE,
1123 stdout=subprocess.PIPE,
1124 stderr=subprocess.PIPE)
1125 finally:
1126 t.join()
1127 exc = None
1128 for fd in fds:
1129 # If a double close occurred, some of those fds will
1130 # already have been closed by mistake, and os.close()
1131 # here will raise.
1132 try:
1133 os.close(fd)
1134 except OSError as e:
1135 exc = e
1136 if exc is not None:
1137 raise exc
1138
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001139 @unittest.skipIf(threading is None, "threading required")
1140 def test_threadsafe_wait(self):
1141 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1142 proc = subprocess.Popen([sys.executable, '-c',
1143 'import time; time.sleep(12)'])
1144 self.assertEqual(proc.returncode, None)
1145 results = []
1146
1147 def kill_proc_timer_thread():
1148 results.append(('thread-start-poll-result', proc.poll()))
1149 # terminate it from the thread and wait for the result.
1150 proc.kill()
1151 proc.wait()
1152 results.append(('thread-after-kill-and-wait', proc.returncode))
1153 # this wait should be a no-op given the above.
1154 proc.wait()
1155 results.append(('thread-after-second-wait', proc.returncode))
1156
1157 # This is a timing sensitive test, the failure mode is
1158 # triggered when both the main thread and this thread are in
1159 # the wait() call at once. The delay here is to allow the
1160 # main thread to most likely be blocked in its wait() call.
1161 t = threading.Timer(0.2, kill_proc_timer_thread)
1162 t.start()
1163
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001164 if mswindows:
1165 expected_errorcode = 1
1166 else:
1167 # Should be -9 because of the proc.kill() from the thread.
1168 expected_errorcode = -9
1169
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001170 # Wait for the process to finish; the thread should kill it
1171 # long before it finishes on its own. Supplying a timeout
1172 # triggers a different code path for better coverage.
1173 proc.wait(timeout=20)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001174 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001175 msg="unexpected result in wait from main thread")
1176
1177 # This should be a no-op with no change in returncode.
1178 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001179 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001180 msg="unexpected result in second main wait.")
1181
1182 t.join()
1183 # Ensure that all of the thread results are as expected.
1184 # When a race condition occurs in wait(), the returncode could
1185 # be set by the wrong thread that doesn't actually have it
1186 # leading to an incorrect value.
1187 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001188 ('thread-after-kill-and-wait', expected_errorcode),
1189 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001190 results)
1191
Victor Stinnerb3693582010-05-21 20:13:12 +00001192 def test_issue8780(self):
1193 # Ensure that stdout is inherited from the parent
1194 # if stdout=PIPE is not used
1195 code = ';'.join((
1196 'import subprocess, sys',
1197 'retcode = subprocess.call('
1198 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1199 'assert retcode == 0'))
1200 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001201 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001202
Tim Goldenaf5ac392010-08-06 13:03:56 +00001203 def test_handles_closed_on_exception(self):
1204 # If CreateProcess exits with an error, ensure the
1205 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001206 ifhandle, ifname = tempfile.mkstemp()
1207 ofhandle, ofname = tempfile.mkstemp()
1208 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001209 try:
1210 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1211 stderr=efhandle)
1212 except OSError:
1213 os.close(ifhandle)
1214 os.remove(ifname)
1215 os.close(ofhandle)
1216 os.remove(ofname)
1217 os.close(efhandle)
1218 os.remove(efname)
1219 self.assertFalse(os.path.exists(ifname))
1220 self.assertFalse(os.path.exists(ofname))
1221 self.assertFalse(os.path.exists(efname))
1222
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001223 def test_communicate_epipe(self):
1224 # Issue 10963: communicate() should hide EPIPE
1225 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1226 stdin=subprocess.PIPE,
1227 stdout=subprocess.PIPE,
1228 stderr=subprocess.PIPE)
1229 self.addCleanup(p.stdout.close)
1230 self.addCleanup(p.stderr.close)
1231 self.addCleanup(p.stdin.close)
1232 p.communicate(b"x" * 2**20)
1233
1234 def test_communicate_epipe_only_stdin(self):
1235 # Issue 10963: communicate() should hide EPIPE
1236 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1237 stdin=subprocess.PIPE)
1238 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001239 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001240 p.communicate(b"x" * 2**20)
1241
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001242 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1243 "Requires signal.SIGUSR1")
1244 @unittest.skipUnless(hasattr(os, 'kill'),
1245 "Requires os.kill")
1246 @unittest.skipUnless(hasattr(os, 'getppid'),
1247 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001248 def test_communicate_eintr(self):
1249 # Issue #12493: communicate() should handle EINTR
1250 def handler(signum, frame):
1251 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001252 old_handler = signal.signal(signal.SIGUSR1, handler)
1253 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001254
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001255 args = [sys.executable, "-c",
1256 'import os, signal;'
1257 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001258 for stream in ('stdout', 'stderr'):
1259 kw = {stream: subprocess.PIPE}
1260 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001261 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001262 process.communicate()
1263
Tim Peterse718f612004-10-12 21:51:32 +00001264
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001265 # This test is Linux-ish specific for simplicity to at least have
1266 # some coverage. It is not a platform specific bug.
1267 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1268 "Linux specific")
1269 def test_failed_child_execute_fd_leak(self):
1270 """Test for the fork() failure fd leak reported in issue16327."""
1271 fd_directory = '/proc/%d/fd' % os.getpid()
1272 fds_before_popen = os.listdir(fd_directory)
1273 with self.assertRaises(PopenTestException):
1274 PopenExecuteChildRaises(
1275 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
1276 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1277
1278 # NOTE: This test doesn't verify that the real _execute_child
1279 # does not close the file descriptors itself on the way out
1280 # during an exception. Code inspection has confirmed that.
1281
1282 fds_after_exception = os.listdir(fd_directory)
1283 self.assertEqual(fds_before_popen, fds_after_exception)
1284
Gregory P. Smith6e730002015-04-14 16:14:25 -07001285
1286class RunFuncTestCase(BaseTestCase):
1287 def run_python(self, code, **kwargs):
1288 """Run Python code in a subprocess using subprocess.run"""
1289 argv = [sys.executable, "-c", code]
1290 return subprocess.run(argv, **kwargs)
1291
1292 def test_returncode(self):
1293 # call() function with sequence argument
1294 cp = self.run_python("import sys; sys.exit(47)")
1295 self.assertEqual(cp.returncode, 47)
1296 with self.assertRaises(subprocess.CalledProcessError):
1297 cp.check_returncode()
1298
1299 def test_check(self):
1300 with self.assertRaises(subprocess.CalledProcessError) as c:
1301 self.run_python("import sys; sys.exit(47)", check=True)
1302 self.assertEqual(c.exception.returncode, 47)
1303
1304 def test_check_zero(self):
1305 # check_returncode shouldn't raise when returncode is zero
1306 cp = self.run_python("import sys; sys.exit(0)", check=True)
1307 self.assertEqual(cp.returncode, 0)
1308
1309 def test_timeout(self):
1310 # run() function with timeout argument; we want to test that the child
1311 # process gets killed when the timeout expires. If the child isn't
1312 # killed, this call will deadlock since subprocess.run waits for the
1313 # child.
1314 with self.assertRaises(subprocess.TimeoutExpired):
1315 self.run_python("while True: pass", timeout=0.0001)
1316
1317 def test_capture_stdout(self):
1318 # capture stdout with zero return code
1319 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1320 self.assertIn(b'BDFL', cp.stdout)
1321
1322 def test_capture_stderr(self):
1323 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1324 stderr=subprocess.PIPE)
1325 self.assertIn(b'BDFL', cp.stderr)
1326
1327 def test_check_output_stdin_arg(self):
1328 # run() can be called with stdin set to a file
1329 tf = tempfile.TemporaryFile()
1330 self.addCleanup(tf.close)
1331 tf.write(b'pear')
1332 tf.seek(0)
1333 cp = self.run_python(
1334 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1335 stdin=tf, stdout=subprocess.PIPE)
1336 self.assertIn(b'PEAR', cp.stdout)
1337
1338 def test_check_output_input_arg(self):
1339 # check_output() can be called with input set to a string
1340 cp = self.run_python(
1341 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1342 input=b'pear', stdout=subprocess.PIPE)
1343 self.assertIn(b'PEAR', cp.stdout)
1344
1345 def test_check_output_stdin_with_input_arg(self):
1346 # run() refuses to accept 'stdin' with 'input'
1347 tf = tempfile.TemporaryFile()
1348 self.addCleanup(tf.close)
1349 tf.write(b'pear')
1350 tf.seek(0)
1351 with self.assertRaises(ValueError,
1352 msg="Expected ValueError when stdin and input args supplied.") as c:
1353 output = self.run_python("print('will not be run')",
1354 stdin=tf, input=b'hare')
1355 self.assertIn('stdin', c.exception.args[0])
1356 self.assertIn('input', c.exception.args[0])
1357
1358 def test_check_output_timeout(self):
1359 with self.assertRaises(subprocess.TimeoutExpired) as c:
1360 cp = self.run_python((
1361 "import sys, time\n"
1362 "sys.stdout.write('BDFL')\n"
1363 "sys.stdout.flush()\n"
1364 "time.sleep(3600)"),
1365 # Some heavily loaded buildbots (sparc Debian 3.x) require
1366 # this much time to start and print.
1367 timeout=3, stdout=subprocess.PIPE)
1368 self.assertEqual(c.exception.output, b'BDFL')
1369 # output is aliased to stdout
1370 self.assertEqual(c.exception.stdout, b'BDFL')
1371
1372 def test_run_kwargs(self):
1373 newenv = os.environ.copy()
1374 newenv["FRUIT"] = "banana"
1375 cp = self.run_python(('import sys, os;'
1376 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1377 env=newenv)
1378 self.assertEqual(cp.returncode, 33)
1379
1380
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001381@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001382class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001383
Gregory P. Smith5591b022012-10-10 03:34:47 -07001384 def setUp(self):
1385 super().setUp()
1386 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1387
1388 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001389 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001390 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001391 except OSError as e:
1392 # This avoids hard coding the errno value or the OS perror()
1393 # string and instead capture the exception that we want to see
1394 # below for comparison.
1395 desired_exception = e
Gregory P. Smith5591b022012-10-10 03:34:47 -07001396 desired_exception.strerror += ': ' + repr(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001397 else:
Martin Pantereb995702016-07-28 01:11:04 +00001398 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001399 self._nonexistent_dir)
1400 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001401
Gregory P. Smith5591b022012-10-10 03:34:47 -07001402 def test_exception_cwd(self):
1403 """Test error in the child raised in the parent for a bad cwd."""
1404 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001405 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001406 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001407 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001408 except OSError as e:
1409 # Test that the child process chdir failure actually makes
1410 # it up to the parent process as the correct exception.
1411 self.assertEqual(desired_exception.errno, e.errno)
1412 self.assertEqual(desired_exception.strerror, e.strerror)
1413 else:
1414 self.fail("Expected OSError: %s" % desired_exception)
1415
Gregory P. Smith5591b022012-10-10 03:34:47 -07001416 def test_exception_bad_executable(self):
1417 """Test error in the child raised in the parent for a bad executable."""
1418 desired_exception = self._get_chdir_exception()
1419 try:
1420 p = subprocess.Popen([sys.executable, "-c", ""],
1421 executable=self._nonexistent_dir)
1422 except OSError as e:
1423 # Test that the child process exec failure actually makes
1424 # it up to the parent process as the correct exception.
1425 self.assertEqual(desired_exception.errno, e.errno)
1426 self.assertEqual(desired_exception.strerror, e.strerror)
1427 else:
1428 self.fail("Expected OSError: %s" % desired_exception)
1429
1430 def test_exception_bad_args_0(self):
1431 """Test error in the child raised in the parent for a bad args[0]."""
1432 desired_exception = self._get_chdir_exception()
1433 try:
1434 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1435 except OSError as e:
1436 # Test that the child process exec failure actually makes
1437 # it up to the parent process as the correct exception.
1438 self.assertEqual(desired_exception.errno, e.errno)
1439 self.assertEqual(desired_exception.strerror, e.strerror)
1440 else:
1441 self.fail("Expected OSError: %s" % desired_exception)
1442
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001443 def test_restore_signals(self):
1444 # Code coverage for both values of restore_signals to make sure it
1445 # at least does not blow up.
1446 # A test for behavior would be complex. Contributions welcome.
1447 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1448 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1449
1450 def test_start_new_session(self):
1451 # For code coverage of calling setsid(). We don't care if we get an
1452 # EPERM error from it depending on the test execution environment, that
1453 # still indicates that it was called.
1454 try:
1455 output = subprocess.check_output(
1456 [sys.executable, "-c",
1457 "import os; print(os.getpgid(os.getpid()))"],
1458 start_new_session=True)
1459 except OSError as e:
1460 if e.errno != errno.EPERM:
1461 raise
1462 else:
1463 parent_pgid = os.getpgid(os.getpid())
1464 child_pgid = int(output)
1465 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001466
1467 def test_run_abort(self):
1468 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001469 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001470 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001471 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001472 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001473 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001474
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001475 def test_CalledProcessError_str_signal(self):
1476 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
1477 error_string = str(err)
1478 # We're relying on the repr() of the signal.Signals intenum to provide
1479 # the word signal, the signal name and the numeric value.
1480 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00001481 # We're not being specific about the signal name as some signals have
1482 # multiple names and which name is revealed can vary.
1483 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001484 self.assertIn(str(signal.SIGABRT), error_string)
1485
1486 def test_CalledProcessError_str_unknown_signal(self):
1487 err = subprocess.CalledProcessError(-9876543, "fake cmd")
1488 error_string = str(err)
1489 self.assertIn("unknown signal 9876543.", error_string)
1490
1491 def test_CalledProcessError_str_non_zero(self):
1492 err = subprocess.CalledProcessError(2, "fake cmd")
1493 error_string = str(err)
1494 self.assertIn("non-zero exit status 2.", error_string)
1495
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001496 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001497 # DISCLAIMER: Setting environment variables is *not* a good use
1498 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001499 p = subprocess.Popen([sys.executable, "-c",
1500 'import sys,os;'
1501 'sys.stdout.write(os.getenv("FRUIT"))'],
1502 stdout=subprocess.PIPE,
1503 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02001504 with p:
1505 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001506
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001507 def test_preexec_exception(self):
1508 def raise_it():
1509 raise ValueError("What if two swallows carried a coconut?")
1510 try:
1511 p = subprocess.Popen([sys.executable, "-c", ""],
1512 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001513 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001514 self.assertTrue(
1515 subprocess._posixsubprocess,
1516 "Expected a ValueError from the preexec_fn")
1517 except ValueError as e:
1518 self.assertIn("coconut", e.args[0])
1519 else:
1520 self.fail("Exception raised by preexec_fn did not make it "
1521 "to the parent process.")
1522
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001523 class _TestExecuteChildPopen(subprocess.Popen):
1524 """Used to test behavior at the end of _execute_child."""
1525 def __init__(self, testcase, *args, **kwargs):
1526 self._testcase = testcase
1527 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001528
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001529 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001530 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001531 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001532 finally:
1533 # Open a bunch of file descriptors and verify that
1534 # none of them are the same as the ones the Popen
1535 # instance is using for stdin/stdout/stderr.
1536 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1537 for _ in range(8)]
1538 try:
1539 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001540 self._testcase.assertNotIn(
1541 fd, (self.stdin.fileno(), self.stdout.fileno(),
1542 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001543 msg="At least one fd was closed early.")
1544 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01001545 for fd in devzero_fds:
1546 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001547
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001548 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1549 def test_preexec_errpipe_does_not_double_close_pipes(self):
1550 """Issue16140: Don't double close pipes on preexec error."""
1551
1552 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08001553 raise subprocess.SubprocessError(
1554 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001555
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08001556 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001557 self._TestExecuteChildPopen(
1558 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001559 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1560 stderr=subprocess.PIPE, preexec_fn=raise_it)
1561
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001562 def test_preexec_gc_module_failure(self):
1563 # This tests the code that disables garbage collection if the child
1564 # process will execute any Python.
1565 def raise_runtime_error():
1566 raise RuntimeError("this shouldn't escape")
1567 enabled = gc.isenabled()
1568 orig_gc_disable = gc.disable
1569 orig_gc_isenabled = gc.isenabled
1570 try:
1571 gc.disable()
1572 self.assertFalse(gc.isenabled())
1573 subprocess.call([sys.executable, '-c', ''],
1574 preexec_fn=lambda: None)
1575 self.assertFalse(gc.isenabled(),
1576 "Popen enabled gc when it shouldn't.")
1577
1578 gc.enable()
1579 self.assertTrue(gc.isenabled())
1580 subprocess.call([sys.executable, '-c', ''],
1581 preexec_fn=lambda: None)
1582 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1583
1584 gc.disable = raise_runtime_error
1585 self.assertRaises(RuntimeError, subprocess.Popen,
1586 [sys.executable, '-c', ''],
1587 preexec_fn=lambda: None)
1588
1589 del gc.isenabled # force an AttributeError
1590 self.assertRaises(AttributeError, subprocess.Popen,
1591 [sys.executable, '-c', ''],
1592 preexec_fn=lambda: None)
1593 finally:
1594 gc.disable = orig_gc_disable
1595 gc.isenabled = orig_gc_isenabled
1596 if not enabled:
1597 gc.disable()
1598
Martin Panterf7fdbda2015-12-05 09:51:52 +00001599 @unittest.skipIf(
1600 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00001601 def test_preexec_fork_failure(self):
1602 # The internal code did not preserve the previous exception when
1603 # re-enabling garbage collection
1604 try:
1605 from resource import getrlimit, setrlimit, RLIMIT_NPROC
1606 except ImportError as err:
1607 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
1608 limits = getrlimit(RLIMIT_NPROC)
1609 [_, hard] = limits
1610 setrlimit(RLIMIT_NPROC, (0, hard))
1611 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00001612 try:
Martin Panterafdd5132015-11-30 02:21:41 +00001613 subprocess.call([sys.executable, '-c', ''],
1614 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00001615 except BlockingIOError:
1616 # Forking should raise EAGAIN, translated to BlockingIOError
1617 pass
1618 else:
1619 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00001620
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001621 def test_args_string(self):
1622 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03001623 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001624 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001625 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001626 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001627 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1628 sys.executable)
1629 os.chmod(fname, 0o700)
1630 p = subprocess.Popen(fname)
1631 p.wait()
1632 os.remove(fname)
1633 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001634
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001635 def test_invalid_args(self):
1636 # invalid arguments should raise ValueError
1637 self.assertRaises(ValueError, subprocess.call,
1638 [sys.executable, "-c",
1639 "import sys; sys.exit(47)"],
1640 startupinfo=47)
1641 self.assertRaises(ValueError, subprocess.call,
1642 [sys.executable, "-c",
1643 "import sys; sys.exit(47)"],
1644 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001645
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001646 def test_shell_sequence(self):
1647 # Run command through the shell (sequence)
1648 newenv = os.environ.copy()
1649 newenv["FRUIT"] = "apple"
1650 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1651 stdout=subprocess.PIPE,
1652 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001653 with p:
1654 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001655
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001656 def test_shell_string(self):
1657 # Run command through the shell (string)
1658 newenv = os.environ.copy()
1659 newenv["FRUIT"] = "apple"
1660 p = subprocess.Popen("echo $FRUIT", shell=1,
1661 stdout=subprocess.PIPE,
1662 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001663 with p:
1664 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001665
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001666 def test_call_string(self):
1667 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03001668 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001669 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001670 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001671 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001672 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1673 sys.executable)
1674 os.chmod(fname, 0o700)
1675 rc = subprocess.call(fname)
1676 os.remove(fname)
1677 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001678
Stefan Krah9542cc62010-07-19 14:20:53 +00001679 def test_specific_shell(self):
1680 # Issue #9265: Incorrect name passed as arg[0].
1681 shells = []
1682 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1683 for name in ['bash', 'ksh']:
1684 sh = os.path.join(prefix, name)
1685 if os.path.isfile(sh):
1686 shells.append(sh)
1687 if not shells: # Will probably work for any shell but csh.
1688 self.skipTest("bash or ksh required for this test")
1689 sh = '/bin/sh'
1690 if os.path.isfile(sh) and not os.path.islink(sh):
1691 # Test will fail if /bin/sh is a symlink to csh.
1692 shells.append(sh)
1693 for sh in shells:
1694 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1695 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02001696 with p:
1697 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00001698
Florent Xicluna4886d242010-03-08 13:27:26 +00001699 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001700 # Do not inherit file handles from the parent.
1701 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07001702 # Also set the SIGINT handler to the default to make sure it's not
1703 # being ignored (some tests rely on that.)
1704 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
1705 try:
1706 p = subprocess.Popen([sys.executable, "-c", """if 1:
1707 import sys, time
1708 sys.stdout.write('x\\n')
1709 sys.stdout.flush()
1710 time.sleep(30)
1711 """],
1712 close_fds=True,
1713 stdin=subprocess.PIPE,
1714 stdout=subprocess.PIPE,
1715 stderr=subprocess.PIPE)
1716 finally:
1717 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001718 # Wait for the interpreter to be completely initialized before
1719 # sending any signal.
1720 p.stdout.read(1)
1721 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001722 return p
1723
Charles-François Natali53221e32013-01-12 16:52:20 +01001724 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1725 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001726 def _kill_dead_process(self, method, *args):
1727 # Do not inherit file handles from the parent.
1728 # It should fix failures on some platforms.
1729 p = subprocess.Popen([sys.executable, "-c", """if 1:
1730 import sys, time
1731 sys.stdout.write('x\\n')
1732 sys.stdout.flush()
1733 """],
1734 close_fds=True,
1735 stdin=subprocess.PIPE,
1736 stdout=subprocess.PIPE,
1737 stderr=subprocess.PIPE)
1738 # Wait for the interpreter to be completely initialized before
1739 # sending any signal.
1740 p.stdout.read(1)
1741 # The process should end after this
1742 time.sleep(1)
1743 # This shouldn't raise even though the child is now dead
1744 getattr(p, method)(*args)
1745 p.communicate()
1746
Florent Xicluna4886d242010-03-08 13:27:26 +00001747 def test_send_signal(self):
1748 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001749 _, stderr = p.communicate()
1750 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001751 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001752
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001753 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001754 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001755 _, stderr = p.communicate()
1756 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001757 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001758
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001759 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001760 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001761 _, stderr = p.communicate()
1762 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001763 self.assertEqual(p.wait(), -signal.SIGTERM)
1764
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001765 def test_send_signal_dead(self):
1766 # Sending a signal to a dead process
1767 self._kill_dead_process('send_signal', signal.SIGINT)
1768
1769 def test_kill_dead(self):
1770 # Killing a dead process
1771 self._kill_dead_process('kill')
1772
1773 def test_terminate_dead(self):
1774 # Terminating a dead process
1775 self._kill_dead_process('terminate')
1776
Victor Stinnerdaf45552013-08-28 00:53:59 +02001777 def _save_fds(self, save_fds):
1778 fds = []
1779 for fd in save_fds:
1780 inheritable = os.get_inheritable(fd)
1781 saved = os.dup(fd)
1782 fds.append((fd, saved, inheritable))
1783 return fds
1784
1785 def _restore_fds(self, fds):
1786 for fd, saved, inheritable in fds:
1787 os.dup2(saved, fd, inheritable=inheritable)
1788 os.close(saved)
1789
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001790 def check_close_std_fds(self, fds):
1791 # Issue #9905: test that subprocess pipes still work properly with
1792 # some standard fds closed
1793 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02001794 saved_fds = self._save_fds(fds)
1795 for fd, saved, inheritable in saved_fds:
1796 if fd == 0:
1797 stdin = saved
1798 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001799 try:
1800 for fd in fds:
1801 os.close(fd)
1802 out, err = subprocess.Popen([sys.executable, "-c",
1803 'import sys;'
1804 'sys.stdout.write("apple");'
1805 'sys.stdout.flush();'
1806 'sys.stderr.write("orange")'],
1807 stdin=stdin,
1808 stdout=subprocess.PIPE,
1809 stderr=subprocess.PIPE).communicate()
1810 err = support.strip_python_stderr(err)
1811 self.assertEqual((out, err), (b'apple', b'orange'))
1812 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001813 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001814
1815 def test_close_fd_0(self):
1816 self.check_close_std_fds([0])
1817
1818 def test_close_fd_1(self):
1819 self.check_close_std_fds([1])
1820
1821 def test_close_fd_2(self):
1822 self.check_close_std_fds([2])
1823
1824 def test_close_fds_0_1(self):
1825 self.check_close_std_fds([0, 1])
1826
1827 def test_close_fds_0_2(self):
1828 self.check_close_std_fds([0, 2])
1829
1830 def test_close_fds_1_2(self):
1831 self.check_close_std_fds([1, 2])
1832
1833 def test_close_fds_0_1_2(self):
1834 # Issue #10806: test that subprocess pipes still work properly with
1835 # all standard fds closed.
1836 self.check_close_std_fds([0, 1, 2])
1837
Gregory P. Smith53dd8162013-12-01 16:03:24 -08001838 def test_small_errpipe_write_fd(self):
1839 """Issue #15798: Popen should work when stdio fds are available."""
1840 new_stdin = os.dup(0)
1841 new_stdout = os.dup(1)
1842 try:
1843 os.close(0)
1844 os.close(1)
1845
1846 # Side test: if errpipe_write fails to have its CLOEXEC
1847 # flag set this should cause the parent to think the exec
1848 # failed. Extremely unlikely: everyone supports CLOEXEC.
1849 subprocess.Popen([
1850 sys.executable, "-c",
1851 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
1852 finally:
1853 # Restore original stdin and stdout
1854 os.dup2(new_stdin, 0)
1855 os.dup2(new_stdout, 1)
1856 os.close(new_stdin)
1857 os.close(new_stdout)
1858
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001859 def test_remapping_std_fds(self):
1860 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03001861 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001862 try:
1863 temp_fds = [fd for fd, fname in temps]
1864
1865 # unlink the files -- we won't need to reopen them
1866 for fd, fname in temps:
1867 os.unlink(fname)
1868
1869 # write some data to what will become stdin, and rewind
1870 os.write(temp_fds[1], b"STDIN")
1871 os.lseek(temp_fds[1], 0, 0)
1872
1873 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02001874 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001875 try:
1876 # duplicate the file objects over the standard fd's
1877 for fd, temp_fd in enumerate(temp_fds):
1878 os.dup2(temp_fd, fd)
1879
1880 # now use those files in the "wrong" order, so that subprocess
1881 # has to rearrange them in the child
1882 p = subprocess.Popen([sys.executable, "-c",
1883 'import sys; got = sys.stdin.read();'
1884 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1885 stdin=temp_fds[1],
1886 stdout=temp_fds[2],
1887 stderr=temp_fds[0])
1888 p.wait()
1889 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001890 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001891
1892 for fd in temp_fds:
1893 os.lseek(fd, 0, 0)
1894
1895 out = os.read(temp_fds[2], 1024)
1896 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1897 self.assertEqual(out, b"got STDIN")
1898 self.assertEqual(err, b"err")
1899
1900 finally:
1901 for fd in temp_fds:
1902 os.close(fd)
1903
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001904 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1905 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03001906 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001907 temp_fds = [fd for fd, fname in temps]
1908 try:
1909 # unlink the files -- we won't need to reopen them
1910 for fd, fname in temps:
1911 os.unlink(fname)
1912
1913 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02001914 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001915 try:
1916 # duplicate the temp files over the standard fd's 0, 1, 2
1917 for fd, temp_fd in enumerate(temp_fds):
1918 os.dup2(temp_fd, fd)
1919
1920 # write some data to what will become stdin, and rewind
1921 os.write(stdin_no, b"STDIN")
1922 os.lseek(stdin_no, 0, 0)
1923
1924 # now use those files in the given order, so that subprocess
1925 # has to rearrange them in the child
1926 p = subprocess.Popen([sys.executable, "-c",
1927 'import sys; got = sys.stdin.read();'
1928 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1929 stdin=stdin_no,
1930 stdout=stdout_no,
1931 stderr=stderr_no)
1932 p.wait()
1933
1934 for fd in temp_fds:
1935 os.lseek(fd, 0, 0)
1936
1937 out = os.read(stdout_no, 1024)
1938 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1939 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001940 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001941
1942 self.assertEqual(out, b"got STDIN")
1943 self.assertEqual(err, b"err")
1944
1945 finally:
1946 for fd in temp_fds:
1947 os.close(fd)
1948
1949 # When duping fds, if there arises a situation where one of the fds is
1950 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1951 # This tests all combinations of this.
1952 def test_swap_fds(self):
1953 self.check_swap_fds(0, 1, 2)
1954 self.check_swap_fds(0, 2, 1)
1955 self.check_swap_fds(1, 0, 2)
1956 self.check_swap_fds(1, 2, 0)
1957 self.check_swap_fds(2, 0, 1)
1958 self.check_swap_fds(2, 1, 0)
1959
Victor Stinner13bb71c2010-04-23 21:41:56 +00001960 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001961 def prepare():
1962 raise ValueError("surrogate:\uDCff")
1963
1964 try:
1965 subprocess.call(
1966 [sys.executable, "-c", "pass"],
1967 preexec_fn=prepare)
1968 except ValueError as err:
1969 # Pure Python implementations keeps the message
1970 self.assertIsNone(subprocess._posixsubprocess)
1971 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001972 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00001973 # _posixsubprocess uses a default message
1974 self.assertIsNotNone(subprocess._posixsubprocess)
1975 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1976 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001977 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00001978
Victor Stinner13bb71c2010-04-23 21:41:56 +00001979 def test_undecodable_env(self):
1980 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01001981 encoded_value = value.encode("ascii", "surrogateescape")
1982
Victor Stinner13bb71c2010-04-23 21:41:56 +00001983 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001984 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001985 env = os.environ.copy()
1986 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01001987 # Use C locale to get ASCII for the locale encoding to force
Victor Stinner89f3ad12010-10-14 10:43:31 +00001988 # surrogate-escaping of \xFF in the child process; otherwise it can
1989 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001990 env['LC_ALL'] = 'C'
Victor Stinner5323fb02013-11-19 23:46:06 +01001991 if sys.platform.startswith("aix"):
1992 # On AIX, the C locale uses the Latin1 encoding
1993 decoded_value = encoded_value.decode("latin1", "surrogateescape")
1994 else:
1995 # On other UNIXes, the C locale uses the ASCII encoding
1996 decoded_value = 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(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002002
2003 # test bytes
2004 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002005 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002006 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01002007 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002008 stdout = subprocess.check_output(
2009 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002010 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002011 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002012 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002013
Victor Stinnerb745a742010-05-18 17:17:23 +00002014 def test_bytes_program(self):
2015 abs_program = os.fsencode(sys.executable)
2016 path, program = os.path.split(sys.executable)
2017 program = os.fsencode(program)
2018
2019 # absolute bytes path
2020 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00002021 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002022
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002023 # absolute bytes path as a string
2024 cmd = b"'" + abs_program + b"' -c pass"
2025 exitcode = subprocess.call(cmd, shell=True)
2026 self.assertEqual(exitcode, 0)
2027
Victor Stinnerb745a742010-05-18 17:17:23 +00002028 # bytes program, unicode PATH
2029 env = os.environ.copy()
2030 env["PATH"] = path
2031 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002032 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002033
2034 # bytes program, bytes PATH
2035 envb = os.environb.copy()
2036 envb[b"PATH"] = os.fsencode(path)
2037 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002038 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002039
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002040 def test_pipe_cloexec(self):
2041 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2042 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2043
2044 p1 = subprocess.Popen([sys.executable, sleeper],
2045 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2046 stderr=subprocess.PIPE, close_fds=False)
2047
2048 self.addCleanup(p1.communicate, b'')
2049
2050 p2 = subprocess.Popen([sys.executable, fd_status],
2051 stdout=subprocess.PIPE, close_fds=False)
2052
2053 output, error = p2.communicate()
2054 result_fds = set(map(int, output.split(b',')))
2055 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2056 p1.stderr.fileno()])
2057
2058 self.assertFalse(result_fds & unwanted_fds,
2059 "Expected no fds from %r to be open in child, "
2060 "found %r" %
2061 (unwanted_fds, result_fds & unwanted_fds))
2062
2063 def test_pipe_cloexec_real_tools(self):
2064 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2065 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2066
2067 subdata = b'zxcvbn'
2068 data = subdata * 4 + b'\n'
2069
2070 p1 = subprocess.Popen([sys.executable, qcat],
2071 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2072 close_fds=False)
2073
2074 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2075 stdin=p1.stdout, stdout=subprocess.PIPE,
2076 close_fds=False)
2077
2078 self.addCleanup(p1.wait)
2079 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002080 def kill_p1():
2081 try:
2082 p1.terminate()
2083 except ProcessLookupError:
2084 pass
2085 def kill_p2():
2086 try:
2087 p2.terminate()
2088 except ProcessLookupError:
2089 pass
2090 self.addCleanup(kill_p1)
2091 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002092
2093 p1.stdin.write(data)
2094 p1.stdin.close()
2095
2096 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2097
2098 self.assertTrue(readfiles, "The child hung")
2099 self.assertEqual(p2.stdout.read(), data)
2100
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002101 p1.stdout.close()
2102 p2.stdout.close()
2103
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002104 def test_close_fds(self):
2105 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2106
2107 fds = os.pipe()
2108 self.addCleanup(os.close, fds[0])
2109 self.addCleanup(os.close, fds[1])
2110
2111 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002112 # add a bunch more fds
2113 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002114 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002115 self.addCleanup(os.close, fd)
2116 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002117
Victor Stinnerdaf45552013-08-28 00:53:59 +02002118 for fd in open_fds:
2119 os.set_inheritable(fd, True)
2120
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002121 p = subprocess.Popen([sys.executable, fd_status],
2122 stdout=subprocess.PIPE, close_fds=False)
2123 output, ignored = p.communicate()
2124 remaining_fds = set(map(int, output.split(b',')))
2125
2126 self.assertEqual(remaining_fds & open_fds, open_fds,
2127 "Some fds were closed")
2128
2129 p = subprocess.Popen([sys.executable, fd_status],
2130 stdout=subprocess.PIPE, close_fds=True)
2131 output, ignored = p.communicate()
2132 remaining_fds = set(map(int, output.split(b',')))
2133
2134 self.assertFalse(remaining_fds & open_fds,
2135 "Some fds were left open")
2136 self.assertIn(1, remaining_fds, "Subprocess failed")
2137
Gregory P. Smith8facece2012-01-21 14:01:08 -08002138 # Keep some of the fd's we opened open in the subprocess.
2139 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2140 fds_to_keep = set(open_fds.pop() for _ in range(8))
2141 p = subprocess.Popen([sys.executable, fd_status],
2142 stdout=subprocess.PIPE, close_fds=True,
2143 pass_fds=())
2144 output, ignored = p.communicate()
2145 remaining_fds = set(map(int, output.split(b',')))
2146
2147 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
2148 "Some fds not in pass_fds were left open")
2149 self.assertIn(1, remaining_fds, "Subprocess failed")
2150
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002151
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002152 @unittest.skipIf(sys.platform.startswith("freebsd") and
2153 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2154 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002155 def test_close_fds_when_max_fd_is_lowered(self):
2156 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2157 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2158
Gregory P. Smith634aa682014-06-15 17:51:04 -07002159 # This launches the meat of the test in a child process to
2160 # avoid messing with the larger unittest processes maximum
2161 # number of file descriptors.
2162 # This process launches:
2163 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2164 # a bunch of high open fds above the new lower rlimit.
2165 # Those are reported via stdout before launching a new
2166 # process with close_fds=False to run the actual test:
2167 # +--> The TEST: This one launches a fd_status.py
2168 # subprocess with close_fds=True so we can find out if
2169 # any of the fds above the lowered rlimit are still open.
2170 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2171 '''
2172 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002173 open_fds = set()
2174 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002175 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002176 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002177 open_fds.add(fd)
2178
2179 # Leave a two pairs of low ones available for use by the
2180 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002181 # We also leave 10 more open as some Python buildbots run into
2182 # "too many open files" errors during the test if we do not.
2183 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002184 os.close(fd)
2185 open_fds.remove(fd)
2186
2187 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002188 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002189 os.set_inheritable(fd, True)
2190
2191 max_fd_open = max(open_fds)
2192
Gregory P. Smith634aa682014-06-15 17:51:04 -07002193 # Communicate the open_fds to the parent unittest.TestCase process.
2194 print(','.join(map(str, sorted(open_fds))))
2195 sys.stdout.flush()
2196
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002197 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2198 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002199 # 29 is lower than the highest fds we are leaving open.
2200 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002201 # Launch a new Python interpreter with our low fd rlim_cur that
2202 # inherits open fds above that limit. It then uses subprocess
2203 # with close_fds=True to get a report of open fds in the child.
2204 # An explicit list of fds to check is passed to fd_status.py as
2205 # letting fd_status rely on its default logic would miss the
2206 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002207 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002208 [sys.executable, '-c',
2209 textwrap.dedent("""
2210 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002211 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002212 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002213 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002214 """.format(max_fd=max_fd_open+1))],
2215 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002216 finally:
2217 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002218 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002219
2220 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002221 output_lines = output.splitlines()
2222 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002223 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002224 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2225 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002226
Gregory P. Smith634aa682014-06-15 17:51:04 -07002227 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002228 msg="Some fds were left open.")
2229
2230
Victor Stinner88701e22011-06-01 13:13:04 +02002231 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2232 # descriptor of a pipe closed in the parent process is valid in the
2233 # child process according to fstat(), but the mode of the file
2234 # descriptor is invalid, and read or write raise an error.
2235 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002236 def test_pass_fds(self):
2237 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2238
2239 open_fds = set()
2240
2241 for x in range(5):
2242 fds = os.pipe()
2243 self.addCleanup(os.close, fds[0])
2244 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002245 os.set_inheritable(fds[0], True)
2246 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002247 open_fds.update(fds)
2248
2249 for fd in open_fds:
2250 p = subprocess.Popen([sys.executable, fd_status],
2251 stdout=subprocess.PIPE, close_fds=True,
2252 pass_fds=(fd, ))
2253 output, ignored = p.communicate()
2254
2255 remaining_fds = set(map(int, output.split(b',')))
2256 to_be_closed = open_fds - {fd}
2257
2258 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2259 self.assertFalse(remaining_fds & to_be_closed,
2260 "fd to be closed passed")
2261
2262 # pass_fds overrides close_fds with a warning.
2263 with self.assertWarns(RuntimeWarning) as context:
2264 self.assertFalse(subprocess.call(
2265 [sys.executable, "-c", "import sys; sys.exit(0)"],
2266 close_fds=False, pass_fds=(fd, )))
2267 self.assertIn('overriding close_fds', str(context.warning))
2268
Victor Stinnerdaf45552013-08-28 00:53:59 +02002269 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002270 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002271
2272 inheritable, non_inheritable = os.pipe()
2273 self.addCleanup(os.close, inheritable)
2274 self.addCleanup(os.close, non_inheritable)
2275 os.set_inheritable(inheritable, True)
2276 os.set_inheritable(non_inheritable, False)
2277 pass_fds = (inheritable, non_inheritable)
2278 args = [sys.executable, script]
2279 args += list(map(str, pass_fds))
2280
2281 p = subprocess.Popen(args,
2282 stdout=subprocess.PIPE, close_fds=True,
2283 pass_fds=pass_fds)
2284 output, ignored = p.communicate()
2285 fds = set(map(int, output.split(b',')))
2286
2287 # the inheritable file descriptor must be inherited, so its inheritable
2288 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002289 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002290
2291 # inheritable flag must not be changed in the parent process
2292 self.assertEqual(os.get_inheritable(inheritable), True)
2293 self.assertEqual(os.get_inheritable(non_inheritable), False)
2294
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002295 def test_stdout_stdin_are_single_inout_fd(self):
2296 with io.open(os.devnull, "r+") as inout:
2297 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2298 stdout=inout, stdin=inout)
2299 p.wait()
2300
2301 def test_stdout_stderr_are_single_inout_fd(self):
2302 with io.open(os.devnull, "r+") as inout:
2303 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2304 stdout=inout, stderr=inout)
2305 p.wait()
2306
2307 def test_stderr_stdin_are_single_inout_fd(self):
2308 with io.open(os.devnull, "r+") as inout:
2309 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2310 stderr=inout, stdin=inout)
2311 p.wait()
2312
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002313 def test_wait_when_sigchild_ignored(self):
2314 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2315 sigchild_ignore = support.findfile("sigchild_ignore.py",
2316 subdir="subprocessdata")
2317 p = subprocess.Popen([sys.executable, sigchild_ignore],
2318 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2319 stdout, stderr = p.communicate()
2320 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002321 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002322 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002323
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002324 def test_select_unbuffered(self):
2325 # Issue #11459: bufsize=0 should really set the pipes as
2326 # unbuffered (and therefore let select() work properly).
2327 select = support.import_module("select")
2328 p = subprocess.Popen([sys.executable, "-c",
2329 'import sys;'
2330 'sys.stdout.write("apple")'],
2331 stdout=subprocess.PIPE,
2332 bufsize=0)
2333 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002334 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002335 try:
2336 self.assertEqual(f.read(4), b"appl")
2337 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2338 finally:
2339 p.wait()
2340
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002341 def test_zombie_fast_process_del(self):
2342 # Issue #12650: on Unix, if Popen.__del__() was called before the
2343 # process exited, it wouldn't be added to subprocess._active, and would
2344 # remain a zombie.
2345 # spawn a Popen, and delete its reference before it exits
2346 p = subprocess.Popen([sys.executable, "-c",
2347 'import sys, time;'
2348 'time.sleep(0.2)'],
2349 stdout=subprocess.PIPE,
2350 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002351 self.addCleanup(p.stdout.close)
2352 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002353 ident = id(p)
2354 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002355 with support.check_warnings(('', ResourceWarning)):
2356 p = None
2357
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002358 # check that p is in the active processes list
2359 self.assertIn(ident, [id(o) for o in subprocess._active])
2360
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002361 def test_leak_fast_process_del_killed(self):
2362 # Issue #12650: on Unix, if Popen.__del__() was called before the
2363 # process exited, and the process got killed by a signal, it would never
2364 # be removed from subprocess._active, which triggered a FD and memory
2365 # leak.
2366 # spawn a Popen, delete its reference and kill it
2367 p = subprocess.Popen([sys.executable, "-c",
2368 'import time;'
2369 'time.sleep(3)'],
2370 stdout=subprocess.PIPE,
2371 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002372 self.addCleanup(p.stdout.close)
2373 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002374 ident = id(p)
2375 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002376 with support.check_warnings(('', ResourceWarning)):
2377 p = None
2378
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002379 os.kill(pid, signal.SIGKILL)
2380 # check that p is in the active processes list
2381 self.assertIn(ident, [id(o) for o in subprocess._active])
2382
2383 # let some time for the process to exit, and create a new Popen: this
2384 # should trigger the wait() of p
2385 time.sleep(0.2)
Andrew Svetlov3438fa42012-12-17 23:35:18 +02002386 with self.assertRaises(OSError) as c:
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002387 with subprocess.Popen(['nonexisting_i_hope'],
2388 stdout=subprocess.PIPE,
2389 stderr=subprocess.PIPE) as proc:
2390 pass
2391 # p should have been wait()ed on, and removed from the _active list
2392 self.assertRaises(OSError, os.waitpid, pid, 0)
2393 self.assertNotIn(ident, [id(o) for o in subprocess._active])
2394
Charles-François Natali249cdc32013-08-25 18:24:45 +02002395 def test_close_fds_after_preexec(self):
2396 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2397
2398 # this FD is used as dup2() target by preexec_fn, and should be closed
2399 # in the child process
2400 fd = os.dup(1)
2401 self.addCleanup(os.close, fd)
2402
2403 p = subprocess.Popen([sys.executable, fd_status],
2404 stdout=subprocess.PIPE, close_fds=True,
2405 preexec_fn=lambda: os.dup2(1, fd))
2406 output, ignored = p.communicate()
2407
2408 remaining_fds = set(map(int, output.split(b',')))
2409
2410 self.assertNotIn(fd, remaining_fds)
2411
Victor Stinner8f437aa2014-10-05 17:25:19 +02002412 @support.cpython_only
2413 def test_fork_exec(self):
2414 # Issue #22290: fork_exec() must not crash on memory allocation failure
2415 # or other errors
2416 import _posixsubprocess
2417 gc_enabled = gc.isenabled()
2418 try:
2419 # Use a preexec function and enable the garbage collector
2420 # to force fork_exec() to re-enable the garbage collector
2421 # on error.
2422 func = lambda: None
2423 gc.enable()
2424
Victor Stinner8f437aa2014-10-05 17:25:19 +02002425 for args, exe_list, cwd, env_list in (
2426 (123, [b"exe"], None, [b"env"]),
2427 ([b"arg"], 123, None, [b"env"]),
2428 ([b"arg"], [b"exe"], 123, [b"env"]),
2429 ([b"arg"], [b"exe"], None, 123),
2430 ):
2431 with self.assertRaises(TypeError):
2432 _posixsubprocess.fork_exec(
2433 args, exe_list,
Serhiy Storchakae2546172017-04-19 23:59:02 +03002434 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02002435 -1, -1, -1, -1,
2436 1, 2, 3, 4,
2437 True, True, func)
2438 finally:
2439 if not gc_enabled:
2440 gc.disable()
2441
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002442 @support.cpython_only
2443 def test_fork_exec_sorted_fd_sanity_check(self):
2444 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
2445 import _posixsubprocess
Serhiy Storchakae2546172017-04-19 23:59:02 +03002446 class BadInt:
2447 first = True
2448 def __init__(self, value):
2449 self.value = value
2450 def __int__(self):
2451 if self.first:
2452 self.first = False
2453 return self.value
2454 raise ValueError
2455
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002456 gc_enabled = gc.isenabled()
2457 try:
2458 gc.enable()
2459
2460 for fds_to_keep in (
2461 (-1, 2, 3, 4, 5), # Negative number.
2462 ('str', 4), # Not an int.
2463 (18, 23, 42, 2**63), # Out of range.
2464 (5, 4), # Not sorted.
2465 (6, 7, 7, 8), # Duplicate.
Serhiy Storchakae2546172017-04-19 23:59:02 +03002466 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002467 ):
2468 with self.assertRaises(
2469 ValueError,
2470 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
2471 _posixsubprocess.fork_exec(
2472 [b"false"], [b"false"],
2473 True, fds_to_keep, None, [b"env"],
2474 -1, -1, -1, -1,
2475 1, 2, 3, 4,
2476 True, True, None)
2477 self.assertIn('fds_to_keep', str(c.exception))
2478 finally:
2479 if not gc_enabled:
2480 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02002481
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00002482 def test_communicate_BrokenPipeError_stdin_close(self):
2483 # By not setting stdout or stderr or a timeout we force the fast path
2484 # that just calls _stdin_write() internally due to our mock.
2485 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2486 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2487 mock_proc_stdin.close.side_effect = BrokenPipeError
2488 proc.communicate() # Should swallow BrokenPipeError from close.
2489 mock_proc_stdin.close.assert_called_with()
2490
2491 def test_communicate_BrokenPipeError_stdin_write(self):
2492 # By not setting stdout or stderr or a timeout we force the fast path
2493 # that just calls _stdin_write() internally due to our mock.
2494 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2495 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2496 mock_proc_stdin.write.side_effect = BrokenPipeError
2497 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
2498 mock_proc_stdin.write.assert_called_once_with(b'stuff')
2499 mock_proc_stdin.close.assert_called_once_with()
2500
2501 def test_communicate_BrokenPipeError_stdin_flush(self):
2502 # Setting stdin and stdout forces the ._communicate() code path.
2503 # python -h exits faster than python -c pass (but spams stdout).
2504 proc = subprocess.Popen([sys.executable, '-h'],
2505 stdin=subprocess.PIPE,
2506 stdout=subprocess.PIPE)
2507 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
2508 open(os.devnull, 'wb') as dev_null:
2509 mock_proc_stdin.flush.side_effect = BrokenPipeError
2510 # because _communicate registers a selector using proc.stdin...
2511 mock_proc_stdin.fileno.return_value = dev_null.fileno()
2512 # _communicate() should swallow BrokenPipeError from flush.
2513 proc.communicate(b'stuff')
2514 mock_proc_stdin.flush.assert_called_once_with()
2515
2516 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
2517 # Setting stdin and stdout forces the ._communicate() code path.
2518 # python -h exits faster than python -c pass (but spams stdout).
2519 proc = subprocess.Popen([sys.executable, '-h'],
2520 stdin=subprocess.PIPE,
2521 stdout=subprocess.PIPE)
2522 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2523 mock_proc_stdin.close.side_effect = BrokenPipeError
2524 # _communicate() should swallow BrokenPipeError from close.
2525 proc.communicate(timeout=999)
2526 mock_proc_stdin.close.assert_called_once_with()
2527
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002528 _libc_file_extensions = {
2529 'Linux': 'so.6',
Gregory P. Smith21d333b2017-01-22 20:54:42 -08002530 'Darwin': 'dylib',
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002531 }
Gregory P. Smith1fa08bc2017-01-22 22:19:38 -08002532 @unittest.skipIf(not ctypes, 'ctypes module required.')
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002533 @unittest.skipIf(platform.uname()[0] not in _libc_file_extensions,
2534 'Test requires a libc this code can load with ctypes.')
2535 @unittest.skipIf(not sys.executable, 'Test requires sys.executable.')
2536 def test_child_terminated_in_stopped_state(self):
2537 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
2538 PTRACE_TRACEME = 0 # From glibc and MacOS (PT_TRACE_ME).
2539 libc_name = 'libc.' + self._libc_file_extensions[platform.uname()[0]]
2540 libc = ctypes.CDLL(libc_name)
2541 if not hasattr(libc, 'ptrace'):
2542 raise unittest.SkipTest('ptrace() required.')
2543 test_ptrace = subprocess.Popen(
2544 [sys.executable, '-c', """if True:
2545 import ctypes
2546 libc = ctypes.CDLL({libc_name!r})
2547 libc.ptrace({PTRACE_TRACEME}, 0, 0)
2548 """.format(libc_name=libc_name, PTRACE_TRACEME=PTRACE_TRACEME)
2549 ])
2550 if test_ptrace.wait() != 0:
2551 raise unittest.SkipTest('ptrace() failed - unable to test.')
2552 child = subprocess.Popen(
2553 [sys.executable, '-c', """if True:
2554 import ctypes
2555 libc = ctypes.CDLL({libc_name!r})
2556 libc.ptrace({PTRACE_TRACEME}, 0, 0)
2557 libc.printf(ctypes.c_char_p(0xdeadbeef)) # Crash the process.
2558 """.format(libc_name=libc_name, PTRACE_TRACEME=PTRACE_TRACEME)
2559 ])
2560 try:
2561 returncode = child.wait()
2562 except Exception as e:
2563 child.kill() # Clean up the hung stopped process.
2564 raise e
2565 self.assertNotEqual(0, returncode)
2566 self.assertLess(returncode, 0) # signal death, likely SIGSEGV.
2567
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002568
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002569@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00002570class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002571
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002572 def test_startupinfo(self):
2573 # startupinfo argument
2574 # We uses hardcoded constants, because we do not want to
2575 # depend on win32all.
2576 STARTF_USESHOWWINDOW = 1
2577 SW_MAXIMIZE = 3
2578 startupinfo = subprocess.STARTUPINFO()
2579 startupinfo.dwFlags = STARTF_USESHOWWINDOW
2580 startupinfo.wShowWindow = SW_MAXIMIZE
2581 # Since Python is a console process, it won't be affected
2582 # by wShowWindow, but the argument should be silently
2583 # ignored
2584 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002585 startupinfo=startupinfo)
2586
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002587 def test_creationflags(self):
2588 # creationflags argument
2589 CREATE_NEW_CONSOLE = 16
2590 sys.stderr.write(" a DOS box should flash briefly ...\n")
2591 subprocess.call(sys.executable +
2592 ' -c "import time; time.sleep(0.25)"',
2593 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002594
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002595 def test_invalid_args(self):
2596 # invalid arguments should raise ValueError
2597 self.assertRaises(ValueError, subprocess.call,
2598 [sys.executable, "-c",
2599 "import sys; sys.exit(47)"],
2600 preexec_fn=lambda: 1)
2601 self.assertRaises(ValueError, subprocess.call,
2602 [sys.executable, "-c",
2603 "import sys; sys.exit(47)"],
2604 stdout=subprocess.PIPE,
2605 close_fds=True)
2606
2607 def test_close_fds(self):
2608 # close file descriptors
2609 rc = subprocess.call([sys.executable, "-c",
2610 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002611 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002612 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002613
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002614 def test_shell_sequence(self):
2615 # Run command through the shell (sequence)
2616 newenv = os.environ.copy()
2617 newenv["FRUIT"] = "physalis"
2618 p = subprocess.Popen(["set"], shell=1,
2619 stdout=subprocess.PIPE,
2620 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002621 with p:
2622 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00002623
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002624 def test_shell_string(self):
2625 # Run command through the shell (string)
2626 newenv = os.environ.copy()
2627 newenv["FRUIT"] = "physalis"
2628 p = subprocess.Popen("set", shell=1,
2629 stdout=subprocess.PIPE,
2630 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002631 with p:
2632 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002633
Steve Dower050acae2016-09-06 20:16:17 -07002634 def test_shell_encodings(self):
2635 # Run command through the shell (string)
2636 for enc in ['ansi', 'oem']:
2637 newenv = os.environ.copy()
2638 newenv["FRUIT"] = "physalis"
2639 p = subprocess.Popen("set", shell=1,
2640 stdout=subprocess.PIPE,
2641 env=newenv,
2642 encoding=enc)
2643 with p:
2644 self.assertIn("physalis", p.stdout.read(), enc)
2645
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002646 def test_call_string(self):
2647 # call() function with string argument on Windows
2648 rc = subprocess.call(sys.executable +
2649 ' -c "import sys; sys.exit(47)"')
2650 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002651
Florent Xicluna4886d242010-03-08 13:27:26 +00002652 def _kill_process(self, method, *args):
2653 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00002654 p = subprocess.Popen([sys.executable, "-c", """if 1:
2655 import sys, time
2656 sys.stdout.write('x\\n')
2657 sys.stdout.flush()
2658 time.sleep(30)
2659 """],
2660 stdin=subprocess.PIPE,
2661 stdout=subprocess.PIPE,
2662 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002663 with p:
2664 # Wait for the interpreter to be completely initialized before
2665 # sending any signal.
2666 p.stdout.read(1)
2667 getattr(p, method)(*args)
2668 _, stderr = p.communicate()
2669 self.assertStderrEqual(stderr, b'')
2670 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00002671 self.assertNotEqual(returncode, 0)
2672
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002673 def _kill_dead_process(self, method, *args):
2674 p = subprocess.Popen([sys.executable, "-c", """if 1:
2675 import sys, time
2676 sys.stdout.write('x\\n')
2677 sys.stdout.flush()
2678 sys.exit(42)
2679 """],
2680 stdin=subprocess.PIPE,
2681 stdout=subprocess.PIPE,
2682 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002683 with p:
2684 # Wait for the interpreter to be completely initialized before
2685 # sending any signal.
2686 p.stdout.read(1)
2687 # The process should end after this
2688 time.sleep(1)
2689 # This shouldn't raise even though the child is now dead
2690 getattr(p, method)(*args)
2691 _, stderr = p.communicate()
2692 self.assertStderrEqual(stderr, b'')
2693 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002694 self.assertEqual(rc, 42)
2695
Florent Xicluna4886d242010-03-08 13:27:26 +00002696 def test_send_signal(self):
2697 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00002698
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002699 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002700 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00002701
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002702 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002703 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00002704
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002705 def test_send_signal_dead(self):
2706 self._kill_dead_process('send_signal', signal.SIGTERM)
2707
2708 def test_kill_dead(self):
2709 self._kill_dead_process('kill')
2710
2711 def test_terminate_dead(self):
2712 self._kill_dead_process('terminate')
2713
Martin Panter23172bd2016-04-16 11:28:10 +00002714class MiscTests(unittest.TestCase):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002715 def test_getoutput(self):
2716 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
2717 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
2718 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00002719
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002720 # we use mkdtemp in the next line to create an empty directory
2721 # under our exclusive control; from that, we can invent a pathname
2722 # that we _know_ won't exist. This is guaranteed to fail.
2723 dir = None
2724 try:
2725 dir = tempfile.mkdtemp()
2726 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00002727 status, output = subprocess.getstatusoutput(
2728 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002729 self.assertNotEqual(status, 0)
2730 finally:
2731 if dir is not None:
2732 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00002733
Gregory P. Smithace55862015-04-07 15:57:54 -07002734 def test__all__(self):
2735 """Ensure that __all__ is populated properly."""
Martin Panter528619b2016-04-16 23:42:37 +00002736 intentionally_excluded = {"list2cmdline", "Handle"}
Gregory P. Smithace55862015-04-07 15:57:54 -07002737 exported = set(subprocess.__all__)
2738 possible_exports = set()
2739 import types
2740 for name, value in subprocess.__dict__.items():
2741 if name.startswith('_'):
2742 continue
2743 if isinstance(value, (types.ModuleType,)):
2744 continue
2745 possible_exports.add(name)
2746 self.assertEqual(exported, possible_exports - intentionally_excluded)
2747
2748
Martin Panter23172bd2016-04-16 11:28:10 +00002749@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
2750 "Test needs selectors.PollSelector")
2751class ProcessTestCaseNoPoll(ProcessTestCase):
2752 def setUp(self):
2753 self.orig_selector = subprocess._PopenSelector
2754 subprocess._PopenSelector = selectors.SelectSelector
2755 ProcessTestCase.setUp(self)
2756
2757 def tearDown(self):
2758 subprocess._PopenSelector = self.orig_selector
2759 ProcessTestCase.tearDown(self)
2760
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002761
Tim Golden126c2962010-08-11 14:20:40 +00002762@unittest.skipUnless(mswindows, "Windows-specific tests")
2763class CommandsWithSpaces (BaseTestCase):
2764
2765 def setUp(self):
2766 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03002767 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00002768 self.fname = fname.lower ()
2769 os.write(f, b"import sys;"
2770 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
2771 )
2772 os.close(f)
2773
2774 def tearDown(self):
2775 os.remove(self.fname)
2776 super().tearDown()
2777
2778 def with_spaces(self, *args, **kwargs):
2779 kwargs['stdout'] = subprocess.PIPE
2780 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02002781 with p:
2782 self.assertEqual(
2783 p.stdout.read ().decode("mbcs"),
2784 "2 [%r, 'ab cd']" % self.fname
2785 )
Tim Golden126c2962010-08-11 14:20:40 +00002786
2787 def test_shell_string_with_spaces(self):
2788 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002789 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2790 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002791
2792 def test_shell_sequence_with_spaces(self):
2793 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002794 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002795
2796 def test_noshell_string_with_spaces(self):
2797 # call() function with string argument with spaces on Windows
2798 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2799 "ab cd"))
2800
2801 def test_noshell_sequence_with_spaces(self):
2802 # call() function with sequence argument with spaces on Windows
2803 self.with_spaces([sys.executable, self.fname, "ab cd"])
2804
Brian Curtin79cdb662010-12-03 02:46:02 +00002805
Georg Brandla86b2622012-02-20 21:34:57 +01002806class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00002807
2808 def test_pipe(self):
2809 with subprocess.Popen([sys.executable, "-c",
2810 "import sys;"
2811 "sys.stdout.write('stdout');"
2812 "sys.stderr.write('stderr');"],
2813 stdout=subprocess.PIPE,
2814 stderr=subprocess.PIPE) as proc:
2815 self.assertEqual(proc.stdout.read(), b"stdout")
2816 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2817
2818 self.assertTrue(proc.stdout.closed)
2819 self.assertTrue(proc.stderr.closed)
2820
2821 def test_returncode(self):
2822 with subprocess.Popen([sys.executable, "-c",
2823 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002824 pass
2825 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002826 self.assertEqual(proc.returncode, 100)
2827
2828 def test_communicate_stdin(self):
2829 with subprocess.Popen([sys.executable, "-c",
2830 "import sys;"
2831 "sys.exit(sys.stdin.read() == 'context')"],
2832 stdin=subprocess.PIPE) as proc:
2833 proc.communicate(b"context")
2834 self.assertEqual(proc.returncode, 1)
2835
2836 def test_invalid_args(self):
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +01002837 with self.assertRaises((FileNotFoundError, PermissionError)) as c:
Brian Curtin79cdb662010-12-03 02:46:02 +00002838 with subprocess.Popen(['nonexisting_i_hope'],
2839 stdout=subprocess.PIPE,
2840 stderr=subprocess.PIPE) as proc:
2841 pass
2842
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002843 def test_broken_pipe_cleanup(self):
2844 """Broken pipe error should not prevent wait() (Issue 21619)"""
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002845 proc = subprocess.Popen([sys.executable, '-c', 'pass'],
Victor Stinner20f4bd42015-03-05 02:38:41 +01002846 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01002847 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002848 proc = proc.__enter__()
2849 # Prepare to send enough data to overflow any OS pipe buffering and
2850 # guarantee a broken pipe error. Data is held in BufferedWriter
2851 # buffer until closed.
2852 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002853 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002854 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02002855 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002856 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002857 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002858
Brian Curtin79cdb662010-12-03 02:46:02 +00002859
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002860if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002861 unittest.main()