blob: e63f9f254cd2b248451a3d3a6162716cdb1e8b3b [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
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700350 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700351 def test_cwd_with_relative_arg(self):
352 # Check that Popen looks for args[0] relative to cwd if args[0]
353 # is relative.
354 python_dir, python_base = self._split_python_path()
355 rel_python = os.path.join(os.curdir, python_base)
356 with support.temp_cwd() as wrong_dir:
357 # Before calling with the correct cwd, confirm that the call fails
358 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700359 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700360 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700361 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700362 [rel_python], cwd=wrong_dir)
363 python_dir = self._normalize_cwd(python_dir)
364 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
365
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700366 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700367 def test_cwd_with_relative_executable(self):
368 # Check that Popen looks for executable relative to cwd if executable
369 # is relative (and that executable takes precedence over args[0]).
370 python_dir, python_base = self._split_python_path()
371 rel_python = os.path.join(os.curdir, python_base)
372 doesntexist = "somethingyoudonthave"
373 with support.temp_cwd() as wrong_dir:
374 # Before calling with the correct cwd, confirm that the call fails
375 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700376 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700377 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700378 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700379 [doesntexist], executable=rel_python,
380 cwd=wrong_dir)
381 python_dir = self._normalize_cwd(python_dir)
382 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
383 cwd=python_dir)
384
385 def test_cwd_with_absolute_arg(self):
386 # Check that Popen can find the executable when the cwd is wrong
387 # if args[0] is an absolute path.
388 python_dir, python_base = self._split_python_path()
389 abs_python = os.path.join(python_dir, python_base)
390 rel_python = os.path.join(os.curdir, python_base)
Berker Peksagce643912015-05-06 06:33:17 +0300391 with support.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700392 # Before calling with an absolute path, confirm that using a
393 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700394 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700395 [rel_python], cwd=wrong_dir)
396 wrong_dir = self._normalize_cwd(wrong_dir)
397 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
398
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100399 @unittest.skipIf(sys.base_prefix != sys.prefix,
400 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000401 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700402 python_dir, python_base = self._split_python_path()
403 python_dir = self._normalize_cwd(python_dir)
404 self._assert_cwd(python_dir, "somethingyoudonthave",
405 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000406
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100407 @unittest.skipIf(sys.base_prefix != sys.prefix,
408 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000409 @unittest.skipIf(sysconfig.is_python_build(),
410 "need an installed Python. See #7774")
411 def test_executable_without_cwd(self):
412 # For a normal installation, it should work without 'cwd'
413 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700414 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
415 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000416
417 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000418 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000419 p = subprocess.Popen([sys.executable, "-c",
420 'import sys; sys.exit(sys.stdin.read() == "pear")'],
421 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000422 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000423 p.stdin.close()
424 p.wait()
425 self.assertEqual(p.returncode, 1)
426
427 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000428 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000429 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000430 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000431 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000432 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000433 os.lseek(d, 0, 0)
434 p = subprocess.Popen([sys.executable, "-c",
435 'import sys; sys.exit(sys.stdin.read() == "pear")'],
436 stdin=d)
437 p.wait()
438 self.assertEqual(p.returncode, 1)
439
440 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000441 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000442 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000443 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000444 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000445 tf.seek(0)
446 p = subprocess.Popen([sys.executable, "-c",
447 'import sys; sys.exit(sys.stdin.read() == "pear")'],
448 stdin=tf)
449 p.wait()
450 self.assertEqual(p.returncode, 1)
451
452 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000453 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000454 p = subprocess.Popen([sys.executable, "-c",
455 'import sys; sys.stdout.write("orange")'],
456 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200457 with p:
458 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000459
460 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000461 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000462 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000463 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000464 d = tf.fileno()
465 p = subprocess.Popen([sys.executable, "-c",
466 'import sys; sys.stdout.write("orange")'],
467 stdout=d)
468 p.wait()
469 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000470 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000471
472 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000473 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000474 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000475 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000476 p = subprocess.Popen([sys.executable, "-c",
477 'import sys; sys.stdout.write("orange")'],
478 stdout=tf)
479 p.wait()
480 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000481 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000482
483 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000484 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000485 p = subprocess.Popen([sys.executable, "-c",
486 'import sys; sys.stderr.write("strawberry")'],
487 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200488 with p:
489 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000490
491 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000492 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000493 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000494 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000495 d = tf.fileno()
496 p = subprocess.Popen([sys.executable, "-c",
497 'import sys; sys.stderr.write("strawberry")'],
498 stderr=d)
499 p.wait()
500 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000501 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000502
503 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000504 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000505 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000506 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000507 p = subprocess.Popen([sys.executable, "-c",
508 'import sys; sys.stderr.write("strawberry")'],
509 stderr=tf)
510 p.wait()
511 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000512 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000513
Martin Panterc7635892016-05-13 01:54:44 +0000514 def test_stderr_redirect_with_no_stdout_redirect(self):
515 # test stderr=STDOUT while stdout=None (not set)
516
517 # - grandchild prints to stderr
518 # - child redirects grandchild's stderr to its stdout
519 # - the parent should get grandchild's stderr in child's stdout
520 p = subprocess.Popen([sys.executable, "-c",
521 'import sys, subprocess;'
522 'rc = subprocess.call([sys.executable, "-c",'
523 ' "import sys;"'
524 ' "sys.stderr.write(\'42\')"],'
525 ' stderr=subprocess.STDOUT);'
526 'sys.exit(rc)'],
527 stdout=subprocess.PIPE,
528 stderr=subprocess.PIPE)
529 stdout, stderr = p.communicate()
530 #NOTE: stdout should get stderr from grandchild
531 self.assertStderrEqual(stdout, b'42')
532 self.assertStderrEqual(stderr, b'') # should be empty
533 self.assertEqual(p.returncode, 0)
534
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000535 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000536 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000537 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000538 'import sys;'
539 'sys.stdout.write("apple");'
540 'sys.stdout.flush();'
541 'sys.stderr.write("orange")'],
542 stdout=subprocess.PIPE,
543 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200544 with p:
545 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000546
547 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000548 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000549 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000550 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000551 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000552 'import sys;'
553 'sys.stdout.write("apple");'
554 'sys.stdout.flush();'
555 'sys.stderr.write("orange")'],
556 stdout=tf,
557 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000558 p.wait()
559 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000560 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000561
Thomas Wouters89f507f2006-12-13 04:49:30 +0000562 def test_stdout_filedes_of_stdout(self):
563 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200564 # To avoid printing the text on stdout, we do something similar to
565 # test_stdout_none (see above). The parent subprocess calls the child
566 # subprocess passing stdout=1, and this test uses stdout=PIPE in
567 # order to capture and check the output of the parent. See #11963.
568 code = ('import sys, subprocess; '
569 'rc = subprocess.call([sys.executable, "-c", '
570 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
571 'b\'test with stdout=1\'))"], stdout=1); '
572 'assert rc == 18')
573 p = subprocess.Popen([sys.executable, "-c", code],
574 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
575 self.addCleanup(p.stdout.close)
576 self.addCleanup(p.stderr.close)
577 out, err = p.communicate()
578 self.assertEqual(p.returncode, 0, err)
579 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000580
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200581 def test_stdout_devnull(self):
582 p = subprocess.Popen([sys.executable, "-c",
583 'for i in range(10240):'
584 'print("x" * 1024)'],
585 stdout=subprocess.DEVNULL)
586 p.wait()
587 self.assertEqual(p.stdout, None)
588
589 def test_stderr_devnull(self):
590 p = subprocess.Popen([sys.executable, "-c",
591 'import sys\n'
592 'for i in range(10240):'
593 'sys.stderr.write("x" * 1024)'],
594 stderr=subprocess.DEVNULL)
595 p.wait()
596 self.assertEqual(p.stderr, None)
597
598 def test_stdin_devnull(self):
599 p = subprocess.Popen([sys.executable, "-c",
600 'import sys;'
601 'sys.stdin.read(1)'],
602 stdin=subprocess.DEVNULL)
603 p.wait()
604 self.assertEqual(p.stdin, None)
605
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000606 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000607 newenv = os.environ.copy()
608 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200609 with subprocess.Popen([sys.executable, "-c",
610 'import sys,os;'
611 'sys.stdout.write(os.getenv("FRUIT"))'],
612 stdout=subprocess.PIPE,
613 env=newenv) as p:
614 stdout, stderr = p.communicate()
615 self.assertEqual(stdout, b"orange")
616
Victor Stinner62d51182011-06-23 01:02:25 +0200617 # Windows requires at least the SYSTEMROOT environment variable to start
618 # Python
619 @unittest.skipIf(sys.platform == 'win32',
620 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200621 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200622 'the python library cannot be loaded '
623 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200624 def test_empty_env(self):
625 with subprocess.Popen([sys.executable, "-c",
626 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200627 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200628 stdout=subprocess.PIPE,
629 env={}) as p:
630 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200631 self.assertIn(stdout.strip(),
632 (b"[]",
633 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
634 # environment
635 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000636
Peter Astrandcbac93c2005-03-03 20:24:28 +0000637 def test_communicate_stdin(self):
638 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000639 'import sys;'
640 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000641 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000642 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000643 self.assertEqual(p.returncode, 1)
644
645 def test_communicate_stdout(self):
646 p = subprocess.Popen([sys.executable, "-c",
647 'import sys; sys.stdout.write("pineapple")'],
648 stdout=subprocess.PIPE)
649 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000650 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000651 self.assertEqual(stderr, None)
652
653 def test_communicate_stderr(self):
654 p = subprocess.Popen([sys.executable, "-c",
655 'import sys; sys.stderr.write("pineapple")'],
656 stderr=subprocess.PIPE)
657 (stdout, stderr) = p.communicate()
658 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000659 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000660
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000661 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000662 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000663 'import sys,os;'
664 'sys.stderr.write("pineapple");'
665 'sys.stdout.write(sys.stdin.read())'],
666 stdin=subprocess.PIPE,
667 stdout=subprocess.PIPE,
668 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000669 self.addCleanup(p.stdout.close)
670 self.addCleanup(p.stderr.close)
671 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000672 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000673 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000674 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000675
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400676 def test_communicate_timeout(self):
677 p = subprocess.Popen([sys.executable, "-c",
678 'import sys,os,time;'
679 'sys.stderr.write("pineapple\\n");'
680 'time.sleep(1);'
681 'sys.stderr.write("pear\\n");'
682 'sys.stdout.write(sys.stdin.read())'],
683 universal_newlines=True,
684 stdin=subprocess.PIPE,
685 stdout=subprocess.PIPE,
686 stderr=subprocess.PIPE)
687 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
688 timeout=0.3)
689 # Make sure we can keep waiting for it, and that we get the whole output
690 # after it completes.
691 (stdout, stderr) = p.communicate()
692 self.assertEqual(stdout, "banana")
693 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
694
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700695 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200696 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400697 p = subprocess.Popen([sys.executable, "-c",
698 'import sys,os,time;'
699 'sys.stdout.write("a" * (64 * 1024));'
700 'time.sleep(0.2);'
701 'sys.stdout.write("a" * (64 * 1024));'
702 'time.sleep(0.2);'
703 'sys.stdout.write("a" * (64 * 1024));'
704 'time.sleep(0.2);'
705 'sys.stdout.write("a" * (64 * 1024));'],
706 stdout=subprocess.PIPE)
707 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
708 (stdout, _) = p.communicate()
709 self.assertEqual(len(stdout), 4 * 64 * 1024)
710
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000711 # Test for the fd leak reported in http://bugs.python.org/issue2791.
712 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000713 for stdin_pipe in (False, True):
714 for stdout_pipe in (False, True):
715 for stderr_pipe in (False, True):
716 options = {}
717 if stdin_pipe:
718 options['stdin'] = subprocess.PIPE
719 if stdout_pipe:
720 options['stdout'] = subprocess.PIPE
721 if stderr_pipe:
722 options['stderr'] = subprocess.PIPE
723 if not options:
724 continue
725 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
726 p.communicate()
727 if p.stdin is not None:
728 self.assertTrue(p.stdin.closed)
729 if p.stdout is not None:
730 self.assertTrue(p.stdout.closed)
731 if p.stderr is not None:
732 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000733
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000734 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000735 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000736 p = subprocess.Popen([sys.executable, "-c",
737 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000738 (stdout, stderr) = p.communicate()
739 self.assertEqual(stdout, None)
740 self.assertEqual(stderr, None)
741
742 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000743 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000744 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000745 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000746 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000747 os.close(x)
748 os.close(y)
749 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000750 'import sys,os;'
751 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200752 'sys.stderr.write("x" * %d);'
753 'sys.stdout.write(sys.stdin.read())' %
754 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000755 stdin=subprocess.PIPE,
756 stdout=subprocess.PIPE,
757 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000758 self.addCleanup(p.stdout.close)
759 self.addCleanup(p.stderr.close)
760 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200761 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000762 (stdout, stderr) = p.communicate(string_to_write)
763 self.assertEqual(stdout, string_to_write)
764
765 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000766 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000767 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000768 'import sys,os;'
769 'sys.stdout.write(sys.stdin.read())'],
770 stdin=subprocess.PIPE,
771 stdout=subprocess.PIPE,
772 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000773 self.addCleanup(p.stdout.close)
774 self.addCleanup(p.stderr.close)
775 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000776 p.stdin.write(b"banana")
777 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000778 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000779 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000780
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000781 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000782 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000783 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200784 'buf = sys.stdout.buffer;'
785 'buf.write(sys.stdin.readline().encode());'
786 'buf.flush();'
787 'buf.write(b"line2\\n");'
788 'buf.flush();'
789 'buf.write(sys.stdin.read().encode());'
790 'buf.flush();'
791 'buf.write(b"line4\\n");'
792 'buf.flush();'
793 'buf.write(b"line5\\r\\n");'
794 'buf.flush();'
795 'buf.write(b"line6\\r");'
796 'buf.flush();'
797 'buf.write(b"\\nline7");'
798 'buf.flush();'
799 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200800 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000801 stdout=subprocess.PIPE,
802 universal_newlines=1)
Victor Stinner7438c612016-05-20 12:43:15 +0200803 with p:
804 p.stdin.write("line1\n")
805 p.stdin.flush()
806 self.assertEqual(p.stdout.readline(), "line1\n")
807 p.stdin.write("line3\n")
808 p.stdin.close()
809 self.addCleanup(p.stdout.close)
810 self.assertEqual(p.stdout.readline(),
811 "line2\n")
812 self.assertEqual(p.stdout.read(6),
813 "line3\n")
814 self.assertEqual(p.stdout.read(),
815 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000816
817 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000818 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000819 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000820 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200821 'buf = sys.stdout.buffer;'
822 'buf.write(b"line2\\n");'
823 'buf.flush();'
824 'buf.write(b"line4\\n");'
825 'buf.flush();'
826 'buf.write(b"line5\\r\\n");'
827 'buf.flush();'
828 'buf.write(b"line6\\r");'
829 'buf.flush();'
830 'buf.write(b"\\nline7");'
831 'buf.flush();'
832 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200833 stderr=subprocess.PIPE,
834 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000835 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000836 self.addCleanup(p.stdout.close)
837 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000838 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200839 self.assertEqual(stdout,
840 "line2\nline4\nline5\nline6\nline7\nline8")
841
842 def test_universal_newlines_communicate_stdin(self):
843 # universal newlines through communicate(), with only stdin
844 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300845 'import sys,os;' + SETBINARY + textwrap.dedent('''
846 s = sys.stdin.readline()
847 assert s == "line1\\n", repr(s)
848 s = sys.stdin.read()
849 assert s == "line3\\n", repr(s)
850 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200851 stdin=subprocess.PIPE,
852 universal_newlines=1)
853 (stdout, stderr) = p.communicate("line1\nline3\n")
854 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000855
Andrew Svetlovf3765072012-08-14 18:35:17 +0300856 def test_universal_newlines_communicate_input_none(self):
857 # Test communicate(input=None) with universal newlines.
858 #
859 # We set stdout to PIPE because, as of this writing, a different
860 # code path is tested when the number of pipes is zero or one.
861 p = subprocess.Popen([sys.executable, "-c", "pass"],
862 stdin=subprocess.PIPE,
863 stdout=subprocess.PIPE,
864 universal_newlines=True)
865 p.communicate()
866 self.assertEqual(p.returncode, 0)
867
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300868 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300869 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300870 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300871 'import sys,os;' + SETBINARY + textwrap.dedent('''
872 s = sys.stdin.buffer.readline()
873 sys.stdout.buffer.write(s)
874 sys.stdout.buffer.write(b"line2\\r")
875 sys.stderr.buffer.write(b"eline2\\n")
876 s = sys.stdin.buffer.read()
877 sys.stdout.buffer.write(s)
878 sys.stdout.buffer.write(b"line4\\n")
879 sys.stdout.buffer.write(b"line5\\r\\n")
880 sys.stderr.buffer.write(b"eline6\\r")
881 sys.stderr.buffer.write(b"eline7\\r\\nz")
882 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300883 stdin=subprocess.PIPE,
884 stderr=subprocess.PIPE,
885 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300886 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300887 self.addCleanup(p.stdout.close)
888 self.addCleanup(p.stderr.close)
889 (stdout, stderr) = p.communicate("line1\nline3\n")
890 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300891 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300892 # Python debug build push something like "[42442 refs]\n"
893 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300894 # Don't use assertStderrEqual because it strips CR and LF from output.
895 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300896
Andrew Svetlov82860712012-08-19 22:13:41 +0300897 def test_universal_newlines_communicate_encodings(self):
898 # Check that universal newlines mode works for various encodings,
899 # in particular for encodings in the UTF-16 and UTF-32 families.
900 # See issue #15595.
901 #
902 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
903 # without, and UTF-16 and UTF-32.
904 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +0300905 code = ("import sys; "
906 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
907 encoding)
908 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -0700909 # We set stdin to be non-None because, as of this writing,
910 # a different code path is used when the number of pipes is
911 # zero or one.
912 popen = subprocess.Popen(args,
913 stdin=subprocess.PIPE,
914 stdout=subprocess.PIPE,
915 encoding=encoding)
916 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +0300917 self.assertEqual(stdout, '1\n2\n3\n4')
918
Steve Dower050acae2016-09-06 20:16:17 -0700919 def test_communicate_errors(self):
920 for errors, expected in [
921 ('ignore', ''),
922 ('replace', '\ufffd\ufffd'),
923 ('surrogateescape', '\udc80\udc80'),
924 ('backslashreplace', '\\x80\\x80'),
925 ]:
926 code = ("import sys; "
927 r"sys.stdout.buffer.write(b'[\x80\x80]')")
928 args = [sys.executable, '-c', code]
929 # We set stdin to be non-None because, as of this writing,
930 # a different code path is used when the number of pipes is
931 # zero or one.
932 popen = subprocess.Popen(args,
933 stdin=subprocess.PIPE,
934 stdout=subprocess.PIPE,
935 encoding='utf-8',
936 errors=errors)
937 stdout, stderr = popen.communicate(input='')
938 self.assertEqual(stdout, '[{}]'.format(expected))
939
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000940 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000941 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000942 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000943 max_handles = 1026 # too much for most UNIX systems
944 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000945 max_handles = 2050 # too much for (at least some) Windows setups
946 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400947 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000948 try:
949 for i in range(max_handles):
950 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400951 tmpfile = os.path.join(tmpdir, support.TESTFN)
952 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000953 except OSError as e:
954 if e.errno != errno.EMFILE:
955 raise
956 break
957 else:
958 self.skipTest("failed to reach the file descriptor limit "
959 "(tried %d)" % max_handles)
960 # Close a couple of them (should be enough for a subprocess)
961 for i in range(10):
962 os.close(handles.pop())
963 # Loop creating some subprocesses. If one of them leaks some fds,
964 # the next loop iteration will fail by reaching the max fd limit.
965 for i in range(15):
966 p = subprocess.Popen([sys.executable, "-c",
967 "import sys;"
968 "sys.stdout.write(sys.stdin.read())"],
969 stdin=subprocess.PIPE,
970 stdout=subprocess.PIPE,
971 stderr=subprocess.PIPE)
972 data = p.communicate(b"lime")[0]
973 self.assertEqual(data, b"lime")
974 finally:
975 for h in handles:
976 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400977 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000978
979 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000980 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
981 '"a b c" d e')
982 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
983 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000984 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
985 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000986 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
987 'a\\\\\\b "de fg" h')
988 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
989 'a\\\\\\"b c d')
990 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
991 '"a\\\\b c" d e')
992 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
993 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000994 self.assertEqual(subprocess.list2cmdline(['ab', '']),
995 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000996
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000997 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200998 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +0200999 "import os; os.read(0, 1)"],
1000 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001001 self.addCleanup(p.stdin.close)
1002 self.assertIsNone(p.poll())
1003 os.write(p.stdin.fileno(), b'A')
1004 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001005 # Subsequent invocations should just return the returncode
1006 self.assertEqual(p.poll(), 0)
1007
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001008 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001009 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001010 self.assertEqual(p.wait(), 0)
1011 # Subsequent invocations should just return the returncode
1012 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001013
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001014 def test_wait_timeout(self):
1015 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001016 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001017 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001018 p.wait(timeout=0.0001)
1019 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -04001020 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
1021 # time to start.
1022 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001023
Gregory P. Smithf0e98c52016-11-20 16:25:14 -08001024 def test_wait_endtime(self):
1025 """Confirm that the deprecated endtime parameter warns."""
1026 p = subprocess.Popen([sys.executable, "-c", "pass"])
1027 try:
1028 with self.assertWarns(DeprecationWarning) as warn_cm:
1029 p.wait(endtime=time.time()+0.01)
1030 except subprocess.TimeoutExpired:
1031 pass # We're not testing endtime timeout behavior.
1032 finally:
1033 p.kill()
1034 self.assertIn('test_subprocess.py', warn_cm.filename)
1035 self.assertIn('endtime', str(warn_cm.warning))
1036
Peter Astrand738131d2004-11-30 21:04:45 +00001037 def test_invalid_bufsize(self):
1038 # an invalid type of the bufsize argument should raise
1039 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001040 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +00001041 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001042
Guido van Rossum46a05a72007-06-07 21:56:45 +00001043 def test_bufsize_is_none(self):
1044 # bufsize=None should be the same as bufsize=0.
1045 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
1046 self.assertEqual(p.wait(), 0)
1047 # Again with keyword arg
1048 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
1049 self.assertEqual(p.wait(), 0)
1050
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001051 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1052 # subprocess may deadlock with bufsize=1, see issue #21332
1053 with subprocess.Popen([sys.executable, "-c", "import sys;"
1054 "sys.stdout.write(sys.stdin.readline());"
1055 "sys.stdout.flush()"],
1056 stdin=subprocess.PIPE,
1057 stdout=subprocess.PIPE,
1058 stderr=subprocess.DEVNULL,
1059 bufsize=1,
1060 universal_newlines=universal_newlines) as p:
1061 p.stdin.write(line) # expect that it flushes the line in text mode
1062 os.close(p.stdin.fileno()) # close it without flushing the buffer
1063 read_line = p.stdout.readline()
1064 try:
1065 p.stdin.close()
1066 except OSError:
1067 pass
1068 p.stdin = None
1069 self.assertEqual(p.returncode, 0)
1070 self.assertEqual(read_line, expected)
1071
1072 def test_bufsize_equal_one_text_mode(self):
1073 # line is flushed in text mode with bufsize=1.
1074 # we should get the full line in return
1075 line = "line\n"
1076 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1077
1078 def test_bufsize_equal_one_binary_mode(self):
1079 # line is not flushed in binary mode with bufsize=1.
1080 # we should get empty response
1081 line = b'line' + os.linesep.encode() # assume ascii-based locale
1082 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
1083
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001084 def test_leaking_fds_on_error(self):
1085 # see bug #5179: Popen leaks file descriptors to PIPEs if
1086 # the child fails to execute; this will eventually exhaust
1087 # the maximum number of open fds. 1024 seems a very common
1088 # value for that limit, but Windows has 2048, so we loop
1089 # 1024 times (each call leaked two fds).
1090 for i in range(1024):
Andrew Svetlov3438fa42012-12-17 23:35:18 +02001091 with self.assertRaises(OSError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001092 subprocess.Popen(['nonexisting_i_hope'],
1093 stdout=subprocess.PIPE,
1094 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -04001095 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -04001096 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001097 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001098
Antoine Pitroua8392712013-08-30 23:38:13 +02001099 @unittest.skipIf(threading is None, "threading required")
1100 def test_double_close_on_error(self):
1101 # Issue #18851
1102 fds = []
1103 def open_fds():
1104 for i in range(20):
1105 fds.extend(os.pipe())
1106 time.sleep(0.001)
1107 t = threading.Thread(target=open_fds)
1108 t.start()
1109 try:
1110 with self.assertRaises(EnvironmentError):
1111 subprocess.Popen(['nonexisting_i_hope'],
1112 stdin=subprocess.PIPE,
1113 stdout=subprocess.PIPE,
1114 stderr=subprocess.PIPE)
1115 finally:
1116 t.join()
1117 exc = None
1118 for fd in fds:
1119 # If a double close occurred, some of those fds will
1120 # already have been closed by mistake, and os.close()
1121 # here will raise.
1122 try:
1123 os.close(fd)
1124 except OSError as e:
1125 exc = e
1126 if exc is not None:
1127 raise exc
1128
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001129 @unittest.skipIf(threading is None, "threading required")
1130 def test_threadsafe_wait(self):
1131 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1132 proc = subprocess.Popen([sys.executable, '-c',
1133 'import time; time.sleep(12)'])
1134 self.assertEqual(proc.returncode, None)
1135 results = []
1136
1137 def kill_proc_timer_thread():
1138 results.append(('thread-start-poll-result', proc.poll()))
1139 # terminate it from the thread and wait for the result.
1140 proc.kill()
1141 proc.wait()
1142 results.append(('thread-after-kill-and-wait', proc.returncode))
1143 # this wait should be a no-op given the above.
1144 proc.wait()
1145 results.append(('thread-after-second-wait', proc.returncode))
1146
1147 # This is a timing sensitive test, the failure mode is
1148 # triggered when both the main thread and this thread are in
1149 # the wait() call at once. The delay here is to allow the
1150 # main thread to most likely be blocked in its wait() call.
1151 t = threading.Timer(0.2, kill_proc_timer_thread)
1152 t.start()
1153
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001154 if mswindows:
1155 expected_errorcode = 1
1156 else:
1157 # Should be -9 because of the proc.kill() from the thread.
1158 expected_errorcode = -9
1159
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001160 # Wait for the process to finish; the thread should kill it
1161 # long before it finishes on its own. Supplying a timeout
1162 # triggers a different code path for better coverage.
1163 proc.wait(timeout=20)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001164 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001165 msg="unexpected result in wait from main thread")
1166
1167 # This should be a no-op with no change in returncode.
1168 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001169 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001170 msg="unexpected result in second main wait.")
1171
1172 t.join()
1173 # Ensure that all of the thread results are as expected.
1174 # When a race condition occurs in wait(), the returncode could
1175 # be set by the wrong thread that doesn't actually have it
1176 # leading to an incorrect value.
1177 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001178 ('thread-after-kill-and-wait', expected_errorcode),
1179 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001180 results)
1181
Victor Stinnerb3693582010-05-21 20:13:12 +00001182 def test_issue8780(self):
1183 # Ensure that stdout is inherited from the parent
1184 # if stdout=PIPE is not used
1185 code = ';'.join((
1186 'import subprocess, sys',
1187 'retcode = subprocess.call('
1188 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1189 'assert retcode == 0'))
1190 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001191 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001192
Tim Goldenaf5ac392010-08-06 13:03:56 +00001193 def test_handles_closed_on_exception(self):
1194 # If CreateProcess exits with an error, ensure the
1195 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001196 ifhandle, ifname = tempfile.mkstemp()
1197 ofhandle, ofname = tempfile.mkstemp()
1198 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001199 try:
1200 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1201 stderr=efhandle)
1202 except OSError:
1203 os.close(ifhandle)
1204 os.remove(ifname)
1205 os.close(ofhandle)
1206 os.remove(ofname)
1207 os.close(efhandle)
1208 os.remove(efname)
1209 self.assertFalse(os.path.exists(ifname))
1210 self.assertFalse(os.path.exists(ofname))
1211 self.assertFalse(os.path.exists(efname))
1212
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001213 def test_communicate_epipe(self):
1214 # Issue 10963: communicate() should hide EPIPE
1215 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1216 stdin=subprocess.PIPE,
1217 stdout=subprocess.PIPE,
1218 stderr=subprocess.PIPE)
1219 self.addCleanup(p.stdout.close)
1220 self.addCleanup(p.stderr.close)
1221 self.addCleanup(p.stdin.close)
1222 p.communicate(b"x" * 2**20)
1223
1224 def test_communicate_epipe_only_stdin(self):
1225 # Issue 10963: communicate() should hide EPIPE
1226 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1227 stdin=subprocess.PIPE)
1228 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001229 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001230 p.communicate(b"x" * 2**20)
1231
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001232 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1233 "Requires signal.SIGUSR1")
1234 @unittest.skipUnless(hasattr(os, 'kill'),
1235 "Requires os.kill")
1236 @unittest.skipUnless(hasattr(os, 'getppid'),
1237 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001238 def test_communicate_eintr(self):
1239 # Issue #12493: communicate() should handle EINTR
1240 def handler(signum, frame):
1241 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001242 old_handler = signal.signal(signal.SIGUSR1, handler)
1243 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001244
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001245 args = [sys.executable, "-c",
1246 'import os, signal;'
1247 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001248 for stream in ('stdout', 'stderr'):
1249 kw = {stream: subprocess.PIPE}
1250 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001251 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001252 process.communicate()
1253
Tim Peterse718f612004-10-12 21:51:32 +00001254
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001255 # This test is Linux-ish specific for simplicity to at least have
1256 # some coverage. It is not a platform specific bug.
1257 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1258 "Linux specific")
1259 def test_failed_child_execute_fd_leak(self):
1260 """Test for the fork() failure fd leak reported in issue16327."""
1261 fd_directory = '/proc/%d/fd' % os.getpid()
1262 fds_before_popen = os.listdir(fd_directory)
1263 with self.assertRaises(PopenTestException):
1264 PopenExecuteChildRaises(
1265 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
1266 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1267
1268 # NOTE: This test doesn't verify that the real _execute_child
1269 # does not close the file descriptors itself on the way out
1270 # during an exception. Code inspection has confirmed that.
1271
1272 fds_after_exception = os.listdir(fd_directory)
1273 self.assertEqual(fds_before_popen, fds_after_exception)
1274
Gregory P. Smith6e730002015-04-14 16:14:25 -07001275
1276class RunFuncTestCase(BaseTestCase):
1277 def run_python(self, code, **kwargs):
1278 """Run Python code in a subprocess using subprocess.run"""
1279 argv = [sys.executable, "-c", code]
1280 return subprocess.run(argv, **kwargs)
1281
1282 def test_returncode(self):
1283 # call() function with sequence argument
1284 cp = self.run_python("import sys; sys.exit(47)")
1285 self.assertEqual(cp.returncode, 47)
1286 with self.assertRaises(subprocess.CalledProcessError):
1287 cp.check_returncode()
1288
1289 def test_check(self):
1290 with self.assertRaises(subprocess.CalledProcessError) as c:
1291 self.run_python("import sys; sys.exit(47)", check=True)
1292 self.assertEqual(c.exception.returncode, 47)
1293
1294 def test_check_zero(self):
1295 # check_returncode shouldn't raise when returncode is zero
1296 cp = self.run_python("import sys; sys.exit(0)", check=True)
1297 self.assertEqual(cp.returncode, 0)
1298
1299 def test_timeout(self):
1300 # run() function with timeout argument; we want to test that the child
1301 # process gets killed when the timeout expires. If the child isn't
1302 # killed, this call will deadlock since subprocess.run waits for the
1303 # child.
1304 with self.assertRaises(subprocess.TimeoutExpired):
1305 self.run_python("while True: pass", timeout=0.0001)
1306
1307 def test_capture_stdout(self):
1308 # capture stdout with zero return code
1309 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1310 self.assertIn(b'BDFL', cp.stdout)
1311
1312 def test_capture_stderr(self):
1313 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1314 stderr=subprocess.PIPE)
1315 self.assertIn(b'BDFL', cp.stderr)
1316
1317 def test_check_output_stdin_arg(self):
1318 # run() can be called with stdin set to a file
1319 tf = tempfile.TemporaryFile()
1320 self.addCleanup(tf.close)
1321 tf.write(b'pear')
1322 tf.seek(0)
1323 cp = self.run_python(
1324 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1325 stdin=tf, stdout=subprocess.PIPE)
1326 self.assertIn(b'PEAR', cp.stdout)
1327
1328 def test_check_output_input_arg(self):
1329 # check_output() can be called with input set to a string
1330 cp = self.run_python(
1331 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1332 input=b'pear', stdout=subprocess.PIPE)
1333 self.assertIn(b'PEAR', cp.stdout)
1334
1335 def test_check_output_stdin_with_input_arg(self):
1336 # run() refuses to accept 'stdin' with 'input'
1337 tf = tempfile.TemporaryFile()
1338 self.addCleanup(tf.close)
1339 tf.write(b'pear')
1340 tf.seek(0)
1341 with self.assertRaises(ValueError,
1342 msg="Expected ValueError when stdin and input args supplied.") as c:
1343 output = self.run_python("print('will not be run')",
1344 stdin=tf, input=b'hare')
1345 self.assertIn('stdin', c.exception.args[0])
1346 self.assertIn('input', c.exception.args[0])
1347
1348 def test_check_output_timeout(self):
1349 with self.assertRaises(subprocess.TimeoutExpired) as c:
1350 cp = self.run_python((
1351 "import sys, time\n"
1352 "sys.stdout.write('BDFL')\n"
1353 "sys.stdout.flush()\n"
1354 "time.sleep(3600)"),
1355 # Some heavily loaded buildbots (sparc Debian 3.x) require
1356 # this much time to start and print.
1357 timeout=3, stdout=subprocess.PIPE)
1358 self.assertEqual(c.exception.output, b'BDFL')
1359 # output is aliased to stdout
1360 self.assertEqual(c.exception.stdout, b'BDFL')
1361
1362 def test_run_kwargs(self):
1363 newenv = os.environ.copy()
1364 newenv["FRUIT"] = "banana"
1365 cp = self.run_python(('import sys, os;'
1366 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1367 env=newenv)
1368 self.assertEqual(cp.returncode, 33)
1369
1370
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001371@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001372class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001373
Gregory P. Smith5591b022012-10-10 03:34:47 -07001374 def setUp(self):
1375 super().setUp()
1376 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1377
1378 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001379 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001380 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001381 except OSError as e:
1382 # This avoids hard coding the errno value or the OS perror()
1383 # string and instead capture the exception that we want to see
1384 # below for comparison.
1385 desired_exception = e
Gregory P. Smith5591b022012-10-10 03:34:47 -07001386 desired_exception.strerror += ': ' + repr(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001387 else:
Martin Pantereb995702016-07-28 01:11:04 +00001388 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001389 self._nonexistent_dir)
1390 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001391
Gregory P. Smith5591b022012-10-10 03:34:47 -07001392 def test_exception_cwd(self):
1393 """Test error in the child raised in the parent for a bad cwd."""
1394 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001395 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001396 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001397 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001398 except OSError as e:
1399 # Test that the child process chdir failure actually makes
1400 # it up to the parent process as the correct exception.
1401 self.assertEqual(desired_exception.errno, e.errno)
1402 self.assertEqual(desired_exception.strerror, e.strerror)
1403 else:
1404 self.fail("Expected OSError: %s" % desired_exception)
1405
Gregory P. Smith5591b022012-10-10 03:34:47 -07001406 def test_exception_bad_executable(self):
1407 """Test error in the child raised in the parent for a bad executable."""
1408 desired_exception = self._get_chdir_exception()
1409 try:
1410 p = subprocess.Popen([sys.executable, "-c", ""],
1411 executable=self._nonexistent_dir)
1412 except OSError as e:
1413 # Test that the child process exec failure actually makes
1414 # it up to the parent process as the correct exception.
1415 self.assertEqual(desired_exception.errno, e.errno)
1416 self.assertEqual(desired_exception.strerror, e.strerror)
1417 else:
1418 self.fail("Expected OSError: %s" % desired_exception)
1419
1420 def test_exception_bad_args_0(self):
1421 """Test error in the child raised in the parent for a bad args[0]."""
1422 desired_exception = self._get_chdir_exception()
1423 try:
1424 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1425 except OSError as e:
1426 # Test that the child process exec failure actually makes
1427 # it up to the parent process as the correct exception.
1428 self.assertEqual(desired_exception.errno, e.errno)
1429 self.assertEqual(desired_exception.strerror, e.strerror)
1430 else:
1431 self.fail("Expected OSError: %s" % desired_exception)
1432
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001433 def test_restore_signals(self):
1434 # Code coverage for both values of restore_signals to make sure it
1435 # at least does not blow up.
1436 # A test for behavior would be complex. Contributions welcome.
1437 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1438 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1439
1440 def test_start_new_session(self):
1441 # For code coverage of calling setsid(). We don't care if we get an
1442 # EPERM error from it depending on the test execution environment, that
1443 # still indicates that it was called.
1444 try:
1445 output = subprocess.check_output(
1446 [sys.executable, "-c",
1447 "import os; print(os.getpgid(os.getpid()))"],
1448 start_new_session=True)
1449 except OSError as e:
1450 if e.errno != errno.EPERM:
1451 raise
1452 else:
1453 parent_pgid = os.getpgid(os.getpid())
1454 child_pgid = int(output)
1455 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001456
1457 def test_run_abort(self):
1458 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001459 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001460 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001461 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001462 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001463 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001464
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001465 def test_CalledProcessError_str_signal(self):
1466 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
1467 error_string = str(err)
1468 # We're relying on the repr() of the signal.Signals intenum to provide
1469 # the word signal, the signal name and the numeric value.
1470 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00001471 # We're not being specific about the signal name as some signals have
1472 # multiple names and which name is revealed can vary.
1473 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001474 self.assertIn(str(signal.SIGABRT), error_string)
1475
1476 def test_CalledProcessError_str_unknown_signal(self):
1477 err = subprocess.CalledProcessError(-9876543, "fake cmd")
1478 error_string = str(err)
1479 self.assertIn("unknown signal 9876543.", error_string)
1480
1481 def test_CalledProcessError_str_non_zero(self):
1482 err = subprocess.CalledProcessError(2, "fake cmd")
1483 error_string = str(err)
1484 self.assertIn("non-zero exit status 2.", error_string)
1485
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001486 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001487 # DISCLAIMER: Setting environment variables is *not* a good use
1488 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001489 p = subprocess.Popen([sys.executable, "-c",
1490 'import sys,os;'
1491 'sys.stdout.write(os.getenv("FRUIT"))'],
1492 stdout=subprocess.PIPE,
1493 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02001494 with p:
1495 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001496
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001497 def test_preexec_exception(self):
1498 def raise_it():
1499 raise ValueError("What if two swallows carried a coconut?")
1500 try:
1501 p = subprocess.Popen([sys.executable, "-c", ""],
1502 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001503 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001504 self.assertTrue(
1505 subprocess._posixsubprocess,
1506 "Expected a ValueError from the preexec_fn")
1507 except ValueError as e:
1508 self.assertIn("coconut", e.args[0])
1509 else:
1510 self.fail("Exception raised by preexec_fn did not make it "
1511 "to the parent process.")
1512
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001513 class _TestExecuteChildPopen(subprocess.Popen):
1514 """Used to test behavior at the end of _execute_child."""
1515 def __init__(self, testcase, *args, **kwargs):
1516 self._testcase = testcase
1517 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001518
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001519 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001520 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001521 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001522 finally:
1523 # Open a bunch of file descriptors and verify that
1524 # none of them are the same as the ones the Popen
1525 # instance is using for stdin/stdout/stderr.
1526 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1527 for _ in range(8)]
1528 try:
1529 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001530 self._testcase.assertNotIn(
1531 fd, (self.stdin.fileno(), self.stdout.fileno(),
1532 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001533 msg="At least one fd was closed early.")
1534 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01001535 for fd in devzero_fds:
1536 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001537
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001538 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1539 def test_preexec_errpipe_does_not_double_close_pipes(self):
1540 """Issue16140: Don't double close pipes on preexec error."""
1541
1542 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08001543 raise subprocess.SubprocessError(
1544 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001545
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08001546 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001547 self._TestExecuteChildPopen(
1548 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001549 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1550 stderr=subprocess.PIPE, preexec_fn=raise_it)
1551
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001552 def test_preexec_gc_module_failure(self):
1553 # This tests the code that disables garbage collection if the child
1554 # process will execute any Python.
1555 def raise_runtime_error():
1556 raise RuntimeError("this shouldn't escape")
1557 enabled = gc.isenabled()
1558 orig_gc_disable = gc.disable
1559 orig_gc_isenabled = gc.isenabled
1560 try:
1561 gc.disable()
1562 self.assertFalse(gc.isenabled())
1563 subprocess.call([sys.executable, '-c', ''],
1564 preexec_fn=lambda: None)
1565 self.assertFalse(gc.isenabled(),
1566 "Popen enabled gc when it shouldn't.")
1567
1568 gc.enable()
1569 self.assertTrue(gc.isenabled())
1570 subprocess.call([sys.executable, '-c', ''],
1571 preexec_fn=lambda: None)
1572 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1573
1574 gc.disable = raise_runtime_error
1575 self.assertRaises(RuntimeError, subprocess.Popen,
1576 [sys.executable, '-c', ''],
1577 preexec_fn=lambda: None)
1578
1579 del gc.isenabled # force an AttributeError
1580 self.assertRaises(AttributeError, subprocess.Popen,
1581 [sys.executable, '-c', ''],
1582 preexec_fn=lambda: None)
1583 finally:
1584 gc.disable = orig_gc_disable
1585 gc.isenabled = orig_gc_isenabled
1586 if not enabled:
1587 gc.disable()
1588
Martin Panterf7fdbda2015-12-05 09:51:52 +00001589 @unittest.skipIf(
1590 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00001591 def test_preexec_fork_failure(self):
1592 # The internal code did not preserve the previous exception when
1593 # re-enabling garbage collection
1594 try:
1595 from resource import getrlimit, setrlimit, RLIMIT_NPROC
1596 except ImportError as err:
1597 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
1598 limits = getrlimit(RLIMIT_NPROC)
1599 [_, hard] = limits
1600 setrlimit(RLIMIT_NPROC, (0, hard))
1601 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00001602 try:
Martin Panterafdd5132015-11-30 02:21:41 +00001603 subprocess.call([sys.executable, '-c', ''],
1604 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00001605 except BlockingIOError:
1606 # Forking should raise EAGAIN, translated to BlockingIOError
1607 pass
1608 else:
1609 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00001610
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001611 def test_args_string(self):
1612 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03001613 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001614 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001615 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001616 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001617 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1618 sys.executable)
1619 os.chmod(fname, 0o700)
1620 p = subprocess.Popen(fname)
1621 p.wait()
1622 os.remove(fname)
1623 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001624
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001625 def test_invalid_args(self):
1626 # invalid arguments should raise ValueError
1627 self.assertRaises(ValueError, subprocess.call,
1628 [sys.executable, "-c",
1629 "import sys; sys.exit(47)"],
1630 startupinfo=47)
1631 self.assertRaises(ValueError, subprocess.call,
1632 [sys.executable, "-c",
1633 "import sys; sys.exit(47)"],
1634 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001635
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001636 def test_shell_sequence(self):
1637 # Run command through the shell (sequence)
1638 newenv = os.environ.copy()
1639 newenv["FRUIT"] = "apple"
1640 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1641 stdout=subprocess.PIPE,
1642 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001643 with p:
1644 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001645
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001646 def test_shell_string(self):
1647 # Run command through the shell (string)
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")
Christian Heimesa342c012008-04-20 21:01:16 +00001655
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001656 def test_call_string(self):
1657 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03001658 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001659 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001660 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001661 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001662 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1663 sys.executable)
1664 os.chmod(fname, 0o700)
1665 rc = subprocess.call(fname)
1666 os.remove(fname)
1667 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001668
Stefan Krah9542cc62010-07-19 14:20:53 +00001669 def test_specific_shell(self):
1670 # Issue #9265: Incorrect name passed as arg[0].
1671 shells = []
1672 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1673 for name in ['bash', 'ksh']:
1674 sh = os.path.join(prefix, name)
1675 if os.path.isfile(sh):
1676 shells.append(sh)
1677 if not shells: # Will probably work for any shell but csh.
1678 self.skipTest("bash or ksh required for this test")
1679 sh = '/bin/sh'
1680 if os.path.isfile(sh) and not os.path.islink(sh):
1681 # Test will fail if /bin/sh is a symlink to csh.
1682 shells.append(sh)
1683 for sh in shells:
1684 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1685 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02001686 with p:
1687 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00001688
Florent Xicluna4886d242010-03-08 13:27:26 +00001689 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001690 # Do not inherit file handles from the parent.
1691 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07001692 # Also set the SIGINT handler to the default to make sure it's not
1693 # being ignored (some tests rely on that.)
1694 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
1695 try:
1696 p = subprocess.Popen([sys.executable, "-c", """if 1:
1697 import sys, time
1698 sys.stdout.write('x\\n')
1699 sys.stdout.flush()
1700 time.sleep(30)
1701 """],
1702 close_fds=True,
1703 stdin=subprocess.PIPE,
1704 stdout=subprocess.PIPE,
1705 stderr=subprocess.PIPE)
1706 finally:
1707 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001708 # Wait for the interpreter to be completely initialized before
1709 # sending any signal.
1710 p.stdout.read(1)
1711 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001712 return p
1713
Charles-François Natali53221e32013-01-12 16:52:20 +01001714 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1715 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001716 def _kill_dead_process(self, method, *args):
1717 # Do not inherit file handles from the parent.
1718 # It should fix failures on some platforms.
1719 p = subprocess.Popen([sys.executable, "-c", """if 1:
1720 import sys, time
1721 sys.stdout.write('x\\n')
1722 sys.stdout.flush()
1723 """],
1724 close_fds=True,
1725 stdin=subprocess.PIPE,
1726 stdout=subprocess.PIPE,
1727 stderr=subprocess.PIPE)
1728 # Wait for the interpreter to be completely initialized before
1729 # sending any signal.
1730 p.stdout.read(1)
1731 # The process should end after this
1732 time.sleep(1)
1733 # This shouldn't raise even though the child is now dead
1734 getattr(p, method)(*args)
1735 p.communicate()
1736
Florent Xicluna4886d242010-03-08 13:27:26 +00001737 def test_send_signal(self):
1738 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001739 _, stderr = p.communicate()
1740 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001741 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001742
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001743 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001744 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001745 _, stderr = p.communicate()
1746 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001747 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001748
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001749 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001750 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001751 _, stderr = p.communicate()
1752 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001753 self.assertEqual(p.wait(), -signal.SIGTERM)
1754
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001755 def test_send_signal_dead(self):
1756 # Sending a signal to a dead process
1757 self._kill_dead_process('send_signal', signal.SIGINT)
1758
1759 def test_kill_dead(self):
1760 # Killing a dead process
1761 self._kill_dead_process('kill')
1762
1763 def test_terminate_dead(self):
1764 # Terminating a dead process
1765 self._kill_dead_process('terminate')
1766
Victor Stinnerdaf45552013-08-28 00:53:59 +02001767 def _save_fds(self, save_fds):
1768 fds = []
1769 for fd in save_fds:
1770 inheritable = os.get_inheritable(fd)
1771 saved = os.dup(fd)
1772 fds.append((fd, saved, inheritable))
1773 return fds
1774
1775 def _restore_fds(self, fds):
1776 for fd, saved, inheritable in fds:
1777 os.dup2(saved, fd, inheritable=inheritable)
1778 os.close(saved)
1779
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001780 def check_close_std_fds(self, fds):
1781 # Issue #9905: test that subprocess pipes still work properly with
1782 # some standard fds closed
1783 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02001784 saved_fds = self._save_fds(fds)
1785 for fd, saved, inheritable in saved_fds:
1786 if fd == 0:
1787 stdin = saved
1788 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001789 try:
1790 for fd in fds:
1791 os.close(fd)
1792 out, err = subprocess.Popen([sys.executable, "-c",
1793 'import sys;'
1794 'sys.stdout.write("apple");'
1795 'sys.stdout.flush();'
1796 'sys.stderr.write("orange")'],
1797 stdin=stdin,
1798 stdout=subprocess.PIPE,
1799 stderr=subprocess.PIPE).communicate()
1800 err = support.strip_python_stderr(err)
1801 self.assertEqual((out, err), (b'apple', b'orange'))
1802 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001803 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001804
1805 def test_close_fd_0(self):
1806 self.check_close_std_fds([0])
1807
1808 def test_close_fd_1(self):
1809 self.check_close_std_fds([1])
1810
1811 def test_close_fd_2(self):
1812 self.check_close_std_fds([2])
1813
1814 def test_close_fds_0_1(self):
1815 self.check_close_std_fds([0, 1])
1816
1817 def test_close_fds_0_2(self):
1818 self.check_close_std_fds([0, 2])
1819
1820 def test_close_fds_1_2(self):
1821 self.check_close_std_fds([1, 2])
1822
1823 def test_close_fds_0_1_2(self):
1824 # Issue #10806: test that subprocess pipes still work properly with
1825 # all standard fds closed.
1826 self.check_close_std_fds([0, 1, 2])
1827
Gregory P. Smith53dd8162013-12-01 16:03:24 -08001828 def test_small_errpipe_write_fd(self):
1829 """Issue #15798: Popen should work when stdio fds are available."""
1830 new_stdin = os.dup(0)
1831 new_stdout = os.dup(1)
1832 try:
1833 os.close(0)
1834 os.close(1)
1835
1836 # Side test: if errpipe_write fails to have its CLOEXEC
1837 # flag set this should cause the parent to think the exec
1838 # failed. Extremely unlikely: everyone supports CLOEXEC.
1839 subprocess.Popen([
1840 sys.executable, "-c",
1841 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
1842 finally:
1843 # Restore original stdin and stdout
1844 os.dup2(new_stdin, 0)
1845 os.dup2(new_stdout, 1)
1846 os.close(new_stdin)
1847 os.close(new_stdout)
1848
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001849 def test_remapping_std_fds(self):
1850 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03001851 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001852 try:
1853 temp_fds = [fd for fd, fname in temps]
1854
1855 # unlink the files -- we won't need to reopen them
1856 for fd, fname in temps:
1857 os.unlink(fname)
1858
1859 # write some data to what will become stdin, and rewind
1860 os.write(temp_fds[1], b"STDIN")
1861 os.lseek(temp_fds[1], 0, 0)
1862
1863 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02001864 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001865 try:
1866 # duplicate the file objects over the standard fd's
1867 for fd, temp_fd in enumerate(temp_fds):
1868 os.dup2(temp_fd, fd)
1869
1870 # now use those files in the "wrong" order, so that subprocess
1871 # has to rearrange them in the child
1872 p = subprocess.Popen([sys.executable, "-c",
1873 'import sys; got = sys.stdin.read();'
1874 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1875 stdin=temp_fds[1],
1876 stdout=temp_fds[2],
1877 stderr=temp_fds[0])
1878 p.wait()
1879 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001880 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001881
1882 for fd in temp_fds:
1883 os.lseek(fd, 0, 0)
1884
1885 out = os.read(temp_fds[2], 1024)
1886 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1887 self.assertEqual(out, b"got STDIN")
1888 self.assertEqual(err, b"err")
1889
1890 finally:
1891 for fd in temp_fds:
1892 os.close(fd)
1893
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001894 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1895 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03001896 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001897 temp_fds = [fd for fd, fname in temps]
1898 try:
1899 # unlink the files -- we won't need to reopen them
1900 for fd, fname in temps:
1901 os.unlink(fname)
1902
1903 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02001904 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001905 try:
1906 # duplicate the temp files over the standard fd's 0, 1, 2
1907 for fd, temp_fd in enumerate(temp_fds):
1908 os.dup2(temp_fd, fd)
1909
1910 # write some data to what will become stdin, and rewind
1911 os.write(stdin_no, b"STDIN")
1912 os.lseek(stdin_no, 0, 0)
1913
1914 # now use those files in the given order, so that subprocess
1915 # has to rearrange them in the child
1916 p = subprocess.Popen([sys.executable, "-c",
1917 'import sys; got = sys.stdin.read();'
1918 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1919 stdin=stdin_no,
1920 stdout=stdout_no,
1921 stderr=stderr_no)
1922 p.wait()
1923
1924 for fd in temp_fds:
1925 os.lseek(fd, 0, 0)
1926
1927 out = os.read(stdout_no, 1024)
1928 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1929 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001930 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001931
1932 self.assertEqual(out, b"got STDIN")
1933 self.assertEqual(err, b"err")
1934
1935 finally:
1936 for fd in temp_fds:
1937 os.close(fd)
1938
1939 # When duping fds, if there arises a situation where one of the fds is
1940 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1941 # This tests all combinations of this.
1942 def test_swap_fds(self):
1943 self.check_swap_fds(0, 1, 2)
1944 self.check_swap_fds(0, 2, 1)
1945 self.check_swap_fds(1, 0, 2)
1946 self.check_swap_fds(1, 2, 0)
1947 self.check_swap_fds(2, 0, 1)
1948 self.check_swap_fds(2, 1, 0)
1949
Victor Stinner13bb71c2010-04-23 21:41:56 +00001950 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001951 def prepare():
1952 raise ValueError("surrogate:\uDCff")
1953
1954 try:
1955 subprocess.call(
1956 [sys.executable, "-c", "pass"],
1957 preexec_fn=prepare)
1958 except ValueError as err:
1959 # Pure Python implementations keeps the message
1960 self.assertIsNone(subprocess._posixsubprocess)
1961 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001962 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00001963 # _posixsubprocess uses a default message
1964 self.assertIsNotNone(subprocess._posixsubprocess)
1965 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1966 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001967 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00001968
Victor Stinner13bb71c2010-04-23 21:41:56 +00001969 def test_undecodable_env(self):
1970 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01001971 encoded_value = value.encode("ascii", "surrogateescape")
1972
Victor Stinner13bb71c2010-04-23 21:41:56 +00001973 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001974 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001975 env = os.environ.copy()
1976 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01001977 # Use C locale to get ASCII for the locale encoding to force
Victor Stinner89f3ad12010-10-14 10:43:31 +00001978 # surrogate-escaping of \xFF in the child process; otherwise it can
1979 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001980 env['LC_ALL'] = 'C'
Victor Stinner5323fb02013-11-19 23:46:06 +01001981 if sys.platform.startswith("aix"):
1982 # On AIX, the C locale uses the Latin1 encoding
1983 decoded_value = encoded_value.decode("latin1", "surrogateescape")
1984 else:
1985 # On other UNIXes, the C locale uses the ASCII encoding
1986 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001987 stdout = subprocess.check_output(
1988 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001989 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001990 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01001991 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001992
1993 # test bytes
1994 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001995 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001996 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01001997 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001998 stdout = subprocess.check_output(
1999 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002000 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002001 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002002 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002003
Victor Stinnerb745a742010-05-18 17:17:23 +00002004 def test_bytes_program(self):
2005 abs_program = os.fsencode(sys.executable)
2006 path, program = os.path.split(sys.executable)
2007 program = os.fsencode(program)
2008
2009 # absolute bytes path
2010 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00002011 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002012
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002013 # absolute bytes path as a string
2014 cmd = b"'" + abs_program + b"' -c pass"
2015 exitcode = subprocess.call(cmd, shell=True)
2016 self.assertEqual(exitcode, 0)
2017
Victor Stinnerb745a742010-05-18 17:17:23 +00002018 # bytes program, unicode PATH
2019 env = os.environ.copy()
2020 env["PATH"] = path
2021 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002022 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002023
2024 # bytes program, bytes PATH
2025 envb = os.environb.copy()
2026 envb[b"PATH"] = os.fsencode(path)
2027 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002028 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002029
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002030 def test_pipe_cloexec(self):
2031 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2032 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2033
2034 p1 = subprocess.Popen([sys.executable, sleeper],
2035 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2036 stderr=subprocess.PIPE, close_fds=False)
2037
2038 self.addCleanup(p1.communicate, b'')
2039
2040 p2 = subprocess.Popen([sys.executable, fd_status],
2041 stdout=subprocess.PIPE, close_fds=False)
2042
2043 output, error = p2.communicate()
2044 result_fds = set(map(int, output.split(b',')))
2045 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2046 p1.stderr.fileno()])
2047
2048 self.assertFalse(result_fds & unwanted_fds,
2049 "Expected no fds from %r to be open in child, "
2050 "found %r" %
2051 (unwanted_fds, result_fds & unwanted_fds))
2052
2053 def test_pipe_cloexec_real_tools(self):
2054 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2055 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2056
2057 subdata = b'zxcvbn'
2058 data = subdata * 4 + b'\n'
2059
2060 p1 = subprocess.Popen([sys.executable, qcat],
2061 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2062 close_fds=False)
2063
2064 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2065 stdin=p1.stdout, stdout=subprocess.PIPE,
2066 close_fds=False)
2067
2068 self.addCleanup(p1.wait)
2069 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002070 def kill_p1():
2071 try:
2072 p1.terminate()
2073 except ProcessLookupError:
2074 pass
2075 def kill_p2():
2076 try:
2077 p2.terminate()
2078 except ProcessLookupError:
2079 pass
2080 self.addCleanup(kill_p1)
2081 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002082
2083 p1.stdin.write(data)
2084 p1.stdin.close()
2085
2086 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2087
2088 self.assertTrue(readfiles, "The child hung")
2089 self.assertEqual(p2.stdout.read(), data)
2090
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002091 p1.stdout.close()
2092 p2.stdout.close()
2093
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002094 def test_close_fds(self):
2095 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2096
2097 fds = os.pipe()
2098 self.addCleanup(os.close, fds[0])
2099 self.addCleanup(os.close, fds[1])
2100
2101 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002102 # add a bunch more fds
2103 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002104 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002105 self.addCleanup(os.close, fd)
2106 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002107
Victor Stinnerdaf45552013-08-28 00:53:59 +02002108 for fd in open_fds:
2109 os.set_inheritable(fd, True)
2110
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002111 p = subprocess.Popen([sys.executable, fd_status],
2112 stdout=subprocess.PIPE, close_fds=False)
2113 output, ignored = p.communicate()
2114 remaining_fds = set(map(int, output.split(b',')))
2115
2116 self.assertEqual(remaining_fds & open_fds, open_fds,
2117 "Some fds were closed")
2118
2119 p = subprocess.Popen([sys.executable, fd_status],
2120 stdout=subprocess.PIPE, close_fds=True)
2121 output, ignored = p.communicate()
2122 remaining_fds = set(map(int, output.split(b',')))
2123
2124 self.assertFalse(remaining_fds & open_fds,
2125 "Some fds were left open")
2126 self.assertIn(1, remaining_fds, "Subprocess failed")
2127
Gregory P. Smith8facece2012-01-21 14:01:08 -08002128 # Keep some of the fd's we opened open in the subprocess.
2129 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2130 fds_to_keep = set(open_fds.pop() for _ in range(8))
2131 p = subprocess.Popen([sys.executable, fd_status],
2132 stdout=subprocess.PIPE, close_fds=True,
2133 pass_fds=())
2134 output, ignored = p.communicate()
2135 remaining_fds = set(map(int, output.split(b',')))
2136
2137 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
2138 "Some fds not in pass_fds were left open")
2139 self.assertIn(1, remaining_fds, "Subprocess failed")
2140
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002141
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002142 @unittest.skipIf(sys.platform.startswith("freebsd") and
2143 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2144 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002145 def test_close_fds_when_max_fd_is_lowered(self):
2146 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2147 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2148
Gregory P. Smith634aa682014-06-15 17:51:04 -07002149 # This launches the meat of the test in a child process to
2150 # avoid messing with the larger unittest processes maximum
2151 # number of file descriptors.
2152 # This process launches:
2153 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2154 # a bunch of high open fds above the new lower rlimit.
2155 # Those are reported via stdout before launching a new
2156 # process with close_fds=False to run the actual test:
2157 # +--> The TEST: This one launches a fd_status.py
2158 # subprocess with close_fds=True so we can find out if
2159 # any of the fds above the lowered rlimit are still open.
2160 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2161 '''
2162 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002163 open_fds = set()
2164 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002165 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002166 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002167 open_fds.add(fd)
2168
2169 # Leave a two pairs of low ones available for use by the
2170 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002171 # We also leave 10 more open as some Python buildbots run into
2172 # "too many open files" errors during the test if we do not.
2173 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002174 os.close(fd)
2175 open_fds.remove(fd)
2176
2177 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002178 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002179 os.set_inheritable(fd, True)
2180
2181 max_fd_open = max(open_fds)
2182
Gregory P. Smith634aa682014-06-15 17:51:04 -07002183 # Communicate the open_fds to the parent unittest.TestCase process.
2184 print(','.join(map(str, sorted(open_fds))))
2185 sys.stdout.flush()
2186
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002187 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2188 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002189 # 29 is lower than the highest fds we are leaving open.
2190 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002191 # Launch a new Python interpreter with our low fd rlim_cur that
2192 # inherits open fds above that limit. It then uses subprocess
2193 # with close_fds=True to get a report of open fds in the child.
2194 # An explicit list of fds to check is passed to fd_status.py as
2195 # letting fd_status rely on its default logic would miss the
2196 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002197 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002198 [sys.executable, '-c',
2199 textwrap.dedent("""
2200 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002201 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002202 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002203 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002204 """.format(max_fd=max_fd_open+1))],
2205 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002206 finally:
2207 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002208 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002209
2210 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002211 output_lines = output.splitlines()
2212 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002213 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002214 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2215 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002216
Gregory P. Smith634aa682014-06-15 17:51:04 -07002217 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002218 msg="Some fds were left open.")
2219
2220
Victor Stinner88701e22011-06-01 13:13:04 +02002221 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2222 # descriptor of a pipe closed in the parent process is valid in the
2223 # child process according to fstat(), but the mode of the file
2224 # descriptor is invalid, and read or write raise an error.
2225 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002226 def test_pass_fds(self):
2227 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2228
2229 open_fds = set()
2230
2231 for x in range(5):
2232 fds = os.pipe()
2233 self.addCleanup(os.close, fds[0])
2234 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002235 os.set_inheritable(fds[0], True)
2236 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002237 open_fds.update(fds)
2238
2239 for fd in open_fds:
2240 p = subprocess.Popen([sys.executable, fd_status],
2241 stdout=subprocess.PIPE, close_fds=True,
2242 pass_fds=(fd, ))
2243 output, ignored = p.communicate()
2244
2245 remaining_fds = set(map(int, output.split(b',')))
2246 to_be_closed = open_fds - {fd}
2247
2248 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2249 self.assertFalse(remaining_fds & to_be_closed,
2250 "fd to be closed passed")
2251
2252 # pass_fds overrides close_fds with a warning.
2253 with self.assertWarns(RuntimeWarning) as context:
2254 self.assertFalse(subprocess.call(
2255 [sys.executable, "-c", "import sys; sys.exit(0)"],
2256 close_fds=False, pass_fds=(fd, )))
2257 self.assertIn('overriding close_fds', str(context.warning))
2258
Victor Stinnerdaf45552013-08-28 00:53:59 +02002259 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002260 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002261
2262 inheritable, non_inheritable = os.pipe()
2263 self.addCleanup(os.close, inheritable)
2264 self.addCleanup(os.close, non_inheritable)
2265 os.set_inheritable(inheritable, True)
2266 os.set_inheritable(non_inheritable, False)
2267 pass_fds = (inheritable, non_inheritable)
2268 args = [sys.executable, script]
2269 args += list(map(str, pass_fds))
2270
2271 p = subprocess.Popen(args,
2272 stdout=subprocess.PIPE, close_fds=True,
2273 pass_fds=pass_fds)
2274 output, ignored = p.communicate()
2275 fds = set(map(int, output.split(b',')))
2276
2277 # the inheritable file descriptor must be inherited, so its inheritable
2278 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002279 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002280
2281 # inheritable flag must not be changed in the parent process
2282 self.assertEqual(os.get_inheritable(inheritable), True)
2283 self.assertEqual(os.get_inheritable(non_inheritable), False)
2284
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002285 def test_stdout_stdin_are_single_inout_fd(self):
2286 with io.open(os.devnull, "r+") as inout:
2287 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2288 stdout=inout, stdin=inout)
2289 p.wait()
2290
2291 def test_stdout_stderr_are_single_inout_fd(self):
2292 with io.open(os.devnull, "r+") as inout:
2293 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2294 stdout=inout, stderr=inout)
2295 p.wait()
2296
2297 def test_stderr_stdin_are_single_inout_fd(self):
2298 with io.open(os.devnull, "r+") as inout:
2299 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2300 stderr=inout, stdin=inout)
2301 p.wait()
2302
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002303 def test_wait_when_sigchild_ignored(self):
2304 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2305 sigchild_ignore = support.findfile("sigchild_ignore.py",
2306 subdir="subprocessdata")
2307 p = subprocess.Popen([sys.executable, sigchild_ignore],
2308 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2309 stdout, stderr = p.communicate()
2310 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002311 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002312 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002313
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002314 def test_select_unbuffered(self):
2315 # Issue #11459: bufsize=0 should really set the pipes as
2316 # unbuffered (and therefore let select() work properly).
2317 select = support.import_module("select")
2318 p = subprocess.Popen([sys.executable, "-c",
2319 'import sys;'
2320 'sys.stdout.write("apple")'],
2321 stdout=subprocess.PIPE,
2322 bufsize=0)
2323 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002324 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002325 try:
2326 self.assertEqual(f.read(4), b"appl")
2327 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2328 finally:
2329 p.wait()
2330
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002331 def test_zombie_fast_process_del(self):
2332 # Issue #12650: on Unix, if Popen.__del__() was called before the
2333 # process exited, it wouldn't be added to subprocess._active, and would
2334 # remain a zombie.
2335 # spawn a Popen, and delete its reference before it exits
2336 p = subprocess.Popen([sys.executable, "-c",
2337 'import sys, time;'
2338 'time.sleep(0.2)'],
2339 stdout=subprocess.PIPE,
2340 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002341 self.addCleanup(p.stdout.close)
2342 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002343 ident = id(p)
2344 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002345 with support.check_warnings(('', ResourceWarning)):
2346 p = None
2347
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002348 # check that p is in the active processes list
2349 self.assertIn(ident, [id(o) for o in subprocess._active])
2350
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002351 def test_leak_fast_process_del_killed(self):
2352 # Issue #12650: on Unix, if Popen.__del__() was called before the
2353 # process exited, and the process got killed by a signal, it would never
2354 # be removed from subprocess._active, which triggered a FD and memory
2355 # leak.
2356 # spawn a Popen, delete its reference and kill it
2357 p = subprocess.Popen([sys.executable, "-c",
2358 'import time;'
2359 'time.sleep(3)'],
2360 stdout=subprocess.PIPE,
2361 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002362 self.addCleanup(p.stdout.close)
2363 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002364 ident = id(p)
2365 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002366 with support.check_warnings(('', ResourceWarning)):
2367 p = None
2368
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002369 os.kill(pid, signal.SIGKILL)
2370 # check that p is in the active processes list
2371 self.assertIn(ident, [id(o) for o in subprocess._active])
2372
2373 # let some time for the process to exit, and create a new Popen: this
2374 # should trigger the wait() of p
2375 time.sleep(0.2)
Andrew Svetlov3438fa42012-12-17 23:35:18 +02002376 with self.assertRaises(OSError) as c:
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002377 with subprocess.Popen(['nonexisting_i_hope'],
2378 stdout=subprocess.PIPE,
2379 stderr=subprocess.PIPE) as proc:
2380 pass
2381 # p should have been wait()ed on, and removed from the _active list
2382 self.assertRaises(OSError, os.waitpid, pid, 0)
2383 self.assertNotIn(ident, [id(o) for o in subprocess._active])
2384
Charles-François Natali249cdc32013-08-25 18:24:45 +02002385 def test_close_fds_after_preexec(self):
2386 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2387
2388 # this FD is used as dup2() target by preexec_fn, and should be closed
2389 # in the child process
2390 fd = os.dup(1)
2391 self.addCleanup(os.close, fd)
2392
2393 p = subprocess.Popen([sys.executable, fd_status],
2394 stdout=subprocess.PIPE, close_fds=True,
2395 preexec_fn=lambda: os.dup2(1, fd))
2396 output, ignored = p.communicate()
2397
2398 remaining_fds = set(map(int, output.split(b',')))
2399
2400 self.assertNotIn(fd, remaining_fds)
2401
Victor Stinner8f437aa2014-10-05 17:25:19 +02002402 @support.cpython_only
2403 def test_fork_exec(self):
2404 # Issue #22290: fork_exec() must not crash on memory allocation failure
2405 # or other errors
2406 import _posixsubprocess
2407 gc_enabled = gc.isenabled()
2408 try:
2409 # Use a preexec function and enable the garbage collector
2410 # to force fork_exec() to re-enable the garbage collector
2411 # on error.
2412 func = lambda: None
2413 gc.enable()
2414
Victor Stinner8f437aa2014-10-05 17:25:19 +02002415 for args, exe_list, cwd, env_list in (
2416 (123, [b"exe"], None, [b"env"]),
2417 ([b"arg"], 123, None, [b"env"]),
2418 ([b"arg"], [b"exe"], 123, [b"env"]),
2419 ([b"arg"], [b"exe"], None, 123),
2420 ):
2421 with self.assertRaises(TypeError):
2422 _posixsubprocess.fork_exec(
2423 args, exe_list,
2424 True, [], cwd, env_list,
2425 -1, -1, -1, -1,
2426 1, 2, 3, 4,
2427 True, True, func)
2428 finally:
2429 if not gc_enabled:
2430 gc.disable()
2431
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002432 @support.cpython_only
2433 def test_fork_exec_sorted_fd_sanity_check(self):
2434 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
2435 import _posixsubprocess
2436 gc_enabled = gc.isenabled()
2437 try:
2438 gc.enable()
2439
2440 for fds_to_keep in (
2441 (-1, 2, 3, 4, 5), # Negative number.
2442 ('str', 4), # Not an int.
2443 (18, 23, 42, 2**63), # Out of range.
2444 (5, 4), # Not sorted.
2445 (6, 7, 7, 8), # Duplicate.
2446 ):
2447 with self.assertRaises(
2448 ValueError,
2449 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
2450 _posixsubprocess.fork_exec(
2451 [b"false"], [b"false"],
2452 True, fds_to_keep, None, [b"env"],
2453 -1, -1, -1, -1,
2454 1, 2, 3, 4,
2455 True, True, None)
2456 self.assertIn('fds_to_keep', str(c.exception))
2457 finally:
2458 if not gc_enabled:
2459 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02002460
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00002461 def test_communicate_BrokenPipeError_stdin_close(self):
2462 # By not setting stdout or stderr or a timeout we force the fast path
2463 # that just calls _stdin_write() internally due to our mock.
2464 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2465 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2466 mock_proc_stdin.close.side_effect = BrokenPipeError
2467 proc.communicate() # Should swallow BrokenPipeError from close.
2468 mock_proc_stdin.close.assert_called_with()
2469
2470 def test_communicate_BrokenPipeError_stdin_write(self):
2471 # By not setting stdout or stderr or a timeout we force the fast path
2472 # that just calls _stdin_write() internally due to our mock.
2473 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2474 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2475 mock_proc_stdin.write.side_effect = BrokenPipeError
2476 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
2477 mock_proc_stdin.write.assert_called_once_with(b'stuff')
2478 mock_proc_stdin.close.assert_called_once_with()
2479
2480 def test_communicate_BrokenPipeError_stdin_flush(self):
2481 # Setting stdin and stdout forces the ._communicate() code path.
2482 # python -h exits faster than python -c pass (but spams stdout).
2483 proc = subprocess.Popen([sys.executable, '-h'],
2484 stdin=subprocess.PIPE,
2485 stdout=subprocess.PIPE)
2486 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
2487 open(os.devnull, 'wb') as dev_null:
2488 mock_proc_stdin.flush.side_effect = BrokenPipeError
2489 # because _communicate registers a selector using proc.stdin...
2490 mock_proc_stdin.fileno.return_value = dev_null.fileno()
2491 # _communicate() should swallow BrokenPipeError from flush.
2492 proc.communicate(b'stuff')
2493 mock_proc_stdin.flush.assert_called_once_with()
2494
2495 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
2496 # Setting stdin and stdout forces the ._communicate() code path.
2497 # python -h exits faster than python -c pass (but spams stdout).
2498 proc = subprocess.Popen([sys.executable, '-h'],
2499 stdin=subprocess.PIPE,
2500 stdout=subprocess.PIPE)
2501 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2502 mock_proc_stdin.close.side_effect = BrokenPipeError
2503 # _communicate() should swallow BrokenPipeError from close.
2504 proc.communicate(timeout=999)
2505 mock_proc_stdin.close.assert_called_once_with()
2506
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002507 _libc_file_extensions = {
2508 'Linux': 'so.6',
Gregory P. Smith21d333b2017-01-22 20:54:42 -08002509 'Darwin': 'dylib',
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002510 }
Gregory P. Smith1fa08bc2017-01-22 22:19:38 -08002511 @unittest.skipIf(not ctypes, 'ctypes module required.')
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002512 @unittest.skipIf(platform.uname()[0] not in _libc_file_extensions,
2513 'Test requires a libc this code can load with ctypes.')
2514 @unittest.skipIf(not sys.executable, 'Test requires sys.executable.')
2515 def test_child_terminated_in_stopped_state(self):
2516 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
2517 PTRACE_TRACEME = 0 # From glibc and MacOS (PT_TRACE_ME).
2518 libc_name = 'libc.' + self._libc_file_extensions[platform.uname()[0]]
2519 libc = ctypes.CDLL(libc_name)
2520 if not hasattr(libc, 'ptrace'):
2521 raise unittest.SkipTest('ptrace() required.')
2522 test_ptrace = subprocess.Popen(
2523 [sys.executable, '-c', """if True:
2524 import ctypes
2525 libc = ctypes.CDLL({libc_name!r})
2526 libc.ptrace({PTRACE_TRACEME}, 0, 0)
2527 """.format(libc_name=libc_name, PTRACE_TRACEME=PTRACE_TRACEME)
2528 ])
2529 if test_ptrace.wait() != 0:
2530 raise unittest.SkipTest('ptrace() failed - unable to test.')
2531 child = subprocess.Popen(
2532 [sys.executable, '-c', """if True:
2533 import ctypes
2534 libc = ctypes.CDLL({libc_name!r})
2535 libc.ptrace({PTRACE_TRACEME}, 0, 0)
2536 libc.printf(ctypes.c_char_p(0xdeadbeef)) # Crash the process.
2537 """.format(libc_name=libc_name, PTRACE_TRACEME=PTRACE_TRACEME)
2538 ])
2539 try:
2540 returncode = child.wait()
2541 except Exception as e:
2542 child.kill() # Clean up the hung stopped process.
2543 raise e
2544 self.assertNotEqual(0, returncode)
2545 self.assertLess(returncode, 0) # signal death, likely SIGSEGV.
2546
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002547
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002548@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00002549class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002550
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002551 def test_startupinfo(self):
2552 # startupinfo argument
2553 # We uses hardcoded constants, because we do not want to
2554 # depend on win32all.
2555 STARTF_USESHOWWINDOW = 1
2556 SW_MAXIMIZE = 3
2557 startupinfo = subprocess.STARTUPINFO()
2558 startupinfo.dwFlags = STARTF_USESHOWWINDOW
2559 startupinfo.wShowWindow = SW_MAXIMIZE
2560 # Since Python is a console process, it won't be affected
2561 # by wShowWindow, but the argument should be silently
2562 # ignored
2563 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002564 startupinfo=startupinfo)
2565
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002566 def test_creationflags(self):
2567 # creationflags argument
2568 CREATE_NEW_CONSOLE = 16
2569 sys.stderr.write(" a DOS box should flash briefly ...\n")
2570 subprocess.call(sys.executable +
2571 ' -c "import time; time.sleep(0.25)"',
2572 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002573
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002574 def test_invalid_args(self):
2575 # invalid arguments should raise ValueError
2576 self.assertRaises(ValueError, subprocess.call,
2577 [sys.executable, "-c",
2578 "import sys; sys.exit(47)"],
2579 preexec_fn=lambda: 1)
2580 self.assertRaises(ValueError, subprocess.call,
2581 [sys.executable, "-c",
2582 "import sys; sys.exit(47)"],
2583 stdout=subprocess.PIPE,
2584 close_fds=True)
2585
2586 def test_close_fds(self):
2587 # close file descriptors
2588 rc = subprocess.call([sys.executable, "-c",
2589 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002590 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002591 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002592
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002593 def test_shell_sequence(self):
2594 # Run command through the shell (sequence)
2595 newenv = os.environ.copy()
2596 newenv["FRUIT"] = "physalis"
2597 p = subprocess.Popen(["set"], shell=1,
2598 stdout=subprocess.PIPE,
2599 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002600 with p:
2601 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00002602
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002603 def test_shell_string(self):
2604 # Run command through the shell (string)
2605 newenv = os.environ.copy()
2606 newenv["FRUIT"] = "physalis"
2607 p = subprocess.Popen("set", shell=1,
2608 stdout=subprocess.PIPE,
2609 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002610 with p:
2611 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002612
Steve Dower050acae2016-09-06 20:16:17 -07002613 def test_shell_encodings(self):
2614 # Run command through the shell (string)
2615 for enc in ['ansi', 'oem']:
2616 newenv = os.environ.copy()
2617 newenv["FRUIT"] = "physalis"
2618 p = subprocess.Popen("set", shell=1,
2619 stdout=subprocess.PIPE,
2620 env=newenv,
2621 encoding=enc)
2622 with p:
2623 self.assertIn("physalis", p.stdout.read(), enc)
2624
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002625 def test_call_string(self):
2626 # call() function with string argument on Windows
2627 rc = subprocess.call(sys.executable +
2628 ' -c "import sys; sys.exit(47)"')
2629 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002630
Florent Xicluna4886d242010-03-08 13:27:26 +00002631 def _kill_process(self, method, *args):
2632 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00002633 p = subprocess.Popen([sys.executable, "-c", """if 1:
2634 import sys, time
2635 sys.stdout.write('x\\n')
2636 sys.stdout.flush()
2637 time.sleep(30)
2638 """],
2639 stdin=subprocess.PIPE,
2640 stdout=subprocess.PIPE,
2641 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002642 with p:
2643 # Wait for the interpreter to be completely initialized before
2644 # sending any signal.
2645 p.stdout.read(1)
2646 getattr(p, method)(*args)
2647 _, stderr = p.communicate()
2648 self.assertStderrEqual(stderr, b'')
2649 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00002650 self.assertNotEqual(returncode, 0)
2651
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002652 def _kill_dead_process(self, method, *args):
2653 p = subprocess.Popen([sys.executable, "-c", """if 1:
2654 import sys, time
2655 sys.stdout.write('x\\n')
2656 sys.stdout.flush()
2657 sys.exit(42)
2658 """],
2659 stdin=subprocess.PIPE,
2660 stdout=subprocess.PIPE,
2661 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002662 with p:
2663 # Wait for the interpreter to be completely initialized before
2664 # sending any signal.
2665 p.stdout.read(1)
2666 # The process should end after this
2667 time.sleep(1)
2668 # This shouldn't raise even though the child is now dead
2669 getattr(p, method)(*args)
2670 _, stderr = p.communicate()
2671 self.assertStderrEqual(stderr, b'')
2672 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002673 self.assertEqual(rc, 42)
2674
Florent Xicluna4886d242010-03-08 13:27:26 +00002675 def test_send_signal(self):
2676 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00002677
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002678 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002679 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00002680
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002681 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002682 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00002683
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002684 def test_send_signal_dead(self):
2685 self._kill_dead_process('send_signal', signal.SIGTERM)
2686
2687 def test_kill_dead(self):
2688 self._kill_dead_process('kill')
2689
2690 def test_terminate_dead(self):
2691 self._kill_dead_process('terminate')
2692
Martin Panter23172bd2016-04-16 11:28:10 +00002693class MiscTests(unittest.TestCase):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002694 def test_getoutput(self):
2695 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
2696 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
2697 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00002698
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002699 # we use mkdtemp in the next line to create an empty directory
2700 # under our exclusive control; from that, we can invent a pathname
2701 # that we _know_ won't exist. This is guaranteed to fail.
2702 dir = None
2703 try:
2704 dir = tempfile.mkdtemp()
2705 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00002706 status, output = subprocess.getstatusoutput(
2707 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002708 self.assertNotEqual(status, 0)
2709 finally:
2710 if dir is not None:
2711 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00002712
Gregory P. Smithace55862015-04-07 15:57:54 -07002713 def test__all__(self):
2714 """Ensure that __all__ is populated properly."""
Martin Panter528619b2016-04-16 23:42:37 +00002715 intentionally_excluded = {"list2cmdline", "Handle"}
Gregory P. Smithace55862015-04-07 15:57:54 -07002716 exported = set(subprocess.__all__)
2717 possible_exports = set()
2718 import types
2719 for name, value in subprocess.__dict__.items():
2720 if name.startswith('_'):
2721 continue
2722 if isinstance(value, (types.ModuleType,)):
2723 continue
2724 possible_exports.add(name)
2725 self.assertEqual(exported, possible_exports - intentionally_excluded)
2726
2727
Martin Panter23172bd2016-04-16 11:28:10 +00002728@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
2729 "Test needs selectors.PollSelector")
2730class ProcessTestCaseNoPoll(ProcessTestCase):
2731 def setUp(self):
2732 self.orig_selector = subprocess._PopenSelector
2733 subprocess._PopenSelector = selectors.SelectSelector
2734 ProcessTestCase.setUp(self)
2735
2736 def tearDown(self):
2737 subprocess._PopenSelector = self.orig_selector
2738 ProcessTestCase.tearDown(self)
2739
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002740
Tim Golden126c2962010-08-11 14:20:40 +00002741@unittest.skipUnless(mswindows, "Windows-specific tests")
2742class CommandsWithSpaces (BaseTestCase):
2743
2744 def setUp(self):
2745 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03002746 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00002747 self.fname = fname.lower ()
2748 os.write(f, b"import sys;"
2749 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
2750 )
2751 os.close(f)
2752
2753 def tearDown(self):
2754 os.remove(self.fname)
2755 super().tearDown()
2756
2757 def with_spaces(self, *args, **kwargs):
2758 kwargs['stdout'] = subprocess.PIPE
2759 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02002760 with p:
2761 self.assertEqual(
2762 p.stdout.read ().decode("mbcs"),
2763 "2 [%r, 'ab cd']" % self.fname
2764 )
Tim Golden126c2962010-08-11 14:20:40 +00002765
2766 def test_shell_string_with_spaces(self):
2767 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002768 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2769 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002770
2771 def test_shell_sequence_with_spaces(self):
2772 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002773 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002774
2775 def test_noshell_string_with_spaces(self):
2776 # call() function with string argument with spaces on Windows
2777 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2778 "ab cd"))
2779
2780 def test_noshell_sequence_with_spaces(self):
2781 # call() function with sequence argument with spaces on Windows
2782 self.with_spaces([sys.executable, self.fname, "ab cd"])
2783
Brian Curtin79cdb662010-12-03 02:46:02 +00002784
Georg Brandla86b2622012-02-20 21:34:57 +01002785class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00002786
2787 def test_pipe(self):
2788 with subprocess.Popen([sys.executable, "-c",
2789 "import sys;"
2790 "sys.stdout.write('stdout');"
2791 "sys.stderr.write('stderr');"],
2792 stdout=subprocess.PIPE,
2793 stderr=subprocess.PIPE) as proc:
2794 self.assertEqual(proc.stdout.read(), b"stdout")
2795 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2796
2797 self.assertTrue(proc.stdout.closed)
2798 self.assertTrue(proc.stderr.closed)
2799
2800 def test_returncode(self):
2801 with subprocess.Popen([sys.executable, "-c",
2802 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002803 pass
2804 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002805 self.assertEqual(proc.returncode, 100)
2806
2807 def test_communicate_stdin(self):
2808 with subprocess.Popen([sys.executable, "-c",
2809 "import sys;"
2810 "sys.exit(sys.stdin.read() == 'context')"],
2811 stdin=subprocess.PIPE) as proc:
2812 proc.communicate(b"context")
2813 self.assertEqual(proc.returncode, 1)
2814
2815 def test_invalid_args(self):
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +01002816 with self.assertRaises((FileNotFoundError, PermissionError)) as c:
Brian Curtin79cdb662010-12-03 02:46:02 +00002817 with subprocess.Popen(['nonexisting_i_hope'],
2818 stdout=subprocess.PIPE,
2819 stderr=subprocess.PIPE) as proc:
2820 pass
2821
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002822 def test_broken_pipe_cleanup(self):
2823 """Broken pipe error should not prevent wait() (Issue 21619)"""
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002824 proc = subprocess.Popen([sys.executable, '-c', 'pass'],
Victor Stinner20f4bd42015-03-05 02:38:41 +01002825 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01002826 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002827 proc = proc.__enter__()
2828 # Prepare to send enough data to overflow any OS pipe buffering and
2829 # guarantee a broken pipe error. Data is held in BufferedWriter
2830 # buffer until closed.
2831 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002832 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002833 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02002834 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002835 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002836 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002837
Brian Curtin79cdb662010-12-03 02:46:02 +00002838
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002839if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002840 unittest.main()