blob: 092e2ce753e951ff7c76e9a145ec4963d0868f34 [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
6import signal
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04007import io
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00008import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00009import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000010import tempfile
11import time
Charles-François Natali3a4586a2013-11-08 19:56:59 +010012import selectors
Ezio Melotti184bdfb2010-02-18 09:37:05 +000013import sysconfig
Gregory P. Smith51ee2702010-12-13 07:59:39 +000014import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040015import shutil
Benjamin Petersonb870aa12011-12-10 12:44:25 -050016import gc
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030017import textwrap
Benjamin Peterson964561b2011-12-10 12:31:42 -050018
19try:
Antoine Pitroua8392712013-08-30 23:38:13 +020020 import threading
21except ImportError:
22 threading = None
Benjamin Peterson964561b2011-12-10 12:31:42 -050023
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000024mswindows = (sys.platform == "win32")
25
26#
27# Depends on the following external programs: Python
28#
29
30if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000031 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
32 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000033else:
34 SETBINARY = ''
35
Florent Xiclunab1e94e82010-02-27 22:12:37 +000036
Florent Xiclunac049d872010-03-27 22:47:23 +000037class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000038 def setUp(self):
39 # Try to minimize the number of children we have so this test
40 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000041 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000042
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000043 def tearDown(self):
44 for inst in subprocess._active:
45 inst.wait()
46 subprocess._cleanup()
47 self.assertFalse(subprocess._active, "subprocess._active not empty")
48
Florent Xiclunab1e94e82010-02-27 22:12:37 +000049 def assertStderrEqual(self, stderr, expected, msg=None):
50 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
51 # shutdown time. That frustrates tests trying to check stderr produced
52 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000053 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040054 # strip_python_stderr also strips whitespace, so we do too.
55 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000056 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000057
Florent Xiclunac049d872010-03-27 22:47:23 +000058
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080059class PopenTestException(Exception):
60 pass
61
62
63class PopenExecuteChildRaises(subprocess.Popen):
64 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
65 _execute_child fails.
66 """
67 def _execute_child(self, *args, **kwargs):
68 raise PopenTestException("Forced Exception for Test")
69
70
Florent Xiclunac049d872010-03-27 22:47:23 +000071class ProcessTestCase(BaseTestCase):
72
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070073 def test_io_buffered_by_default(self):
74 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
75 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
76 stderr=subprocess.PIPE)
77 try:
78 self.assertIsInstance(p.stdin, io.BufferedIOBase)
79 self.assertIsInstance(p.stdout, io.BufferedIOBase)
80 self.assertIsInstance(p.stderr, io.BufferedIOBase)
81 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -070082 p.stdin.close()
83 p.stdout.close()
84 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070085 p.wait()
86
87 def test_io_unbuffered_works(self):
88 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
89 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
90 stderr=subprocess.PIPE, bufsize=0)
91 try:
92 self.assertIsInstance(p.stdin, io.RawIOBase)
93 self.assertIsInstance(p.stdout, io.RawIOBase)
94 self.assertIsInstance(p.stderr, io.RawIOBase)
95 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -070096 p.stdin.close()
97 p.stdout.close()
98 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070099 p.wait()
100
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000101 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000102 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000103 rc = subprocess.call([sys.executable, "-c",
104 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000105 self.assertEqual(rc, 47)
106
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400107 def test_call_timeout(self):
108 # call() function with timeout argument; we want to test that the child
109 # process gets killed when the timeout expires. If the child isn't
110 # killed, this call will deadlock since subprocess.call waits for the
111 # child.
112 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
113 [sys.executable, "-c", "while True: pass"],
114 timeout=0.1)
115
Peter Astrand454f7672005-01-01 09:36:35 +0000116 def test_check_call_zero(self):
117 # check_call() function with zero return code
118 rc = subprocess.check_call([sys.executable, "-c",
119 "import sys; sys.exit(0)"])
120 self.assertEqual(rc, 0)
121
122 def test_check_call_nonzero(self):
123 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000124 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000125 subprocess.check_call([sys.executable, "-c",
126 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000127 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000128
Georg Brandlf9734072008-12-07 15:30:06 +0000129 def test_check_output(self):
130 # check_output() function with zero return code
131 output = subprocess.check_output(
132 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000133 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000134
135 def test_check_output_nonzero(self):
136 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000137 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000138 subprocess.check_output(
139 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000140 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000141
142 def test_check_output_stderr(self):
143 # check_output() function stderr redirected to stdout
144 output = subprocess.check_output(
145 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
146 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000147 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000148
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300149 def test_check_output_stdin_arg(self):
150 # check_output() can be called with stdin set to a file
151 tf = tempfile.TemporaryFile()
152 self.addCleanup(tf.close)
153 tf.write(b'pear')
154 tf.seek(0)
155 output = subprocess.check_output(
156 [sys.executable, "-c",
157 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
158 stdin=tf)
159 self.assertIn(b'PEAR', output)
160
161 def test_check_output_input_arg(self):
162 # check_output() can be called with input set to a string
163 output = subprocess.check_output(
164 [sys.executable, "-c",
165 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
166 input=b'pear')
167 self.assertIn(b'PEAR', output)
168
Georg Brandlf9734072008-12-07 15:30:06 +0000169 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300170 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000171 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000172 output = subprocess.check_output(
173 [sys.executable, "-c", "print('will not be run')"],
174 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000175 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000176 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000177
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300178 def test_check_output_stdin_with_input_arg(self):
179 # check_output() refuses to accept 'stdin' with 'input'
180 tf = tempfile.TemporaryFile()
181 self.addCleanup(tf.close)
182 tf.write(b'pear')
183 tf.seek(0)
184 with self.assertRaises(ValueError) as c:
185 output = subprocess.check_output(
186 [sys.executable, "-c", "print('will not be run')"],
187 stdin=tf, input=b'hare')
188 self.fail("Expected ValueError when stdin and input args supplied.")
189 self.assertIn('stdin', c.exception.args[0])
190 self.assertIn('input', c.exception.args[0])
191
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400192 def test_check_output_timeout(self):
193 # check_output() function with timeout arg
194 with self.assertRaises(subprocess.TimeoutExpired) as c:
195 output = subprocess.check_output(
196 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200197 "import sys, time\n"
198 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400199 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200200 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400201 # Some heavily loaded buildbots (sparc Debian 3.x) require
202 # this much time to start and print.
203 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400204 self.fail("Expected TimeoutExpired.")
205 self.assertEqual(c.exception.output, b'BDFL')
206
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000207 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000208 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000209 newenv = os.environ.copy()
210 newenv["FRUIT"] = "banana"
211 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000212 'import sys, os;'
213 'sys.exit(os.getenv("FRUIT")=="banana")'],
214 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000215 self.assertEqual(rc, 1)
216
Victor Stinner87b9bc32011-06-01 00:57:47 +0200217 def test_invalid_args(self):
218 # Popen() called with invalid arguments should raise TypeError
219 # but Popen.__del__ should not complain (issue #12085)
220 with support.captured_stderr() as s:
221 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
222 argcount = subprocess.Popen.__init__.__code__.co_argcount
223 too_many_args = [0] * (argcount + 1)
224 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
225 self.assertEqual(s.getvalue(), '')
226
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000227 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000228 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000229 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000230 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000231 self.addCleanup(p.stdout.close)
232 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000233 p.wait()
234 self.assertEqual(p.stdin, None)
235
236 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200237 # .stdout is None when not redirected, and the child's stdout will
238 # be inherited from the parent. In order to test this we run a
239 # subprocess in a subprocess:
240 # this_test
241 # \-- subprocess created by this test (parent)
242 # \-- subprocess created by the parent subprocess (child)
243 # The parent doesn't specify stdout, so the child will use the
244 # parent's stdout. This test checks that the message printed by the
245 # child goes to the parent stdout. The parent also checks that the
246 # child's stdout is None. See #11963.
247 code = ('import sys; from subprocess import Popen, PIPE;'
248 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
249 ' stdin=PIPE, stderr=PIPE);'
250 'p.wait(); assert p.stdout is None;')
251 p = subprocess.Popen([sys.executable, "-c", code],
252 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
253 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000254 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200255 out, err = p.communicate()
256 self.assertEqual(p.returncode, 0, err)
257 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000258
259 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000260 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000261 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000262 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000263 self.addCleanup(p.stdout.close)
264 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000265 p.wait()
266 self.assertEqual(p.stderr, None)
267
Chris Jerdonek776cb192012-10-08 15:56:43 -0700268 def _assert_python(self, pre_args, **kwargs):
269 # We include sys.exit() to prevent the test runner from hanging
270 # whenever python is found.
271 args = pre_args + ["import sys; sys.exit(47)"]
272 p = subprocess.Popen(args, **kwargs)
273 p.wait()
274 self.assertEqual(47, p.returncode)
275
276 def test_executable(self):
277 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700278 #
279 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
280 # determine where its standard library is, so we need the directory
281 # of args[0] to be valid for the Popen() call to Python to succeed.
282 # See also issue #16170 and issue #7774.
283 doesnotexist = os.path.join(os.path.dirname(sys.executable),
284 "doesnotexist")
285 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700286
287 def test_executable_takes_precedence(self):
288 # Check that the executable argument takes precedence over args[0].
289 #
290 # Verify first that the call succeeds without the executable arg.
291 pre_args = [sys.executable, "-c"]
292 self._assert_python(pre_args)
293 self.assertRaises(FileNotFoundError, self._assert_python, pre_args,
294 executable="doesnotexist")
295
296 @unittest.skipIf(mswindows, "executable argument replaces shell")
297 def test_executable_replaces_shell(self):
298 # Check that the executable argument replaces the default shell
299 # when shell=True.
300 self._assert_python([], executable=sys.executable, shell=True)
301
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700302 # For use in the test_cwd* tests below.
303 def _normalize_cwd(self, cwd):
304 # Normalize an expected cwd (for Tru64 support).
305 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
306 # strings. See bug #1063571.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300307 with support.change_cwd(cwd):
308 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700309
310 # For use in the test_cwd* tests below.
311 def _split_python_path(self):
312 # Return normalized (python_dir, python_base).
313 python_path = os.path.realpath(sys.executable)
314 return os.path.split(python_path)
315
316 # For use in the test_cwd* tests below.
317 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
318 # Invoke Python via Popen, and assert that (1) the call succeeds,
319 # and that (2) the current working directory of the child process
320 # matches *expected_cwd*.
321 p = subprocess.Popen([python_arg, "-c",
322 "import os, sys; "
323 "sys.stdout.write(os.getcwd()); "
324 "sys.exit(47)"],
325 stdout=subprocess.PIPE,
326 **kwargs)
327 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000328 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700329 self.assertEqual(47, p.returncode)
330 normcase = os.path.normcase
331 self.assertEqual(normcase(expected_cwd),
332 normcase(p.stdout.read().decode("utf-8")))
333
334 def test_cwd(self):
335 # Check that cwd changes the cwd for the child process.
336 temp_dir = tempfile.gettempdir()
337 temp_dir = self._normalize_cwd(temp_dir)
338 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
339
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700340 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700341 def test_cwd_with_relative_arg(self):
342 # Check that Popen looks for args[0] relative to cwd if args[0]
343 # is relative.
344 python_dir, python_base = self._split_python_path()
345 rel_python = os.path.join(os.curdir, python_base)
346 with support.temp_cwd() as wrong_dir:
347 # Before calling with the correct cwd, confirm that the call fails
348 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700349 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700350 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700351 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700352 [rel_python], cwd=wrong_dir)
353 python_dir = self._normalize_cwd(python_dir)
354 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
355
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700356 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700357 def test_cwd_with_relative_executable(self):
358 # Check that Popen looks for executable relative to cwd if executable
359 # is relative (and that executable takes precedence over args[0]).
360 python_dir, python_base = self._split_python_path()
361 rel_python = os.path.join(os.curdir, python_base)
362 doesntexist = "somethingyoudonthave"
363 with support.temp_cwd() as wrong_dir:
364 # Before calling with the correct cwd, confirm that the call fails
365 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700366 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700367 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700368 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700369 [doesntexist], executable=rel_python,
370 cwd=wrong_dir)
371 python_dir = self._normalize_cwd(python_dir)
372 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
373 cwd=python_dir)
374
375 def test_cwd_with_absolute_arg(self):
376 # Check that Popen can find the executable when the cwd is wrong
377 # if args[0] is an absolute path.
378 python_dir, python_base = self._split_python_path()
379 abs_python = os.path.join(python_dir, python_base)
380 rel_python = os.path.join(os.curdir, python_base)
Berker Peksagce643912015-05-06 06:33:17 +0300381 with support.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700382 # Before calling with an absolute path, confirm that using a
383 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700384 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700385 [rel_python], cwd=wrong_dir)
386 wrong_dir = self._normalize_cwd(wrong_dir)
387 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
388
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100389 @unittest.skipIf(sys.base_prefix != sys.prefix,
390 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000391 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700392 python_dir, python_base = self._split_python_path()
393 python_dir = self._normalize_cwd(python_dir)
394 self._assert_cwd(python_dir, "somethingyoudonthave",
395 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000396
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100397 @unittest.skipIf(sys.base_prefix != sys.prefix,
398 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000399 @unittest.skipIf(sysconfig.is_python_build(),
400 "need an installed Python. See #7774")
401 def test_executable_without_cwd(self):
402 # For a normal installation, it should work without 'cwd'
403 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700404 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
405 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000406
407 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000408 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000409 p = subprocess.Popen([sys.executable, "-c",
410 'import sys; sys.exit(sys.stdin.read() == "pear")'],
411 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000412 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000413 p.stdin.close()
414 p.wait()
415 self.assertEqual(p.returncode, 1)
416
417 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000418 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000419 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000420 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000421 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000422 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000423 os.lseek(d, 0, 0)
424 p = subprocess.Popen([sys.executable, "-c",
425 'import sys; sys.exit(sys.stdin.read() == "pear")'],
426 stdin=d)
427 p.wait()
428 self.assertEqual(p.returncode, 1)
429
430 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000431 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000432 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000433 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000434 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000435 tf.seek(0)
436 p = subprocess.Popen([sys.executable, "-c",
437 'import sys; sys.exit(sys.stdin.read() == "pear")'],
438 stdin=tf)
439 p.wait()
440 self.assertEqual(p.returncode, 1)
441
442 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000443 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000444 p = subprocess.Popen([sys.executable, "-c",
445 'import sys; sys.stdout.write("orange")'],
446 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200447 with p:
448 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000449
450 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000451 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000452 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000453 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000454 d = tf.fileno()
455 p = subprocess.Popen([sys.executable, "-c",
456 'import sys; sys.stdout.write("orange")'],
457 stdout=d)
458 p.wait()
459 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000460 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000461
462 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000463 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000464 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000465 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000466 p = subprocess.Popen([sys.executable, "-c",
467 'import sys; sys.stdout.write("orange")'],
468 stdout=tf)
469 p.wait()
470 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000471 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000472
473 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000474 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000475 p = subprocess.Popen([sys.executable, "-c",
476 'import sys; sys.stderr.write("strawberry")'],
477 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200478 with p:
479 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000480
481 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000482 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000483 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000484 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000485 d = tf.fileno()
486 p = subprocess.Popen([sys.executable, "-c",
487 'import sys; sys.stderr.write("strawberry")'],
488 stderr=d)
489 p.wait()
490 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000491 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000492
493 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000494 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000495 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000496 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000497 p = subprocess.Popen([sys.executable, "-c",
498 'import sys; sys.stderr.write("strawberry")'],
499 stderr=tf)
500 p.wait()
501 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000502 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000503
Martin Panterc7635892016-05-13 01:54:44 +0000504 def test_stderr_redirect_with_no_stdout_redirect(self):
505 # test stderr=STDOUT while stdout=None (not set)
506
507 # - grandchild prints to stderr
508 # - child redirects grandchild's stderr to its stdout
509 # - the parent should get grandchild's stderr in child's stdout
510 p = subprocess.Popen([sys.executable, "-c",
511 'import sys, subprocess;'
512 'rc = subprocess.call([sys.executable, "-c",'
513 ' "import sys;"'
514 ' "sys.stderr.write(\'42\')"],'
515 ' stderr=subprocess.STDOUT);'
516 'sys.exit(rc)'],
517 stdout=subprocess.PIPE,
518 stderr=subprocess.PIPE)
519 stdout, stderr = p.communicate()
520 #NOTE: stdout should get stderr from grandchild
521 self.assertStderrEqual(stdout, b'42')
522 self.assertStderrEqual(stderr, b'') # should be empty
523 self.assertEqual(p.returncode, 0)
524
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000525 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000526 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000527 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000528 'import sys;'
529 'sys.stdout.write("apple");'
530 'sys.stdout.flush();'
531 'sys.stderr.write("orange")'],
532 stdout=subprocess.PIPE,
533 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200534 with p:
535 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000536
537 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000538 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000539 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000540 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000541 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000542 'import sys;'
543 'sys.stdout.write("apple");'
544 'sys.stdout.flush();'
545 'sys.stderr.write("orange")'],
546 stdout=tf,
547 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000548 p.wait()
549 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000550 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000551
Thomas Wouters89f507f2006-12-13 04:49:30 +0000552 def test_stdout_filedes_of_stdout(self):
553 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200554 # To avoid printing the text on stdout, we do something similar to
555 # test_stdout_none (see above). The parent subprocess calls the child
556 # subprocess passing stdout=1, and this test uses stdout=PIPE in
557 # order to capture and check the output of the parent. See #11963.
558 code = ('import sys, subprocess; '
559 'rc = subprocess.call([sys.executable, "-c", '
560 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
561 'b\'test with stdout=1\'))"], stdout=1); '
562 'assert rc == 18')
563 p = subprocess.Popen([sys.executable, "-c", code],
564 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
565 self.addCleanup(p.stdout.close)
566 self.addCleanup(p.stderr.close)
567 out, err = p.communicate()
568 self.assertEqual(p.returncode, 0, err)
569 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000570
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200571 def test_stdout_devnull(self):
572 p = subprocess.Popen([sys.executable, "-c",
573 'for i in range(10240):'
574 'print("x" * 1024)'],
575 stdout=subprocess.DEVNULL)
576 p.wait()
577 self.assertEqual(p.stdout, None)
578
579 def test_stderr_devnull(self):
580 p = subprocess.Popen([sys.executable, "-c",
581 'import sys\n'
582 'for i in range(10240):'
583 'sys.stderr.write("x" * 1024)'],
584 stderr=subprocess.DEVNULL)
585 p.wait()
586 self.assertEqual(p.stderr, None)
587
588 def test_stdin_devnull(self):
589 p = subprocess.Popen([sys.executable, "-c",
590 'import sys;'
591 'sys.stdin.read(1)'],
592 stdin=subprocess.DEVNULL)
593 p.wait()
594 self.assertEqual(p.stdin, None)
595
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000596 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000597 newenv = os.environ.copy()
598 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200599 with subprocess.Popen([sys.executable, "-c",
600 'import sys,os;'
601 'sys.stdout.write(os.getenv("FRUIT"))'],
602 stdout=subprocess.PIPE,
603 env=newenv) as p:
604 stdout, stderr = p.communicate()
605 self.assertEqual(stdout, b"orange")
606
Victor Stinner62d51182011-06-23 01:02:25 +0200607 # Windows requires at least the SYSTEMROOT environment variable to start
608 # Python
609 @unittest.skipIf(sys.platform == 'win32',
610 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200611 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200612 'the python library cannot be loaded '
613 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200614 def test_empty_env(self):
615 with subprocess.Popen([sys.executable, "-c",
616 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200617 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200618 stdout=subprocess.PIPE,
619 env={}) as p:
620 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200621 self.assertIn(stdout.strip(),
622 (b"[]",
623 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
624 # environment
625 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000626
Peter Astrandcbac93c2005-03-03 20:24:28 +0000627 def test_communicate_stdin(self):
628 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000629 'import sys;'
630 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000631 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000632 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000633 self.assertEqual(p.returncode, 1)
634
635 def test_communicate_stdout(self):
636 p = subprocess.Popen([sys.executable, "-c",
637 'import sys; sys.stdout.write("pineapple")'],
638 stdout=subprocess.PIPE)
639 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000640 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000641 self.assertEqual(stderr, None)
642
643 def test_communicate_stderr(self):
644 p = subprocess.Popen([sys.executable, "-c",
645 'import sys; sys.stderr.write("pineapple")'],
646 stderr=subprocess.PIPE)
647 (stdout, stderr) = p.communicate()
648 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000649 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000650
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000651 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000652 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000653 'import sys,os;'
654 'sys.stderr.write("pineapple");'
655 'sys.stdout.write(sys.stdin.read())'],
656 stdin=subprocess.PIPE,
657 stdout=subprocess.PIPE,
658 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000659 self.addCleanup(p.stdout.close)
660 self.addCleanup(p.stderr.close)
661 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000662 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000663 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000664 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000665
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400666 def test_communicate_timeout(self):
667 p = subprocess.Popen([sys.executable, "-c",
668 'import sys,os,time;'
669 'sys.stderr.write("pineapple\\n");'
670 'time.sleep(1);'
671 'sys.stderr.write("pear\\n");'
672 'sys.stdout.write(sys.stdin.read())'],
673 universal_newlines=True,
674 stdin=subprocess.PIPE,
675 stdout=subprocess.PIPE,
676 stderr=subprocess.PIPE)
677 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
678 timeout=0.3)
679 # Make sure we can keep waiting for it, and that we get the whole output
680 # after it completes.
681 (stdout, stderr) = p.communicate()
682 self.assertEqual(stdout, "banana")
683 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
684
685 def test_communicate_timeout_large_ouput(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200686 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400687 p = subprocess.Popen([sys.executable, "-c",
688 'import sys,os,time;'
689 'sys.stdout.write("a" * (64 * 1024));'
690 'time.sleep(0.2);'
691 'sys.stdout.write("a" * (64 * 1024));'
692 'time.sleep(0.2);'
693 'sys.stdout.write("a" * (64 * 1024));'
694 'time.sleep(0.2);'
695 'sys.stdout.write("a" * (64 * 1024));'],
696 stdout=subprocess.PIPE)
697 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
698 (stdout, _) = p.communicate()
699 self.assertEqual(len(stdout), 4 * 64 * 1024)
700
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000701 # Test for the fd leak reported in http://bugs.python.org/issue2791.
702 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000703 for stdin_pipe in (False, True):
704 for stdout_pipe in (False, True):
705 for stderr_pipe in (False, True):
706 options = {}
707 if stdin_pipe:
708 options['stdin'] = subprocess.PIPE
709 if stdout_pipe:
710 options['stdout'] = subprocess.PIPE
711 if stderr_pipe:
712 options['stderr'] = subprocess.PIPE
713 if not options:
714 continue
715 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
716 p.communicate()
717 if p.stdin is not None:
718 self.assertTrue(p.stdin.closed)
719 if p.stdout is not None:
720 self.assertTrue(p.stdout.closed)
721 if p.stderr is not None:
722 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000723
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000724 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000725 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000726 p = subprocess.Popen([sys.executable, "-c",
727 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000728 (stdout, stderr) = p.communicate()
729 self.assertEqual(stdout, None)
730 self.assertEqual(stderr, None)
731
732 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000733 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000734 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000735 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000736 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000737 os.close(x)
738 os.close(y)
739 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000740 'import sys,os;'
741 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200742 'sys.stderr.write("x" * %d);'
743 'sys.stdout.write(sys.stdin.read())' %
744 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000745 stdin=subprocess.PIPE,
746 stdout=subprocess.PIPE,
747 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000748 self.addCleanup(p.stdout.close)
749 self.addCleanup(p.stderr.close)
750 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200751 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000752 (stdout, stderr) = p.communicate(string_to_write)
753 self.assertEqual(stdout, string_to_write)
754
755 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000756 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000757 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000758 'import sys,os;'
759 'sys.stdout.write(sys.stdin.read())'],
760 stdin=subprocess.PIPE,
761 stdout=subprocess.PIPE,
762 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000763 self.addCleanup(p.stdout.close)
764 self.addCleanup(p.stderr.close)
765 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000766 p.stdin.write(b"banana")
767 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000768 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000769 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000770
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000771 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000772 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000773 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200774 'buf = sys.stdout.buffer;'
775 'buf.write(sys.stdin.readline().encode());'
776 'buf.flush();'
777 'buf.write(b"line2\\n");'
778 'buf.flush();'
779 'buf.write(sys.stdin.read().encode());'
780 'buf.flush();'
781 'buf.write(b"line4\\n");'
782 'buf.flush();'
783 'buf.write(b"line5\\r\\n");'
784 'buf.flush();'
785 'buf.write(b"line6\\r");'
786 'buf.flush();'
787 'buf.write(b"\\nline7");'
788 'buf.flush();'
789 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200790 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000791 stdout=subprocess.PIPE,
792 universal_newlines=1)
Victor Stinner7438c612016-05-20 12:43:15 +0200793 with p:
794 p.stdin.write("line1\n")
795 p.stdin.flush()
796 self.assertEqual(p.stdout.readline(), "line1\n")
797 p.stdin.write("line3\n")
798 p.stdin.close()
799 self.addCleanup(p.stdout.close)
800 self.assertEqual(p.stdout.readline(),
801 "line2\n")
802 self.assertEqual(p.stdout.read(6),
803 "line3\n")
804 self.assertEqual(p.stdout.read(),
805 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000806
807 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000808 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000809 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000810 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200811 'buf = sys.stdout.buffer;'
812 'buf.write(b"line2\\n");'
813 'buf.flush();'
814 'buf.write(b"line4\\n");'
815 'buf.flush();'
816 'buf.write(b"line5\\r\\n");'
817 'buf.flush();'
818 'buf.write(b"line6\\r");'
819 'buf.flush();'
820 'buf.write(b"\\nline7");'
821 'buf.flush();'
822 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200823 stderr=subprocess.PIPE,
824 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000825 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000826 self.addCleanup(p.stdout.close)
827 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000828 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200829 self.assertEqual(stdout,
830 "line2\nline4\nline5\nline6\nline7\nline8")
831
832 def test_universal_newlines_communicate_stdin(self):
833 # universal newlines through communicate(), with only stdin
834 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300835 'import sys,os;' + SETBINARY + textwrap.dedent('''
836 s = sys.stdin.readline()
837 assert s == "line1\\n", repr(s)
838 s = sys.stdin.read()
839 assert s == "line3\\n", repr(s)
840 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200841 stdin=subprocess.PIPE,
842 universal_newlines=1)
843 (stdout, stderr) = p.communicate("line1\nline3\n")
844 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000845
Andrew Svetlovf3765072012-08-14 18:35:17 +0300846 def test_universal_newlines_communicate_input_none(self):
847 # Test communicate(input=None) with universal newlines.
848 #
849 # We set stdout to PIPE because, as of this writing, a different
850 # code path is tested when the number of pipes is zero or one.
851 p = subprocess.Popen([sys.executable, "-c", "pass"],
852 stdin=subprocess.PIPE,
853 stdout=subprocess.PIPE,
854 universal_newlines=True)
855 p.communicate()
856 self.assertEqual(p.returncode, 0)
857
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300858 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300859 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300860 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300861 'import sys,os;' + SETBINARY + textwrap.dedent('''
862 s = sys.stdin.buffer.readline()
863 sys.stdout.buffer.write(s)
864 sys.stdout.buffer.write(b"line2\\r")
865 sys.stderr.buffer.write(b"eline2\\n")
866 s = sys.stdin.buffer.read()
867 sys.stdout.buffer.write(s)
868 sys.stdout.buffer.write(b"line4\\n")
869 sys.stdout.buffer.write(b"line5\\r\\n")
870 sys.stderr.buffer.write(b"eline6\\r")
871 sys.stderr.buffer.write(b"eline7\\r\\nz")
872 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300873 stdin=subprocess.PIPE,
874 stderr=subprocess.PIPE,
875 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300876 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300877 self.addCleanup(p.stdout.close)
878 self.addCleanup(p.stderr.close)
879 (stdout, stderr) = p.communicate("line1\nline3\n")
880 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300881 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300882 # Python debug build push something like "[42442 refs]\n"
883 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300884 # Don't use assertStderrEqual because it strips CR and LF from output.
885 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300886
Andrew Svetlov82860712012-08-19 22:13:41 +0300887 def test_universal_newlines_communicate_encodings(self):
888 # Check that universal newlines mode works for various encodings,
889 # in particular for encodings in the UTF-16 and UTF-32 families.
890 # See issue #15595.
891 #
892 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
893 # without, and UTF-16 and UTF-32.
Antoine Pitroufd4722c2013-10-12 00:13:50 +0200894 import _bootlocale
Andrew Svetlov82860712012-08-19 22:13:41 +0300895 for encoding in ['utf-16', 'utf-32-be']:
Antoine Pitroufd4722c2013-10-12 00:13:50 +0200896 old_getpreferredencoding = _bootlocale.getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300897 # Indirectly via io.TextIOWrapper, Popen() defaults to
898 # locale.getpreferredencoding(False) and earlier in Python 3.2 to
899 # locale.getpreferredencoding().
900 def getpreferredencoding(do_setlocale=True):
901 return encoding
902 code = ("import sys; "
903 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
904 encoding)
905 args = [sys.executable, '-c', code]
906 try:
Antoine Pitroufd4722c2013-10-12 00:13:50 +0200907 _bootlocale.getpreferredencoding = getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300908 # We set stdin to be non-None because, as of this writing,
909 # a different code path is used when the number of pipes is
910 # zero or one.
911 popen = subprocess.Popen(args, universal_newlines=True,
912 stdin=subprocess.PIPE,
913 stdout=subprocess.PIPE)
914 stdout, stderr = popen.communicate(input='')
915 finally:
Antoine Pitroufd4722c2013-10-12 00:13:50 +0200916 _bootlocale.getpreferredencoding = old_getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300917 self.assertEqual(stdout, '1\n2\n3\n4')
918
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000919 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000920 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000921 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000922 max_handles = 1026 # too much for most UNIX systems
923 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000924 max_handles = 2050 # too much for (at least some) Windows setups
925 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400926 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000927 try:
928 for i in range(max_handles):
929 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400930 tmpfile = os.path.join(tmpdir, support.TESTFN)
931 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000932 except OSError as e:
933 if e.errno != errno.EMFILE:
934 raise
935 break
936 else:
937 self.skipTest("failed to reach the file descriptor limit "
938 "(tried %d)" % max_handles)
939 # Close a couple of them (should be enough for a subprocess)
940 for i in range(10):
941 os.close(handles.pop())
942 # Loop creating some subprocesses. If one of them leaks some fds,
943 # the next loop iteration will fail by reaching the max fd limit.
944 for i in range(15):
945 p = subprocess.Popen([sys.executable, "-c",
946 "import sys;"
947 "sys.stdout.write(sys.stdin.read())"],
948 stdin=subprocess.PIPE,
949 stdout=subprocess.PIPE,
950 stderr=subprocess.PIPE)
951 data = p.communicate(b"lime")[0]
952 self.assertEqual(data, b"lime")
953 finally:
954 for h in handles:
955 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400956 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000957
958 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000959 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
960 '"a b c" d e')
961 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
962 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000963 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
964 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000965 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
966 'a\\\\\\b "de fg" h')
967 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
968 'a\\\\\\"b c d')
969 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
970 '"a\\\\b c" d e')
971 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
972 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000973 self.assertEqual(subprocess.list2cmdline(['ab', '']),
974 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000975
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000976 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200977 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +0200978 "import os; os.read(0, 1)"],
979 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200980 self.addCleanup(p.stdin.close)
981 self.assertIsNone(p.poll())
982 os.write(p.stdin.fileno(), b'A')
983 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000984 # Subsequent invocations should just return the returncode
985 self.assertEqual(p.poll(), 0)
986
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000987 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200988 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000989 self.assertEqual(p.wait(), 0)
990 # Subsequent invocations should just return the returncode
991 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000992
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400993 def test_wait_timeout(self):
994 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +0200995 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -0400996 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +0200997 p.wait(timeout=0.0001)
998 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -0400999 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
1000 # time to start.
1001 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001002
Peter Astrand738131d2004-11-30 21:04:45 +00001003 def test_invalid_bufsize(self):
1004 # an invalid type of the bufsize argument should raise
1005 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001006 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +00001007 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001008
Guido van Rossum46a05a72007-06-07 21:56:45 +00001009 def test_bufsize_is_none(self):
1010 # bufsize=None should be the same as bufsize=0.
1011 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
1012 self.assertEqual(p.wait(), 0)
1013 # Again with keyword arg
1014 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
1015 self.assertEqual(p.wait(), 0)
1016
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001017 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1018 # subprocess may deadlock with bufsize=1, see issue #21332
1019 with subprocess.Popen([sys.executable, "-c", "import sys;"
1020 "sys.stdout.write(sys.stdin.readline());"
1021 "sys.stdout.flush()"],
1022 stdin=subprocess.PIPE,
1023 stdout=subprocess.PIPE,
1024 stderr=subprocess.DEVNULL,
1025 bufsize=1,
1026 universal_newlines=universal_newlines) as p:
1027 p.stdin.write(line) # expect that it flushes the line in text mode
1028 os.close(p.stdin.fileno()) # close it without flushing the buffer
1029 read_line = p.stdout.readline()
1030 try:
1031 p.stdin.close()
1032 except OSError:
1033 pass
1034 p.stdin = None
1035 self.assertEqual(p.returncode, 0)
1036 self.assertEqual(read_line, expected)
1037
1038 def test_bufsize_equal_one_text_mode(self):
1039 # line is flushed in text mode with bufsize=1.
1040 # we should get the full line in return
1041 line = "line\n"
1042 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1043
1044 def test_bufsize_equal_one_binary_mode(self):
1045 # line is not flushed in binary mode with bufsize=1.
1046 # we should get empty response
1047 line = b'line' + os.linesep.encode() # assume ascii-based locale
1048 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
1049
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001050 def test_leaking_fds_on_error(self):
1051 # see bug #5179: Popen leaks file descriptors to PIPEs if
1052 # the child fails to execute; this will eventually exhaust
1053 # the maximum number of open fds. 1024 seems a very common
1054 # value for that limit, but Windows has 2048, so we loop
1055 # 1024 times (each call leaked two fds).
1056 for i in range(1024):
Andrew Svetlov3438fa42012-12-17 23:35:18 +02001057 with self.assertRaises(OSError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001058 subprocess.Popen(['nonexisting_i_hope'],
1059 stdout=subprocess.PIPE,
1060 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -04001061 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -04001062 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001063 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001064
Antoine Pitroua8392712013-08-30 23:38:13 +02001065 @unittest.skipIf(threading is None, "threading required")
1066 def test_double_close_on_error(self):
1067 # Issue #18851
1068 fds = []
1069 def open_fds():
1070 for i in range(20):
1071 fds.extend(os.pipe())
1072 time.sleep(0.001)
1073 t = threading.Thread(target=open_fds)
1074 t.start()
1075 try:
1076 with self.assertRaises(EnvironmentError):
1077 subprocess.Popen(['nonexisting_i_hope'],
1078 stdin=subprocess.PIPE,
1079 stdout=subprocess.PIPE,
1080 stderr=subprocess.PIPE)
1081 finally:
1082 t.join()
1083 exc = None
1084 for fd in fds:
1085 # If a double close occurred, some of those fds will
1086 # already have been closed by mistake, and os.close()
1087 # here will raise.
1088 try:
1089 os.close(fd)
1090 except OSError as e:
1091 exc = e
1092 if exc is not None:
1093 raise exc
1094
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001095 @unittest.skipIf(threading is None, "threading required")
1096 def test_threadsafe_wait(self):
1097 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1098 proc = subprocess.Popen([sys.executable, '-c',
1099 'import time; time.sleep(12)'])
1100 self.assertEqual(proc.returncode, None)
1101 results = []
1102
1103 def kill_proc_timer_thread():
1104 results.append(('thread-start-poll-result', proc.poll()))
1105 # terminate it from the thread and wait for the result.
1106 proc.kill()
1107 proc.wait()
1108 results.append(('thread-after-kill-and-wait', proc.returncode))
1109 # this wait should be a no-op given the above.
1110 proc.wait()
1111 results.append(('thread-after-second-wait', proc.returncode))
1112
1113 # This is a timing sensitive test, the failure mode is
1114 # triggered when both the main thread and this thread are in
1115 # the wait() call at once. The delay here is to allow the
1116 # main thread to most likely be blocked in its wait() call.
1117 t = threading.Timer(0.2, kill_proc_timer_thread)
1118 t.start()
1119
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001120 if mswindows:
1121 expected_errorcode = 1
1122 else:
1123 # Should be -9 because of the proc.kill() from the thread.
1124 expected_errorcode = -9
1125
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001126 # Wait for the process to finish; the thread should kill it
1127 # long before it finishes on its own. Supplying a timeout
1128 # triggers a different code path for better coverage.
1129 proc.wait(timeout=20)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001130 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001131 msg="unexpected result in wait from main thread")
1132
1133 # This should be a no-op with no change in returncode.
1134 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001135 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001136 msg="unexpected result in second main wait.")
1137
1138 t.join()
1139 # Ensure that all of the thread results are as expected.
1140 # When a race condition occurs in wait(), the returncode could
1141 # be set by the wrong thread that doesn't actually have it
1142 # leading to an incorrect value.
1143 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001144 ('thread-after-kill-and-wait', expected_errorcode),
1145 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001146 results)
1147
Victor Stinnerb3693582010-05-21 20:13:12 +00001148 def test_issue8780(self):
1149 # Ensure that stdout is inherited from the parent
1150 # if stdout=PIPE is not used
1151 code = ';'.join((
1152 'import subprocess, sys',
1153 'retcode = subprocess.call('
1154 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1155 'assert retcode == 0'))
1156 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001157 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001158
Tim Goldenaf5ac392010-08-06 13:03:56 +00001159 def test_handles_closed_on_exception(self):
1160 # If CreateProcess exits with an error, ensure the
1161 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001162 ifhandle, ifname = tempfile.mkstemp()
1163 ofhandle, ofname = tempfile.mkstemp()
1164 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001165 try:
1166 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1167 stderr=efhandle)
1168 except OSError:
1169 os.close(ifhandle)
1170 os.remove(ifname)
1171 os.close(ofhandle)
1172 os.remove(ofname)
1173 os.close(efhandle)
1174 os.remove(efname)
1175 self.assertFalse(os.path.exists(ifname))
1176 self.assertFalse(os.path.exists(ofname))
1177 self.assertFalse(os.path.exists(efname))
1178
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001179 def test_communicate_epipe(self):
1180 # Issue 10963: communicate() should hide EPIPE
1181 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1182 stdin=subprocess.PIPE,
1183 stdout=subprocess.PIPE,
1184 stderr=subprocess.PIPE)
1185 self.addCleanup(p.stdout.close)
1186 self.addCleanup(p.stderr.close)
1187 self.addCleanup(p.stdin.close)
1188 p.communicate(b"x" * 2**20)
1189
1190 def test_communicate_epipe_only_stdin(self):
1191 # Issue 10963: communicate() should hide EPIPE
1192 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1193 stdin=subprocess.PIPE)
1194 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001195 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001196 p.communicate(b"x" * 2**20)
1197
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001198 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1199 "Requires signal.SIGUSR1")
1200 @unittest.skipUnless(hasattr(os, 'kill'),
1201 "Requires os.kill")
1202 @unittest.skipUnless(hasattr(os, 'getppid'),
1203 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001204 def test_communicate_eintr(self):
1205 # Issue #12493: communicate() should handle EINTR
1206 def handler(signum, frame):
1207 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001208 old_handler = signal.signal(signal.SIGUSR1, handler)
1209 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001210
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001211 args = [sys.executable, "-c",
1212 'import os, signal;'
1213 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001214 for stream in ('stdout', 'stderr'):
1215 kw = {stream: subprocess.PIPE}
1216 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001217 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001218 process.communicate()
1219
Tim Peterse718f612004-10-12 21:51:32 +00001220
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001221 # This test is Linux-ish specific for simplicity to at least have
1222 # some coverage. It is not a platform specific bug.
1223 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1224 "Linux specific")
1225 def test_failed_child_execute_fd_leak(self):
1226 """Test for the fork() failure fd leak reported in issue16327."""
1227 fd_directory = '/proc/%d/fd' % os.getpid()
1228 fds_before_popen = os.listdir(fd_directory)
1229 with self.assertRaises(PopenTestException):
1230 PopenExecuteChildRaises(
1231 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
1232 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1233
1234 # NOTE: This test doesn't verify that the real _execute_child
1235 # does not close the file descriptors itself on the way out
1236 # during an exception. Code inspection has confirmed that.
1237
1238 fds_after_exception = os.listdir(fd_directory)
1239 self.assertEqual(fds_before_popen, fds_after_exception)
1240
Gregory P. Smith6e730002015-04-14 16:14:25 -07001241
1242class RunFuncTestCase(BaseTestCase):
1243 def run_python(self, code, **kwargs):
1244 """Run Python code in a subprocess using subprocess.run"""
1245 argv = [sys.executable, "-c", code]
1246 return subprocess.run(argv, **kwargs)
1247
1248 def test_returncode(self):
1249 # call() function with sequence argument
1250 cp = self.run_python("import sys; sys.exit(47)")
1251 self.assertEqual(cp.returncode, 47)
1252 with self.assertRaises(subprocess.CalledProcessError):
1253 cp.check_returncode()
1254
1255 def test_check(self):
1256 with self.assertRaises(subprocess.CalledProcessError) as c:
1257 self.run_python("import sys; sys.exit(47)", check=True)
1258 self.assertEqual(c.exception.returncode, 47)
1259
1260 def test_check_zero(self):
1261 # check_returncode shouldn't raise when returncode is zero
1262 cp = self.run_python("import sys; sys.exit(0)", check=True)
1263 self.assertEqual(cp.returncode, 0)
1264
1265 def test_timeout(self):
1266 # run() function with timeout argument; we want to test that the child
1267 # process gets killed when the timeout expires. If the child isn't
1268 # killed, this call will deadlock since subprocess.run waits for the
1269 # child.
1270 with self.assertRaises(subprocess.TimeoutExpired):
1271 self.run_python("while True: pass", timeout=0.0001)
1272
1273 def test_capture_stdout(self):
1274 # capture stdout with zero return code
1275 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1276 self.assertIn(b'BDFL', cp.stdout)
1277
1278 def test_capture_stderr(self):
1279 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1280 stderr=subprocess.PIPE)
1281 self.assertIn(b'BDFL', cp.stderr)
1282
1283 def test_check_output_stdin_arg(self):
1284 # run() can be called with stdin set to a file
1285 tf = tempfile.TemporaryFile()
1286 self.addCleanup(tf.close)
1287 tf.write(b'pear')
1288 tf.seek(0)
1289 cp = self.run_python(
1290 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1291 stdin=tf, stdout=subprocess.PIPE)
1292 self.assertIn(b'PEAR', cp.stdout)
1293
1294 def test_check_output_input_arg(self):
1295 # check_output() can be called with input set to a string
1296 cp = self.run_python(
1297 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1298 input=b'pear', stdout=subprocess.PIPE)
1299 self.assertIn(b'PEAR', cp.stdout)
1300
1301 def test_check_output_stdin_with_input_arg(self):
1302 # run() refuses to accept 'stdin' with 'input'
1303 tf = tempfile.TemporaryFile()
1304 self.addCleanup(tf.close)
1305 tf.write(b'pear')
1306 tf.seek(0)
1307 with self.assertRaises(ValueError,
1308 msg="Expected ValueError when stdin and input args supplied.") as c:
1309 output = self.run_python("print('will not be run')",
1310 stdin=tf, input=b'hare')
1311 self.assertIn('stdin', c.exception.args[0])
1312 self.assertIn('input', c.exception.args[0])
1313
1314 def test_check_output_timeout(self):
1315 with self.assertRaises(subprocess.TimeoutExpired) as c:
1316 cp = self.run_python((
1317 "import sys, time\n"
1318 "sys.stdout.write('BDFL')\n"
1319 "sys.stdout.flush()\n"
1320 "time.sleep(3600)"),
1321 # Some heavily loaded buildbots (sparc Debian 3.x) require
1322 # this much time to start and print.
1323 timeout=3, stdout=subprocess.PIPE)
1324 self.assertEqual(c.exception.output, b'BDFL')
1325 # output is aliased to stdout
1326 self.assertEqual(c.exception.stdout, b'BDFL')
1327
1328 def test_run_kwargs(self):
1329 newenv = os.environ.copy()
1330 newenv["FRUIT"] = "banana"
1331 cp = self.run_python(('import sys, os;'
1332 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1333 env=newenv)
1334 self.assertEqual(cp.returncode, 33)
1335
1336
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001337@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001338class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001339
Gregory P. Smith5591b022012-10-10 03:34:47 -07001340 def setUp(self):
1341 super().setUp()
1342 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1343
1344 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001345 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001346 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001347 except OSError as e:
1348 # This avoids hard coding the errno value or the OS perror()
1349 # string and instead capture the exception that we want to see
1350 # below for comparison.
1351 desired_exception = e
Gregory P. Smith5591b022012-10-10 03:34:47 -07001352 desired_exception.strerror += ': ' + repr(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001353 else:
1354 self.fail("chdir to nonexistant directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001355 self._nonexistent_dir)
1356 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001357
Gregory P. Smith5591b022012-10-10 03:34:47 -07001358 def test_exception_cwd(self):
1359 """Test error in the child raised in the parent for a bad cwd."""
1360 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001361 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001362 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001363 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001364 except OSError as e:
1365 # Test that the child process chdir failure actually makes
1366 # it up to the parent process as the correct exception.
1367 self.assertEqual(desired_exception.errno, e.errno)
1368 self.assertEqual(desired_exception.strerror, e.strerror)
1369 else:
1370 self.fail("Expected OSError: %s" % desired_exception)
1371
Gregory P. Smith5591b022012-10-10 03:34:47 -07001372 def test_exception_bad_executable(self):
1373 """Test error in the child raised in the parent for a bad executable."""
1374 desired_exception = self._get_chdir_exception()
1375 try:
1376 p = subprocess.Popen([sys.executable, "-c", ""],
1377 executable=self._nonexistent_dir)
1378 except OSError as e:
1379 # Test that the child process exec failure actually makes
1380 # it up to the parent process as the correct exception.
1381 self.assertEqual(desired_exception.errno, e.errno)
1382 self.assertEqual(desired_exception.strerror, e.strerror)
1383 else:
1384 self.fail("Expected OSError: %s" % desired_exception)
1385
1386 def test_exception_bad_args_0(self):
1387 """Test error in the child raised in the parent for a bad args[0]."""
1388 desired_exception = self._get_chdir_exception()
1389 try:
1390 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1391 except OSError as e:
1392 # Test that the child process exec failure actually makes
1393 # it up to the parent process as the correct exception.
1394 self.assertEqual(desired_exception.errno, e.errno)
1395 self.assertEqual(desired_exception.strerror, e.strerror)
1396 else:
1397 self.fail("Expected OSError: %s" % desired_exception)
1398
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001399 def test_restore_signals(self):
1400 # Code coverage for both values of restore_signals to make sure it
1401 # at least does not blow up.
1402 # A test for behavior would be complex. Contributions welcome.
1403 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1404 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1405
1406 def test_start_new_session(self):
1407 # For code coverage of calling setsid(). We don't care if we get an
1408 # EPERM error from it depending on the test execution environment, that
1409 # still indicates that it was called.
1410 try:
1411 output = subprocess.check_output(
1412 [sys.executable, "-c",
1413 "import os; print(os.getpgid(os.getpid()))"],
1414 start_new_session=True)
1415 except OSError as e:
1416 if e.errno != errno.EPERM:
1417 raise
1418 else:
1419 parent_pgid = os.getpgid(os.getpid())
1420 child_pgid = int(output)
1421 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001422
1423 def test_run_abort(self):
1424 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001425 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001426 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001427 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001428 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001429 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001430
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001431 def test_CalledProcessError_str_signal(self):
1432 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
1433 error_string = str(err)
1434 # We're relying on the repr() of the signal.Signals intenum to provide
1435 # the word signal, the signal name and the numeric value.
1436 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00001437 # We're not being specific about the signal name as some signals have
1438 # multiple names and which name is revealed can vary.
1439 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001440 self.assertIn(str(signal.SIGABRT), error_string)
1441
1442 def test_CalledProcessError_str_unknown_signal(self):
1443 err = subprocess.CalledProcessError(-9876543, "fake cmd")
1444 error_string = str(err)
1445 self.assertIn("unknown signal 9876543.", error_string)
1446
1447 def test_CalledProcessError_str_non_zero(self):
1448 err = subprocess.CalledProcessError(2, "fake cmd")
1449 error_string = str(err)
1450 self.assertIn("non-zero exit status 2.", error_string)
1451
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001452 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001453 # DISCLAIMER: Setting environment variables is *not* a good use
1454 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001455 p = subprocess.Popen([sys.executable, "-c",
1456 'import sys,os;'
1457 'sys.stdout.write(os.getenv("FRUIT"))'],
1458 stdout=subprocess.PIPE,
1459 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02001460 with p:
1461 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001462
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001463 def test_preexec_exception(self):
1464 def raise_it():
1465 raise ValueError("What if two swallows carried a coconut?")
1466 try:
1467 p = subprocess.Popen([sys.executable, "-c", ""],
1468 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001469 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001470 self.assertTrue(
1471 subprocess._posixsubprocess,
1472 "Expected a ValueError from the preexec_fn")
1473 except ValueError as e:
1474 self.assertIn("coconut", e.args[0])
1475 else:
1476 self.fail("Exception raised by preexec_fn did not make it "
1477 "to the parent process.")
1478
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001479 class _TestExecuteChildPopen(subprocess.Popen):
1480 """Used to test behavior at the end of _execute_child."""
1481 def __init__(self, testcase, *args, **kwargs):
1482 self._testcase = testcase
1483 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001484
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001485 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001486 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001487 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001488 finally:
1489 # Open a bunch of file descriptors and verify that
1490 # none of them are the same as the ones the Popen
1491 # instance is using for stdin/stdout/stderr.
1492 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1493 for _ in range(8)]
1494 try:
1495 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001496 self._testcase.assertNotIn(
1497 fd, (self.stdin.fileno(), self.stdout.fileno(),
1498 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001499 msg="At least one fd was closed early.")
1500 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01001501 for fd in devzero_fds:
1502 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001503
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001504 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1505 def test_preexec_errpipe_does_not_double_close_pipes(self):
1506 """Issue16140: Don't double close pipes on preexec error."""
1507
1508 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08001509 raise subprocess.SubprocessError(
1510 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001511
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08001512 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001513 self._TestExecuteChildPopen(
1514 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001515 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1516 stderr=subprocess.PIPE, preexec_fn=raise_it)
1517
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001518 def test_preexec_gc_module_failure(self):
1519 # This tests the code that disables garbage collection if the child
1520 # process will execute any Python.
1521 def raise_runtime_error():
1522 raise RuntimeError("this shouldn't escape")
1523 enabled = gc.isenabled()
1524 orig_gc_disable = gc.disable
1525 orig_gc_isenabled = gc.isenabled
1526 try:
1527 gc.disable()
1528 self.assertFalse(gc.isenabled())
1529 subprocess.call([sys.executable, '-c', ''],
1530 preexec_fn=lambda: None)
1531 self.assertFalse(gc.isenabled(),
1532 "Popen enabled gc when it shouldn't.")
1533
1534 gc.enable()
1535 self.assertTrue(gc.isenabled())
1536 subprocess.call([sys.executable, '-c', ''],
1537 preexec_fn=lambda: None)
1538 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1539
1540 gc.disable = raise_runtime_error
1541 self.assertRaises(RuntimeError, subprocess.Popen,
1542 [sys.executable, '-c', ''],
1543 preexec_fn=lambda: None)
1544
1545 del gc.isenabled # force an AttributeError
1546 self.assertRaises(AttributeError, subprocess.Popen,
1547 [sys.executable, '-c', ''],
1548 preexec_fn=lambda: None)
1549 finally:
1550 gc.disable = orig_gc_disable
1551 gc.isenabled = orig_gc_isenabled
1552 if not enabled:
1553 gc.disable()
1554
Martin Panterf7fdbda2015-12-05 09:51:52 +00001555 @unittest.skipIf(
1556 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00001557 def test_preexec_fork_failure(self):
1558 # The internal code did not preserve the previous exception when
1559 # re-enabling garbage collection
1560 try:
1561 from resource import getrlimit, setrlimit, RLIMIT_NPROC
1562 except ImportError as err:
1563 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
1564 limits = getrlimit(RLIMIT_NPROC)
1565 [_, hard] = limits
1566 setrlimit(RLIMIT_NPROC, (0, hard))
1567 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00001568 try:
Martin Panterafdd5132015-11-30 02:21:41 +00001569 subprocess.call([sys.executable, '-c', ''],
1570 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00001571 except BlockingIOError:
1572 # Forking should raise EAGAIN, translated to BlockingIOError
1573 pass
1574 else:
1575 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00001576
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001577 def test_args_string(self):
1578 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03001579 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001580 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001581 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001582 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001583 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1584 sys.executable)
1585 os.chmod(fname, 0o700)
1586 p = subprocess.Popen(fname)
1587 p.wait()
1588 os.remove(fname)
1589 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001590
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001591 def test_invalid_args(self):
1592 # invalid arguments should raise ValueError
1593 self.assertRaises(ValueError, subprocess.call,
1594 [sys.executable, "-c",
1595 "import sys; sys.exit(47)"],
1596 startupinfo=47)
1597 self.assertRaises(ValueError, subprocess.call,
1598 [sys.executable, "-c",
1599 "import sys; sys.exit(47)"],
1600 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001601
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001602 def test_shell_sequence(self):
1603 # Run command through the shell (sequence)
1604 newenv = os.environ.copy()
1605 newenv["FRUIT"] = "apple"
1606 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1607 stdout=subprocess.PIPE,
1608 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001609 with p:
1610 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001611
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001612 def test_shell_string(self):
1613 # Run command through the shell (string)
1614 newenv = os.environ.copy()
1615 newenv["FRUIT"] = "apple"
1616 p = subprocess.Popen("echo $FRUIT", shell=1,
1617 stdout=subprocess.PIPE,
1618 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001619 with p:
1620 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001621
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001622 def test_call_string(self):
1623 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03001624 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001625 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001626 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001627 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001628 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1629 sys.executable)
1630 os.chmod(fname, 0o700)
1631 rc = subprocess.call(fname)
1632 os.remove(fname)
1633 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001634
Stefan Krah9542cc62010-07-19 14:20:53 +00001635 def test_specific_shell(self):
1636 # Issue #9265: Incorrect name passed as arg[0].
1637 shells = []
1638 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1639 for name in ['bash', 'ksh']:
1640 sh = os.path.join(prefix, name)
1641 if os.path.isfile(sh):
1642 shells.append(sh)
1643 if not shells: # Will probably work for any shell but csh.
1644 self.skipTest("bash or ksh required for this test")
1645 sh = '/bin/sh'
1646 if os.path.isfile(sh) and not os.path.islink(sh):
1647 # Test will fail if /bin/sh is a symlink to csh.
1648 shells.append(sh)
1649 for sh in shells:
1650 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1651 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02001652 with p:
1653 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00001654
Florent Xicluna4886d242010-03-08 13:27:26 +00001655 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001656 # Do not inherit file handles from the parent.
1657 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07001658 # Also set the SIGINT handler to the default to make sure it's not
1659 # being ignored (some tests rely on that.)
1660 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
1661 try:
1662 p = subprocess.Popen([sys.executable, "-c", """if 1:
1663 import sys, time
1664 sys.stdout.write('x\\n')
1665 sys.stdout.flush()
1666 time.sleep(30)
1667 """],
1668 close_fds=True,
1669 stdin=subprocess.PIPE,
1670 stdout=subprocess.PIPE,
1671 stderr=subprocess.PIPE)
1672 finally:
1673 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001674 # Wait for the interpreter to be completely initialized before
1675 # sending any signal.
1676 p.stdout.read(1)
1677 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001678 return p
1679
Charles-François Natali53221e32013-01-12 16:52:20 +01001680 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1681 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001682 def _kill_dead_process(self, method, *args):
1683 # Do not inherit file handles from the parent.
1684 # It should fix failures on some platforms.
1685 p = subprocess.Popen([sys.executable, "-c", """if 1:
1686 import sys, time
1687 sys.stdout.write('x\\n')
1688 sys.stdout.flush()
1689 """],
1690 close_fds=True,
1691 stdin=subprocess.PIPE,
1692 stdout=subprocess.PIPE,
1693 stderr=subprocess.PIPE)
1694 # Wait for the interpreter to be completely initialized before
1695 # sending any signal.
1696 p.stdout.read(1)
1697 # The process should end after this
1698 time.sleep(1)
1699 # This shouldn't raise even though the child is now dead
1700 getattr(p, method)(*args)
1701 p.communicate()
1702
Florent Xicluna4886d242010-03-08 13:27:26 +00001703 def test_send_signal(self):
1704 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001705 _, stderr = p.communicate()
1706 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001707 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001708
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001709 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001710 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001711 _, stderr = p.communicate()
1712 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001713 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001714
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001715 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001716 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001717 _, stderr = p.communicate()
1718 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001719 self.assertEqual(p.wait(), -signal.SIGTERM)
1720
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001721 def test_send_signal_dead(self):
1722 # Sending a signal to a dead process
1723 self._kill_dead_process('send_signal', signal.SIGINT)
1724
1725 def test_kill_dead(self):
1726 # Killing a dead process
1727 self._kill_dead_process('kill')
1728
1729 def test_terminate_dead(self):
1730 # Terminating a dead process
1731 self._kill_dead_process('terminate')
1732
Victor Stinnerdaf45552013-08-28 00:53:59 +02001733 def _save_fds(self, save_fds):
1734 fds = []
1735 for fd in save_fds:
1736 inheritable = os.get_inheritable(fd)
1737 saved = os.dup(fd)
1738 fds.append((fd, saved, inheritable))
1739 return fds
1740
1741 def _restore_fds(self, fds):
1742 for fd, saved, inheritable in fds:
1743 os.dup2(saved, fd, inheritable=inheritable)
1744 os.close(saved)
1745
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001746 def check_close_std_fds(self, fds):
1747 # Issue #9905: test that subprocess pipes still work properly with
1748 # some standard fds closed
1749 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02001750 saved_fds = self._save_fds(fds)
1751 for fd, saved, inheritable in saved_fds:
1752 if fd == 0:
1753 stdin = saved
1754 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001755 try:
1756 for fd in fds:
1757 os.close(fd)
1758 out, err = subprocess.Popen([sys.executable, "-c",
1759 'import sys;'
1760 'sys.stdout.write("apple");'
1761 'sys.stdout.flush();'
1762 'sys.stderr.write("orange")'],
1763 stdin=stdin,
1764 stdout=subprocess.PIPE,
1765 stderr=subprocess.PIPE).communicate()
1766 err = support.strip_python_stderr(err)
1767 self.assertEqual((out, err), (b'apple', b'orange'))
1768 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001769 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001770
1771 def test_close_fd_0(self):
1772 self.check_close_std_fds([0])
1773
1774 def test_close_fd_1(self):
1775 self.check_close_std_fds([1])
1776
1777 def test_close_fd_2(self):
1778 self.check_close_std_fds([2])
1779
1780 def test_close_fds_0_1(self):
1781 self.check_close_std_fds([0, 1])
1782
1783 def test_close_fds_0_2(self):
1784 self.check_close_std_fds([0, 2])
1785
1786 def test_close_fds_1_2(self):
1787 self.check_close_std_fds([1, 2])
1788
1789 def test_close_fds_0_1_2(self):
1790 # Issue #10806: test that subprocess pipes still work properly with
1791 # all standard fds closed.
1792 self.check_close_std_fds([0, 1, 2])
1793
Gregory P. Smith53dd8162013-12-01 16:03:24 -08001794 def test_small_errpipe_write_fd(self):
1795 """Issue #15798: Popen should work when stdio fds are available."""
1796 new_stdin = os.dup(0)
1797 new_stdout = os.dup(1)
1798 try:
1799 os.close(0)
1800 os.close(1)
1801
1802 # Side test: if errpipe_write fails to have its CLOEXEC
1803 # flag set this should cause the parent to think the exec
1804 # failed. Extremely unlikely: everyone supports CLOEXEC.
1805 subprocess.Popen([
1806 sys.executable, "-c",
1807 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
1808 finally:
1809 # Restore original stdin and stdout
1810 os.dup2(new_stdin, 0)
1811 os.dup2(new_stdout, 1)
1812 os.close(new_stdin)
1813 os.close(new_stdout)
1814
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001815 def test_remapping_std_fds(self):
1816 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03001817 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001818 try:
1819 temp_fds = [fd for fd, fname in temps]
1820
1821 # unlink the files -- we won't need to reopen them
1822 for fd, fname in temps:
1823 os.unlink(fname)
1824
1825 # write some data to what will become stdin, and rewind
1826 os.write(temp_fds[1], b"STDIN")
1827 os.lseek(temp_fds[1], 0, 0)
1828
1829 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02001830 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001831 try:
1832 # duplicate the file objects over the standard fd's
1833 for fd, temp_fd in enumerate(temp_fds):
1834 os.dup2(temp_fd, fd)
1835
1836 # now use those files in the "wrong" order, so that subprocess
1837 # has to rearrange them in the child
1838 p = subprocess.Popen([sys.executable, "-c",
1839 'import sys; got = sys.stdin.read();'
1840 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1841 stdin=temp_fds[1],
1842 stdout=temp_fds[2],
1843 stderr=temp_fds[0])
1844 p.wait()
1845 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001846 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001847
1848 for fd in temp_fds:
1849 os.lseek(fd, 0, 0)
1850
1851 out = os.read(temp_fds[2], 1024)
1852 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1853 self.assertEqual(out, b"got STDIN")
1854 self.assertEqual(err, b"err")
1855
1856 finally:
1857 for fd in temp_fds:
1858 os.close(fd)
1859
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001860 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1861 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03001862 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001863 temp_fds = [fd for fd, fname in temps]
1864 try:
1865 # unlink the files -- we won't need to reopen them
1866 for fd, fname in temps:
1867 os.unlink(fname)
1868
1869 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02001870 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001871 try:
1872 # duplicate the temp files over the standard fd's 0, 1, 2
1873 for fd, temp_fd in enumerate(temp_fds):
1874 os.dup2(temp_fd, fd)
1875
1876 # write some data to what will become stdin, and rewind
1877 os.write(stdin_no, b"STDIN")
1878 os.lseek(stdin_no, 0, 0)
1879
1880 # now use those files in the given order, so that subprocess
1881 # has to rearrange them in the child
1882 p = subprocess.Popen([sys.executable, "-c",
1883 'import sys; got = sys.stdin.read();'
1884 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1885 stdin=stdin_no,
1886 stdout=stdout_no,
1887 stderr=stderr_no)
1888 p.wait()
1889
1890 for fd in temp_fds:
1891 os.lseek(fd, 0, 0)
1892
1893 out = os.read(stdout_no, 1024)
1894 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1895 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001896 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001897
1898 self.assertEqual(out, b"got STDIN")
1899 self.assertEqual(err, b"err")
1900
1901 finally:
1902 for fd in temp_fds:
1903 os.close(fd)
1904
1905 # When duping fds, if there arises a situation where one of the fds is
1906 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1907 # This tests all combinations of this.
1908 def test_swap_fds(self):
1909 self.check_swap_fds(0, 1, 2)
1910 self.check_swap_fds(0, 2, 1)
1911 self.check_swap_fds(1, 0, 2)
1912 self.check_swap_fds(1, 2, 0)
1913 self.check_swap_fds(2, 0, 1)
1914 self.check_swap_fds(2, 1, 0)
1915
Victor Stinner13bb71c2010-04-23 21:41:56 +00001916 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001917 def prepare():
1918 raise ValueError("surrogate:\uDCff")
1919
1920 try:
1921 subprocess.call(
1922 [sys.executable, "-c", "pass"],
1923 preexec_fn=prepare)
1924 except ValueError as err:
1925 # Pure Python implementations keeps the message
1926 self.assertIsNone(subprocess._posixsubprocess)
1927 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001928 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00001929 # _posixsubprocess uses a default message
1930 self.assertIsNotNone(subprocess._posixsubprocess)
1931 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1932 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001933 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00001934
Victor Stinner13bb71c2010-04-23 21:41:56 +00001935 def test_undecodable_env(self):
1936 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01001937 encoded_value = value.encode("ascii", "surrogateescape")
1938
Victor Stinner13bb71c2010-04-23 21:41:56 +00001939 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001940 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001941 env = os.environ.copy()
1942 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01001943 # Use C locale to get ASCII for the locale encoding to force
Victor Stinner89f3ad12010-10-14 10:43:31 +00001944 # surrogate-escaping of \xFF in the child process; otherwise it can
1945 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001946 env['LC_ALL'] = 'C'
Victor Stinner5323fb02013-11-19 23:46:06 +01001947 if sys.platform.startswith("aix"):
1948 # On AIX, the C locale uses the Latin1 encoding
1949 decoded_value = encoded_value.decode("latin1", "surrogateescape")
1950 else:
1951 # On other UNIXes, the C locale uses the ASCII encoding
1952 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001953 stdout = subprocess.check_output(
1954 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001955 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001956 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01001957 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001958
1959 # test bytes
1960 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001961 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001962 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01001963 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001964 stdout = subprocess.check_output(
1965 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001966 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001967 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01001968 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001969
Victor Stinnerb745a742010-05-18 17:17:23 +00001970 def test_bytes_program(self):
1971 abs_program = os.fsencode(sys.executable)
1972 path, program = os.path.split(sys.executable)
1973 program = os.fsencode(program)
1974
1975 # absolute bytes path
1976 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001977 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001978
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001979 # absolute bytes path as a string
1980 cmd = b"'" + abs_program + b"' -c pass"
1981 exitcode = subprocess.call(cmd, shell=True)
1982 self.assertEqual(exitcode, 0)
1983
Victor Stinnerb745a742010-05-18 17:17:23 +00001984 # bytes program, unicode PATH
1985 env = os.environ.copy()
1986 env["PATH"] = path
1987 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001988 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001989
1990 # bytes program, bytes PATH
1991 envb = os.environb.copy()
1992 envb[b"PATH"] = os.fsencode(path)
1993 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001994 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001995
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001996 def test_pipe_cloexec(self):
1997 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1998 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1999
2000 p1 = subprocess.Popen([sys.executable, sleeper],
2001 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2002 stderr=subprocess.PIPE, close_fds=False)
2003
2004 self.addCleanup(p1.communicate, b'')
2005
2006 p2 = subprocess.Popen([sys.executable, fd_status],
2007 stdout=subprocess.PIPE, close_fds=False)
2008
2009 output, error = p2.communicate()
2010 result_fds = set(map(int, output.split(b',')))
2011 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2012 p1.stderr.fileno()])
2013
2014 self.assertFalse(result_fds & unwanted_fds,
2015 "Expected no fds from %r to be open in child, "
2016 "found %r" %
2017 (unwanted_fds, result_fds & unwanted_fds))
2018
2019 def test_pipe_cloexec_real_tools(self):
2020 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2021 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2022
2023 subdata = b'zxcvbn'
2024 data = subdata * 4 + b'\n'
2025
2026 p1 = subprocess.Popen([sys.executable, qcat],
2027 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2028 close_fds=False)
2029
2030 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2031 stdin=p1.stdout, stdout=subprocess.PIPE,
2032 close_fds=False)
2033
2034 self.addCleanup(p1.wait)
2035 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002036 def kill_p1():
2037 try:
2038 p1.terminate()
2039 except ProcessLookupError:
2040 pass
2041 def kill_p2():
2042 try:
2043 p2.terminate()
2044 except ProcessLookupError:
2045 pass
2046 self.addCleanup(kill_p1)
2047 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002048
2049 p1.stdin.write(data)
2050 p1.stdin.close()
2051
2052 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2053
2054 self.assertTrue(readfiles, "The child hung")
2055 self.assertEqual(p2.stdout.read(), data)
2056
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002057 p1.stdout.close()
2058 p2.stdout.close()
2059
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002060 def test_close_fds(self):
2061 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2062
2063 fds = os.pipe()
2064 self.addCleanup(os.close, fds[0])
2065 self.addCleanup(os.close, fds[1])
2066
2067 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002068 # add a bunch more fds
2069 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002070 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002071 self.addCleanup(os.close, fd)
2072 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002073
Victor Stinnerdaf45552013-08-28 00:53:59 +02002074 for fd in open_fds:
2075 os.set_inheritable(fd, True)
2076
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002077 p = subprocess.Popen([sys.executable, fd_status],
2078 stdout=subprocess.PIPE, close_fds=False)
2079 output, ignored = p.communicate()
2080 remaining_fds = set(map(int, output.split(b',')))
2081
2082 self.assertEqual(remaining_fds & open_fds, open_fds,
2083 "Some fds were closed")
2084
2085 p = subprocess.Popen([sys.executable, fd_status],
2086 stdout=subprocess.PIPE, close_fds=True)
2087 output, ignored = p.communicate()
2088 remaining_fds = set(map(int, output.split(b',')))
2089
2090 self.assertFalse(remaining_fds & open_fds,
2091 "Some fds were left open")
2092 self.assertIn(1, remaining_fds, "Subprocess failed")
2093
Gregory P. Smith8facece2012-01-21 14:01:08 -08002094 # Keep some of the fd's we opened open in the subprocess.
2095 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2096 fds_to_keep = set(open_fds.pop() for _ in range(8))
2097 p = subprocess.Popen([sys.executable, fd_status],
2098 stdout=subprocess.PIPE, close_fds=True,
2099 pass_fds=())
2100 output, ignored = p.communicate()
2101 remaining_fds = set(map(int, output.split(b',')))
2102
2103 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
2104 "Some fds not in pass_fds were left open")
2105 self.assertIn(1, remaining_fds, "Subprocess failed")
2106
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002107
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002108 @unittest.skipIf(sys.platform.startswith("freebsd") and
2109 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2110 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002111 def test_close_fds_when_max_fd_is_lowered(self):
2112 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2113 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2114
Gregory P. Smith634aa682014-06-15 17:51:04 -07002115 # This launches the meat of the test in a child process to
2116 # avoid messing with the larger unittest processes maximum
2117 # number of file descriptors.
2118 # This process launches:
2119 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2120 # a bunch of high open fds above the new lower rlimit.
2121 # Those are reported via stdout before launching a new
2122 # process with close_fds=False to run the actual test:
2123 # +--> The TEST: This one launches a fd_status.py
2124 # subprocess with close_fds=True so we can find out if
2125 # any of the fds above the lowered rlimit are still open.
2126 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2127 '''
2128 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002129 open_fds = set()
2130 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002131 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002132 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002133 open_fds.add(fd)
2134
2135 # Leave a two pairs of low ones available for use by the
2136 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002137 # We also leave 10 more open as some Python buildbots run into
2138 # "too many open files" errors during the test if we do not.
2139 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002140 os.close(fd)
2141 open_fds.remove(fd)
2142
2143 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002144 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002145 os.set_inheritable(fd, True)
2146
2147 max_fd_open = max(open_fds)
2148
Gregory P. Smith634aa682014-06-15 17:51:04 -07002149 # Communicate the open_fds to the parent unittest.TestCase process.
2150 print(','.join(map(str, sorted(open_fds))))
2151 sys.stdout.flush()
2152
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002153 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2154 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002155 # 29 is lower than the highest fds we are leaving open.
2156 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002157 # Launch a new Python interpreter with our low fd rlim_cur that
2158 # inherits open fds above that limit. It then uses subprocess
2159 # with close_fds=True to get a report of open fds in the child.
2160 # An explicit list of fds to check is passed to fd_status.py as
2161 # letting fd_status rely on its default logic would miss the
2162 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002163 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002164 [sys.executable, '-c',
2165 textwrap.dedent("""
2166 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002167 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002168 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002169 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002170 """.format(max_fd=max_fd_open+1))],
2171 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002172 finally:
2173 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002174 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002175
2176 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002177 output_lines = output.splitlines()
2178 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002179 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002180 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2181 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002182
Gregory P. Smith634aa682014-06-15 17:51:04 -07002183 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002184 msg="Some fds were left open.")
2185
2186
Victor Stinner88701e22011-06-01 13:13:04 +02002187 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2188 # descriptor of a pipe closed in the parent process is valid in the
2189 # child process according to fstat(), but the mode of the file
2190 # descriptor is invalid, and read or write raise an error.
2191 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002192 def test_pass_fds(self):
2193 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2194
2195 open_fds = set()
2196
2197 for x in range(5):
2198 fds = os.pipe()
2199 self.addCleanup(os.close, fds[0])
2200 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002201 os.set_inheritable(fds[0], True)
2202 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002203 open_fds.update(fds)
2204
2205 for fd in open_fds:
2206 p = subprocess.Popen([sys.executable, fd_status],
2207 stdout=subprocess.PIPE, close_fds=True,
2208 pass_fds=(fd, ))
2209 output, ignored = p.communicate()
2210
2211 remaining_fds = set(map(int, output.split(b',')))
2212 to_be_closed = open_fds - {fd}
2213
2214 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2215 self.assertFalse(remaining_fds & to_be_closed,
2216 "fd to be closed passed")
2217
2218 # pass_fds overrides close_fds with a warning.
2219 with self.assertWarns(RuntimeWarning) as context:
2220 self.assertFalse(subprocess.call(
2221 [sys.executable, "-c", "import sys; sys.exit(0)"],
2222 close_fds=False, pass_fds=(fd, )))
2223 self.assertIn('overriding close_fds', str(context.warning))
2224
Victor Stinnerdaf45552013-08-28 00:53:59 +02002225 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002226 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002227
2228 inheritable, non_inheritable = os.pipe()
2229 self.addCleanup(os.close, inheritable)
2230 self.addCleanup(os.close, non_inheritable)
2231 os.set_inheritable(inheritable, True)
2232 os.set_inheritable(non_inheritable, False)
2233 pass_fds = (inheritable, non_inheritable)
2234 args = [sys.executable, script]
2235 args += list(map(str, pass_fds))
2236
2237 p = subprocess.Popen(args,
2238 stdout=subprocess.PIPE, close_fds=True,
2239 pass_fds=pass_fds)
2240 output, ignored = p.communicate()
2241 fds = set(map(int, output.split(b',')))
2242
2243 # the inheritable file descriptor must be inherited, so its inheritable
2244 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002245 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002246
2247 # inheritable flag must not be changed in the parent process
2248 self.assertEqual(os.get_inheritable(inheritable), True)
2249 self.assertEqual(os.get_inheritable(non_inheritable), False)
2250
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002251 def test_stdout_stdin_are_single_inout_fd(self):
2252 with io.open(os.devnull, "r+") as inout:
2253 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2254 stdout=inout, stdin=inout)
2255 p.wait()
2256
2257 def test_stdout_stderr_are_single_inout_fd(self):
2258 with io.open(os.devnull, "r+") as inout:
2259 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2260 stdout=inout, stderr=inout)
2261 p.wait()
2262
2263 def test_stderr_stdin_are_single_inout_fd(self):
2264 with io.open(os.devnull, "r+") as inout:
2265 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2266 stderr=inout, stdin=inout)
2267 p.wait()
2268
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002269 def test_wait_when_sigchild_ignored(self):
2270 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2271 sigchild_ignore = support.findfile("sigchild_ignore.py",
2272 subdir="subprocessdata")
2273 p = subprocess.Popen([sys.executable, sigchild_ignore],
2274 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2275 stdout, stderr = p.communicate()
2276 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002277 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002278 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002279
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002280 def test_select_unbuffered(self):
2281 # Issue #11459: bufsize=0 should really set the pipes as
2282 # unbuffered (and therefore let select() work properly).
2283 select = support.import_module("select")
2284 p = subprocess.Popen([sys.executable, "-c",
2285 'import sys;'
2286 'sys.stdout.write("apple")'],
2287 stdout=subprocess.PIPE,
2288 bufsize=0)
2289 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002290 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002291 try:
2292 self.assertEqual(f.read(4), b"appl")
2293 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2294 finally:
2295 p.wait()
2296
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002297 def test_zombie_fast_process_del(self):
2298 # Issue #12650: on Unix, if Popen.__del__() was called before the
2299 # process exited, it wouldn't be added to subprocess._active, and would
2300 # remain a zombie.
2301 # spawn a Popen, and delete its reference before it exits
2302 p = subprocess.Popen([sys.executable, "-c",
2303 'import sys, time;'
2304 'time.sleep(0.2)'],
2305 stdout=subprocess.PIPE,
2306 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002307 self.addCleanup(p.stdout.close)
2308 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002309 ident = id(p)
2310 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002311 with support.check_warnings(('', ResourceWarning)):
2312 p = None
2313
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002314 # check that p is in the active processes list
2315 self.assertIn(ident, [id(o) for o in subprocess._active])
2316
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002317 def test_leak_fast_process_del_killed(self):
2318 # Issue #12650: on Unix, if Popen.__del__() was called before the
2319 # process exited, and the process got killed by a signal, it would never
2320 # be removed from subprocess._active, which triggered a FD and memory
2321 # leak.
2322 # spawn a Popen, delete its reference and kill it
2323 p = subprocess.Popen([sys.executable, "-c",
2324 'import time;'
2325 'time.sleep(3)'],
2326 stdout=subprocess.PIPE,
2327 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002328 self.addCleanup(p.stdout.close)
2329 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002330 ident = id(p)
2331 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002332 with support.check_warnings(('', ResourceWarning)):
2333 p = None
2334
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002335 os.kill(pid, signal.SIGKILL)
2336 # check that p is in the active processes list
2337 self.assertIn(ident, [id(o) for o in subprocess._active])
2338
2339 # let some time for the process to exit, and create a new Popen: this
2340 # should trigger the wait() of p
2341 time.sleep(0.2)
Andrew Svetlov3438fa42012-12-17 23:35:18 +02002342 with self.assertRaises(OSError) as c:
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002343 with subprocess.Popen(['nonexisting_i_hope'],
2344 stdout=subprocess.PIPE,
2345 stderr=subprocess.PIPE) as proc:
2346 pass
2347 # p should have been wait()ed on, and removed from the _active list
2348 self.assertRaises(OSError, os.waitpid, pid, 0)
2349 self.assertNotIn(ident, [id(o) for o in subprocess._active])
2350
Charles-François Natali249cdc32013-08-25 18:24:45 +02002351 def test_close_fds_after_preexec(self):
2352 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2353
2354 # this FD is used as dup2() target by preexec_fn, and should be closed
2355 # in the child process
2356 fd = os.dup(1)
2357 self.addCleanup(os.close, fd)
2358
2359 p = subprocess.Popen([sys.executable, fd_status],
2360 stdout=subprocess.PIPE, close_fds=True,
2361 preexec_fn=lambda: os.dup2(1, fd))
2362 output, ignored = p.communicate()
2363
2364 remaining_fds = set(map(int, output.split(b',')))
2365
2366 self.assertNotIn(fd, remaining_fds)
2367
Victor Stinner8f437aa2014-10-05 17:25:19 +02002368 @support.cpython_only
2369 def test_fork_exec(self):
2370 # Issue #22290: fork_exec() must not crash on memory allocation failure
2371 # or other errors
2372 import _posixsubprocess
2373 gc_enabled = gc.isenabled()
2374 try:
2375 # Use a preexec function and enable the garbage collector
2376 # to force fork_exec() to re-enable the garbage collector
2377 # on error.
2378 func = lambda: None
2379 gc.enable()
2380
Victor Stinner8f437aa2014-10-05 17:25:19 +02002381 for args, exe_list, cwd, env_list in (
2382 (123, [b"exe"], None, [b"env"]),
2383 ([b"arg"], 123, None, [b"env"]),
2384 ([b"arg"], [b"exe"], 123, [b"env"]),
2385 ([b"arg"], [b"exe"], None, 123),
2386 ):
2387 with self.assertRaises(TypeError):
2388 _posixsubprocess.fork_exec(
2389 args, exe_list,
2390 True, [], cwd, env_list,
2391 -1, -1, -1, -1,
2392 1, 2, 3, 4,
2393 True, True, func)
2394 finally:
2395 if not gc_enabled:
2396 gc.disable()
2397
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002398 @support.cpython_only
2399 def test_fork_exec_sorted_fd_sanity_check(self):
2400 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
2401 import _posixsubprocess
2402 gc_enabled = gc.isenabled()
2403 try:
2404 gc.enable()
2405
2406 for fds_to_keep in (
2407 (-1, 2, 3, 4, 5), # Negative number.
2408 ('str', 4), # Not an int.
2409 (18, 23, 42, 2**63), # Out of range.
2410 (5, 4), # Not sorted.
2411 (6, 7, 7, 8), # Duplicate.
2412 ):
2413 with self.assertRaises(
2414 ValueError,
2415 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
2416 _posixsubprocess.fork_exec(
2417 [b"false"], [b"false"],
2418 True, fds_to_keep, None, [b"env"],
2419 -1, -1, -1, -1,
2420 1, 2, 3, 4,
2421 True, True, None)
2422 self.assertIn('fds_to_keep', str(c.exception))
2423 finally:
2424 if not gc_enabled:
2425 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02002426
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00002427 def test_communicate_BrokenPipeError_stdin_close(self):
2428 # By not setting stdout or stderr or a timeout we force the fast path
2429 # that just calls _stdin_write() internally due to our mock.
2430 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2431 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2432 mock_proc_stdin.close.side_effect = BrokenPipeError
2433 proc.communicate() # Should swallow BrokenPipeError from close.
2434 mock_proc_stdin.close.assert_called_with()
2435
2436 def test_communicate_BrokenPipeError_stdin_write(self):
2437 # By not setting stdout or stderr or a timeout we force the fast path
2438 # that just calls _stdin_write() internally due to our mock.
2439 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2440 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2441 mock_proc_stdin.write.side_effect = BrokenPipeError
2442 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
2443 mock_proc_stdin.write.assert_called_once_with(b'stuff')
2444 mock_proc_stdin.close.assert_called_once_with()
2445
2446 def test_communicate_BrokenPipeError_stdin_flush(self):
2447 # Setting stdin and stdout forces the ._communicate() code path.
2448 # python -h exits faster than python -c pass (but spams stdout).
2449 proc = subprocess.Popen([sys.executable, '-h'],
2450 stdin=subprocess.PIPE,
2451 stdout=subprocess.PIPE)
2452 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
2453 open(os.devnull, 'wb') as dev_null:
2454 mock_proc_stdin.flush.side_effect = BrokenPipeError
2455 # because _communicate registers a selector using proc.stdin...
2456 mock_proc_stdin.fileno.return_value = dev_null.fileno()
2457 # _communicate() should swallow BrokenPipeError from flush.
2458 proc.communicate(b'stuff')
2459 mock_proc_stdin.flush.assert_called_once_with()
2460
2461 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
2462 # Setting stdin and stdout forces the ._communicate() code path.
2463 # python -h exits faster than python -c pass (but spams stdout).
2464 proc = subprocess.Popen([sys.executable, '-h'],
2465 stdin=subprocess.PIPE,
2466 stdout=subprocess.PIPE)
2467 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2468 mock_proc_stdin.close.side_effect = BrokenPipeError
2469 # _communicate() should swallow BrokenPipeError from close.
2470 proc.communicate(timeout=999)
2471 mock_proc_stdin.close.assert_called_once_with()
2472
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002473
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002474@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00002475class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002476
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002477 def test_startupinfo(self):
2478 # startupinfo argument
2479 # We uses hardcoded constants, because we do not want to
2480 # depend on win32all.
2481 STARTF_USESHOWWINDOW = 1
2482 SW_MAXIMIZE = 3
2483 startupinfo = subprocess.STARTUPINFO()
2484 startupinfo.dwFlags = STARTF_USESHOWWINDOW
2485 startupinfo.wShowWindow = SW_MAXIMIZE
2486 # Since Python is a console process, it won't be affected
2487 # by wShowWindow, but the argument should be silently
2488 # ignored
2489 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002490 startupinfo=startupinfo)
2491
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002492 def test_creationflags(self):
2493 # creationflags argument
2494 CREATE_NEW_CONSOLE = 16
2495 sys.stderr.write(" a DOS box should flash briefly ...\n")
2496 subprocess.call(sys.executable +
2497 ' -c "import time; time.sleep(0.25)"',
2498 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002499
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002500 def test_invalid_args(self):
2501 # invalid arguments should raise ValueError
2502 self.assertRaises(ValueError, subprocess.call,
2503 [sys.executable, "-c",
2504 "import sys; sys.exit(47)"],
2505 preexec_fn=lambda: 1)
2506 self.assertRaises(ValueError, subprocess.call,
2507 [sys.executable, "-c",
2508 "import sys; sys.exit(47)"],
2509 stdout=subprocess.PIPE,
2510 close_fds=True)
2511
2512 def test_close_fds(self):
2513 # close file descriptors
2514 rc = subprocess.call([sys.executable, "-c",
2515 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002516 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002517 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002518
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002519 def test_shell_sequence(self):
2520 # Run command through the shell (sequence)
2521 newenv = os.environ.copy()
2522 newenv["FRUIT"] = "physalis"
2523 p = subprocess.Popen(["set"], shell=1,
2524 stdout=subprocess.PIPE,
2525 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002526 with p:
2527 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00002528
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002529 def test_shell_string(self):
2530 # Run command through the shell (string)
2531 newenv = os.environ.copy()
2532 newenv["FRUIT"] = "physalis"
2533 p = subprocess.Popen("set", shell=1,
2534 stdout=subprocess.PIPE,
2535 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002536 with p:
2537 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002538
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002539 def test_call_string(self):
2540 # call() function with string argument on Windows
2541 rc = subprocess.call(sys.executable +
2542 ' -c "import sys; sys.exit(47)"')
2543 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002544
Florent Xicluna4886d242010-03-08 13:27:26 +00002545 def _kill_process(self, method, *args):
2546 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00002547 p = subprocess.Popen([sys.executable, "-c", """if 1:
2548 import sys, time
2549 sys.stdout.write('x\\n')
2550 sys.stdout.flush()
2551 time.sleep(30)
2552 """],
2553 stdin=subprocess.PIPE,
2554 stdout=subprocess.PIPE,
2555 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002556 with p:
2557 # Wait for the interpreter to be completely initialized before
2558 # sending any signal.
2559 p.stdout.read(1)
2560 getattr(p, method)(*args)
2561 _, stderr = p.communicate()
2562 self.assertStderrEqual(stderr, b'')
2563 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00002564 self.assertNotEqual(returncode, 0)
2565
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002566 def _kill_dead_process(self, method, *args):
2567 p = subprocess.Popen([sys.executable, "-c", """if 1:
2568 import sys, time
2569 sys.stdout.write('x\\n')
2570 sys.stdout.flush()
2571 sys.exit(42)
2572 """],
2573 stdin=subprocess.PIPE,
2574 stdout=subprocess.PIPE,
2575 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002576 with p:
2577 # Wait for the interpreter to be completely initialized before
2578 # sending any signal.
2579 p.stdout.read(1)
2580 # The process should end after this
2581 time.sleep(1)
2582 # This shouldn't raise even though the child is now dead
2583 getattr(p, method)(*args)
2584 _, stderr = p.communicate()
2585 self.assertStderrEqual(stderr, b'')
2586 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002587 self.assertEqual(rc, 42)
2588
Florent Xicluna4886d242010-03-08 13:27:26 +00002589 def test_send_signal(self):
2590 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00002591
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002592 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002593 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00002594
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002595 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002596 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00002597
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002598 def test_send_signal_dead(self):
2599 self._kill_dead_process('send_signal', signal.SIGTERM)
2600
2601 def test_kill_dead(self):
2602 self._kill_dead_process('kill')
2603
2604 def test_terminate_dead(self):
2605 self._kill_dead_process('terminate')
2606
Martin Panter23172bd2016-04-16 11:28:10 +00002607class MiscTests(unittest.TestCase):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002608 def test_getoutput(self):
2609 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
2610 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
2611 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00002612
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002613 # we use mkdtemp in the next line to create an empty directory
2614 # under our exclusive control; from that, we can invent a pathname
2615 # that we _know_ won't exist. This is guaranteed to fail.
2616 dir = None
2617 try:
2618 dir = tempfile.mkdtemp()
2619 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00002620 status, output = subprocess.getstatusoutput(
2621 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002622 self.assertNotEqual(status, 0)
2623 finally:
2624 if dir is not None:
2625 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00002626
Gregory P. Smithace55862015-04-07 15:57:54 -07002627 def test__all__(self):
2628 """Ensure that __all__ is populated properly."""
Martin Panter528619b2016-04-16 23:42:37 +00002629 intentionally_excluded = {"list2cmdline", "Handle"}
Gregory P. Smithace55862015-04-07 15:57:54 -07002630 exported = set(subprocess.__all__)
2631 possible_exports = set()
2632 import types
2633 for name, value in subprocess.__dict__.items():
2634 if name.startswith('_'):
2635 continue
2636 if isinstance(value, (types.ModuleType,)):
2637 continue
2638 possible_exports.add(name)
2639 self.assertEqual(exported, possible_exports - intentionally_excluded)
2640
2641
Martin Panter23172bd2016-04-16 11:28:10 +00002642@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
2643 "Test needs selectors.PollSelector")
2644class ProcessTestCaseNoPoll(ProcessTestCase):
2645 def setUp(self):
2646 self.orig_selector = subprocess._PopenSelector
2647 subprocess._PopenSelector = selectors.SelectSelector
2648 ProcessTestCase.setUp(self)
2649
2650 def tearDown(self):
2651 subprocess._PopenSelector = self.orig_selector
2652 ProcessTestCase.tearDown(self)
2653
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002654
Tim Golden126c2962010-08-11 14:20:40 +00002655@unittest.skipUnless(mswindows, "Windows-specific tests")
2656class CommandsWithSpaces (BaseTestCase):
2657
2658 def setUp(self):
2659 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03002660 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00002661 self.fname = fname.lower ()
2662 os.write(f, b"import sys;"
2663 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
2664 )
2665 os.close(f)
2666
2667 def tearDown(self):
2668 os.remove(self.fname)
2669 super().tearDown()
2670
2671 def with_spaces(self, *args, **kwargs):
2672 kwargs['stdout'] = subprocess.PIPE
2673 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02002674 with p:
2675 self.assertEqual(
2676 p.stdout.read ().decode("mbcs"),
2677 "2 [%r, 'ab cd']" % self.fname
2678 )
Tim Golden126c2962010-08-11 14:20:40 +00002679
2680 def test_shell_string_with_spaces(self):
2681 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002682 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2683 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002684
2685 def test_shell_sequence_with_spaces(self):
2686 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002687 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002688
2689 def test_noshell_string_with_spaces(self):
2690 # call() function with string argument with spaces on Windows
2691 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2692 "ab cd"))
2693
2694 def test_noshell_sequence_with_spaces(self):
2695 # call() function with sequence argument with spaces on Windows
2696 self.with_spaces([sys.executable, self.fname, "ab cd"])
2697
Brian Curtin79cdb662010-12-03 02:46:02 +00002698
Georg Brandla86b2622012-02-20 21:34:57 +01002699class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00002700
2701 def test_pipe(self):
2702 with subprocess.Popen([sys.executable, "-c",
2703 "import sys;"
2704 "sys.stdout.write('stdout');"
2705 "sys.stderr.write('stderr');"],
2706 stdout=subprocess.PIPE,
2707 stderr=subprocess.PIPE) as proc:
2708 self.assertEqual(proc.stdout.read(), b"stdout")
2709 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2710
2711 self.assertTrue(proc.stdout.closed)
2712 self.assertTrue(proc.stderr.closed)
2713
2714 def test_returncode(self):
2715 with subprocess.Popen([sys.executable, "-c",
2716 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002717 pass
2718 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002719 self.assertEqual(proc.returncode, 100)
2720
2721 def test_communicate_stdin(self):
2722 with subprocess.Popen([sys.executable, "-c",
2723 "import sys;"
2724 "sys.exit(sys.stdin.read() == 'context')"],
2725 stdin=subprocess.PIPE) as proc:
2726 proc.communicate(b"context")
2727 self.assertEqual(proc.returncode, 1)
2728
2729 def test_invalid_args(self):
Andrew Svetlovb1726972012-12-26 23:34:54 +02002730 with self.assertRaises(FileNotFoundError) as c:
Brian Curtin79cdb662010-12-03 02:46:02 +00002731 with subprocess.Popen(['nonexisting_i_hope'],
2732 stdout=subprocess.PIPE,
2733 stderr=subprocess.PIPE) as proc:
2734 pass
2735
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002736 def test_broken_pipe_cleanup(self):
2737 """Broken pipe error should not prevent wait() (Issue 21619)"""
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002738 proc = subprocess.Popen([sys.executable, '-c', 'pass'],
Victor Stinner20f4bd42015-03-05 02:38:41 +01002739 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01002740 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002741 proc = proc.__enter__()
2742 # Prepare to send enough data to overflow any OS pipe buffering and
2743 # guarantee a broken pipe error. Data is held in BufferedWriter
2744 # buffer until closed.
2745 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002746 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002747 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02002748 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002749 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002750 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002751
Brian Curtin79cdb662010-12-03 02:46:02 +00002752
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002753def test_main():
2754 unit_tests = (ProcessTestCase,
2755 POSIXProcessTestCase,
2756 Win32ProcessTestCase,
Martin Panter23172bd2016-04-16 11:28:10 +00002757 MiscTests,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002758 ProcessTestCaseNoPoll,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002759 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02002760 ContextManagerTests,
Gregory P. Smith6e730002015-04-14 16:14:25 -07002761 RunFuncTestCase,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02002762 )
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002763
2764 support.run_unittest(*unit_tests)
2765 support.reap_children()
2766
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002767if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002768 unittest.main()