blob: 89de6d1b1ac9a22e68802e98106818d9eff81d83 [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
Steve Dower22d06982016-09-06 19:38:15 -070024if support.PGO:
25 raise unittest.SkipTest("test is not helpful for PGO")
26
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000027mswindows = (sys.platform == "win32")
28
29#
30# Depends on the following external programs: Python
31#
32
33if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000034 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
35 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000036else:
37 SETBINARY = ''
38
Florent Xiclunab1e94e82010-02-27 22:12:37 +000039
Florent Xiclunac049d872010-03-27 22:47:23 +000040class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000041 def setUp(self):
42 # Try to minimize the number of children we have so this test
43 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000044 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000045
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000046 def tearDown(self):
47 for inst in subprocess._active:
48 inst.wait()
49 subprocess._cleanup()
50 self.assertFalse(subprocess._active, "subprocess._active not empty")
51
Florent Xiclunab1e94e82010-02-27 22:12:37 +000052 def assertStderrEqual(self, stderr, expected, msg=None):
53 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
54 # shutdown time. That frustrates tests trying to check stderr produced
55 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000056 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040057 # strip_python_stderr also strips whitespace, so we do too.
58 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000059 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000060
Florent Xiclunac049d872010-03-27 22:47:23 +000061
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080062class PopenTestException(Exception):
63 pass
64
65
66class PopenExecuteChildRaises(subprocess.Popen):
67 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
68 _execute_child fails.
69 """
70 def _execute_child(self, *args, **kwargs):
71 raise PopenTestException("Forced Exception for Test")
72
73
Florent Xiclunac049d872010-03-27 22:47:23 +000074class ProcessTestCase(BaseTestCase):
75
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070076 def test_io_buffered_by_default(self):
77 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
78 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
79 stderr=subprocess.PIPE)
80 try:
81 self.assertIsInstance(p.stdin, io.BufferedIOBase)
82 self.assertIsInstance(p.stdout, io.BufferedIOBase)
83 self.assertIsInstance(p.stderr, io.BufferedIOBase)
84 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -070085 p.stdin.close()
86 p.stdout.close()
87 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070088 p.wait()
89
90 def test_io_unbuffered_works(self):
91 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
92 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
93 stderr=subprocess.PIPE, bufsize=0)
94 try:
95 self.assertIsInstance(p.stdin, io.RawIOBase)
96 self.assertIsInstance(p.stdout, io.RawIOBase)
97 self.assertIsInstance(p.stderr, io.RawIOBase)
98 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -070099 p.stdin.close()
100 p.stdout.close()
101 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700102 p.wait()
103
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000104 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000105 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000106 rc = subprocess.call([sys.executable, "-c",
107 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000108 self.assertEqual(rc, 47)
109
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400110 def test_call_timeout(self):
111 # call() function with timeout argument; we want to test that the child
112 # process gets killed when the timeout expires. If the child isn't
113 # killed, this call will deadlock since subprocess.call waits for the
114 # child.
115 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
116 [sys.executable, "-c", "while True: pass"],
117 timeout=0.1)
118
Peter Astrand454f7672005-01-01 09:36:35 +0000119 def test_check_call_zero(self):
120 # check_call() function with zero return code
121 rc = subprocess.check_call([sys.executable, "-c",
122 "import sys; sys.exit(0)"])
123 self.assertEqual(rc, 0)
124
125 def test_check_call_nonzero(self):
126 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000127 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000128 subprocess.check_call([sys.executable, "-c",
129 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000130 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000131
Georg Brandlf9734072008-12-07 15:30:06 +0000132 def test_check_output(self):
133 # check_output() function with zero return code
134 output = subprocess.check_output(
135 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000136 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000137
138 def test_check_output_nonzero(self):
139 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000140 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000141 subprocess.check_output(
142 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000143 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000144
145 def test_check_output_stderr(self):
146 # check_output() function stderr redirected to stdout
147 output = subprocess.check_output(
148 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
149 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000150 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000151
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300152 def test_check_output_stdin_arg(self):
153 # check_output() can be called with stdin set to a file
154 tf = tempfile.TemporaryFile()
155 self.addCleanup(tf.close)
156 tf.write(b'pear')
157 tf.seek(0)
158 output = subprocess.check_output(
159 [sys.executable, "-c",
160 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
161 stdin=tf)
162 self.assertIn(b'PEAR', output)
163
164 def test_check_output_input_arg(self):
165 # check_output() can be called with input set to a string
166 output = subprocess.check_output(
167 [sys.executable, "-c",
168 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
169 input=b'pear')
170 self.assertIn(b'PEAR', output)
171
Georg Brandlf9734072008-12-07 15:30:06 +0000172 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300173 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000174 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000175 output = subprocess.check_output(
176 [sys.executable, "-c", "print('will not be run')"],
177 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000178 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000179 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000180
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300181 def test_check_output_stdin_with_input_arg(self):
182 # check_output() refuses to accept 'stdin' with 'input'
183 tf = tempfile.TemporaryFile()
184 self.addCleanup(tf.close)
185 tf.write(b'pear')
186 tf.seek(0)
187 with self.assertRaises(ValueError) as c:
188 output = subprocess.check_output(
189 [sys.executable, "-c", "print('will not be run')"],
190 stdin=tf, input=b'hare')
191 self.fail("Expected ValueError when stdin and input args supplied.")
192 self.assertIn('stdin', c.exception.args[0])
193 self.assertIn('input', c.exception.args[0])
194
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400195 def test_check_output_timeout(self):
196 # check_output() function with timeout arg
197 with self.assertRaises(subprocess.TimeoutExpired) as c:
198 output = subprocess.check_output(
199 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200200 "import sys, time\n"
201 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400202 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200203 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400204 # Some heavily loaded buildbots (sparc Debian 3.x) require
205 # this much time to start and print.
206 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400207 self.fail("Expected TimeoutExpired.")
208 self.assertEqual(c.exception.output, b'BDFL')
209
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000210 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000211 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000212 newenv = os.environ.copy()
213 newenv["FRUIT"] = "banana"
214 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000215 'import sys, os;'
216 'sys.exit(os.getenv("FRUIT")=="banana")'],
217 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000218 self.assertEqual(rc, 1)
219
Victor Stinner87b9bc32011-06-01 00:57:47 +0200220 def test_invalid_args(self):
221 # Popen() called with invalid arguments should raise TypeError
222 # but Popen.__del__ should not complain (issue #12085)
223 with support.captured_stderr() as s:
224 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
225 argcount = subprocess.Popen.__init__.__code__.co_argcount
226 too_many_args = [0] * (argcount + 1)
227 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
228 self.assertEqual(s.getvalue(), '')
229
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000230 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000231 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000232 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000233 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000234 self.addCleanup(p.stdout.close)
235 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000236 p.wait()
237 self.assertEqual(p.stdin, None)
238
239 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200240 # .stdout is None when not redirected, and the child's stdout will
241 # be inherited from the parent. In order to test this we run a
242 # subprocess in a subprocess:
243 # this_test
244 # \-- subprocess created by this test (parent)
245 # \-- subprocess created by the parent subprocess (child)
246 # The parent doesn't specify stdout, so the child will use the
247 # parent's stdout. This test checks that the message printed by the
248 # child goes to the parent stdout. The parent also checks that the
249 # child's stdout is None. See #11963.
250 code = ('import sys; from subprocess import Popen, PIPE;'
251 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
252 ' stdin=PIPE, stderr=PIPE);'
253 'p.wait(); assert p.stdout is None;')
254 p = subprocess.Popen([sys.executable, "-c", code],
255 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
256 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000257 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200258 out, err = p.communicate()
259 self.assertEqual(p.returncode, 0, err)
260 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000261
262 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000263 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000264 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000265 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000266 self.addCleanup(p.stdout.close)
267 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000268 p.wait()
269 self.assertEqual(p.stderr, None)
270
Chris Jerdonek776cb192012-10-08 15:56:43 -0700271 def _assert_python(self, pre_args, **kwargs):
272 # We include sys.exit() to prevent the test runner from hanging
273 # whenever python is found.
274 args = pre_args + ["import sys; sys.exit(47)"]
275 p = subprocess.Popen(args, **kwargs)
276 p.wait()
277 self.assertEqual(47, p.returncode)
278
279 def test_executable(self):
280 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700281 #
282 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
283 # determine where its standard library is, so we need the directory
284 # of args[0] to be valid for the Popen() call to Python to succeed.
285 # See also issue #16170 and issue #7774.
286 doesnotexist = os.path.join(os.path.dirname(sys.executable),
287 "doesnotexist")
288 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700289
290 def test_executable_takes_precedence(self):
291 # Check that the executable argument takes precedence over args[0].
292 #
293 # Verify first that the call succeeds without the executable arg.
294 pre_args = [sys.executable, "-c"]
295 self._assert_python(pre_args)
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +0100296 self.assertRaises((FileNotFoundError, PermissionError),
297 self._assert_python, pre_args,
Chris Jerdonek776cb192012-10-08 15:56:43 -0700298 executable="doesnotexist")
299
300 @unittest.skipIf(mswindows, "executable argument replaces shell")
301 def test_executable_replaces_shell(self):
302 # Check that the executable argument replaces the default shell
303 # when shell=True.
304 self._assert_python([], executable=sys.executable, shell=True)
305
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700306 # For use in the test_cwd* tests below.
307 def _normalize_cwd(self, cwd):
308 # Normalize an expected cwd (for Tru64 support).
309 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
310 # strings. See bug #1063571.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300311 with support.change_cwd(cwd):
312 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700313
314 # For use in the test_cwd* tests below.
315 def _split_python_path(self):
316 # Return normalized (python_dir, python_base).
317 python_path = os.path.realpath(sys.executable)
318 return os.path.split(python_path)
319
320 # For use in the test_cwd* tests below.
321 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
322 # Invoke Python via Popen, and assert that (1) the call succeeds,
323 # and that (2) the current working directory of the child process
324 # matches *expected_cwd*.
325 p = subprocess.Popen([python_arg, "-c",
326 "import os, sys; "
327 "sys.stdout.write(os.getcwd()); "
328 "sys.exit(47)"],
329 stdout=subprocess.PIPE,
330 **kwargs)
331 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000332 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700333 self.assertEqual(47, p.returncode)
334 normcase = os.path.normcase
335 self.assertEqual(normcase(expected_cwd),
336 normcase(p.stdout.read().decode("utf-8")))
337
338 def test_cwd(self):
339 # Check that cwd changes the cwd for the child process.
340 temp_dir = tempfile.gettempdir()
341 temp_dir = self._normalize_cwd(temp_dir)
342 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
343
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700344 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700345 def test_cwd_with_relative_arg(self):
346 # Check that Popen looks for args[0] relative to cwd if args[0]
347 # is relative.
348 python_dir, python_base = self._split_python_path()
349 rel_python = os.path.join(os.curdir, python_base)
350 with support.temp_cwd() as wrong_dir:
351 # Before calling with the correct cwd, confirm that the call fails
352 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700353 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700354 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700355 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700356 [rel_python], cwd=wrong_dir)
357 python_dir = self._normalize_cwd(python_dir)
358 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
359
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700360 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700361 def test_cwd_with_relative_executable(self):
362 # Check that Popen looks for executable relative to cwd if executable
363 # is relative (and that executable takes precedence over args[0]).
364 python_dir, python_base = self._split_python_path()
365 rel_python = os.path.join(os.curdir, python_base)
366 doesntexist = "somethingyoudonthave"
367 with support.temp_cwd() as wrong_dir:
368 # Before calling with the correct cwd, confirm that the call fails
369 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700370 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700371 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700372 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700373 [doesntexist], executable=rel_python,
374 cwd=wrong_dir)
375 python_dir = self._normalize_cwd(python_dir)
376 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
377 cwd=python_dir)
378
379 def test_cwd_with_absolute_arg(self):
380 # Check that Popen can find the executable when the cwd is wrong
381 # if args[0] is an absolute path.
382 python_dir, python_base = self._split_python_path()
383 abs_python = os.path.join(python_dir, python_base)
384 rel_python = os.path.join(os.curdir, python_base)
Berker Peksagce643912015-05-06 06:33:17 +0300385 with support.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700386 # Before calling with an absolute path, confirm that using a
387 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700388 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700389 [rel_python], cwd=wrong_dir)
390 wrong_dir = self._normalize_cwd(wrong_dir)
391 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
392
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100393 @unittest.skipIf(sys.base_prefix != sys.prefix,
394 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000395 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700396 python_dir, python_base = self._split_python_path()
397 python_dir = self._normalize_cwd(python_dir)
398 self._assert_cwd(python_dir, "somethingyoudonthave",
399 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000400
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100401 @unittest.skipIf(sys.base_prefix != sys.prefix,
402 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000403 @unittest.skipIf(sysconfig.is_python_build(),
404 "need an installed Python. See #7774")
405 def test_executable_without_cwd(self):
406 # For a normal installation, it should work without 'cwd'
407 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700408 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
409 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000410
411 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000412 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000413 p = subprocess.Popen([sys.executable, "-c",
414 'import sys; sys.exit(sys.stdin.read() == "pear")'],
415 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000416 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000417 p.stdin.close()
418 p.wait()
419 self.assertEqual(p.returncode, 1)
420
421 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000422 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000423 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000424 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000425 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000426 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000427 os.lseek(d, 0, 0)
428 p = subprocess.Popen([sys.executable, "-c",
429 'import sys; sys.exit(sys.stdin.read() == "pear")'],
430 stdin=d)
431 p.wait()
432 self.assertEqual(p.returncode, 1)
433
434 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000435 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000436 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000437 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000438 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000439 tf.seek(0)
440 p = subprocess.Popen([sys.executable, "-c",
441 'import sys; sys.exit(sys.stdin.read() == "pear")'],
442 stdin=tf)
443 p.wait()
444 self.assertEqual(p.returncode, 1)
445
446 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000447 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000448 p = subprocess.Popen([sys.executable, "-c",
449 'import sys; sys.stdout.write("orange")'],
450 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200451 with p:
452 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000453
454 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000455 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000456 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000457 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000458 d = tf.fileno()
459 p = subprocess.Popen([sys.executable, "-c",
460 'import sys; sys.stdout.write("orange")'],
461 stdout=d)
462 p.wait()
463 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000464 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000465
466 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000467 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000468 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000469 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000470 p = subprocess.Popen([sys.executable, "-c",
471 'import sys; sys.stdout.write("orange")'],
472 stdout=tf)
473 p.wait()
474 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000475 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000476
477 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000478 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000479 p = subprocess.Popen([sys.executable, "-c",
480 'import sys; sys.stderr.write("strawberry")'],
481 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200482 with p:
483 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000484
485 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000486 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000487 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000488 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000489 d = tf.fileno()
490 p = subprocess.Popen([sys.executable, "-c",
491 'import sys; sys.stderr.write("strawberry")'],
492 stderr=d)
493 p.wait()
494 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000495 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000496
497 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000498 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000499 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000500 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000501 p = subprocess.Popen([sys.executable, "-c",
502 'import sys; sys.stderr.write("strawberry")'],
503 stderr=tf)
504 p.wait()
505 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000506 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000507
Martin Panterc7635892016-05-13 01:54:44 +0000508 def test_stderr_redirect_with_no_stdout_redirect(self):
509 # test stderr=STDOUT while stdout=None (not set)
510
511 # - grandchild prints to stderr
512 # - child redirects grandchild's stderr to its stdout
513 # - the parent should get grandchild's stderr in child's stdout
514 p = subprocess.Popen([sys.executable, "-c",
515 'import sys, subprocess;'
516 'rc = subprocess.call([sys.executable, "-c",'
517 ' "import sys;"'
518 ' "sys.stderr.write(\'42\')"],'
519 ' stderr=subprocess.STDOUT);'
520 'sys.exit(rc)'],
521 stdout=subprocess.PIPE,
522 stderr=subprocess.PIPE)
523 stdout, stderr = p.communicate()
524 #NOTE: stdout should get stderr from grandchild
525 self.assertStderrEqual(stdout, b'42')
526 self.assertStderrEqual(stderr, b'') # should be empty
527 self.assertEqual(p.returncode, 0)
528
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000529 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000530 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000531 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000532 'import sys;'
533 'sys.stdout.write("apple");'
534 'sys.stdout.flush();'
535 'sys.stderr.write("orange")'],
536 stdout=subprocess.PIPE,
537 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200538 with p:
539 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000540
541 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000542 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000543 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000544 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000545 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000546 'import sys;'
547 'sys.stdout.write("apple");'
548 'sys.stdout.flush();'
549 'sys.stderr.write("orange")'],
550 stdout=tf,
551 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000552 p.wait()
553 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000554 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000555
Thomas Wouters89f507f2006-12-13 04:49:30 +0000556 def test_stdout_filedes_of_stdout(self):
557 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200558 # To avoid printing the text on stdout, we do something similar to
559 # test_stdout_none (see above). The parent subprocess calls the child
560 # subprocess passing stdout=1, and this test uses stdout=PIPE in
561 # order to capture and check the output of the parent. See #11963.
562 code = ('import sys, subprocess; '
563 'rc = subprocess.call([sys.executable, "-c", '
564 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
565 'b\'test with stdout=1\'))"], stdout=1); '
566 'assert rc == 18')
567 p = subprocess.Popen([sys.executable, "-c", code],
568 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
569 self.addCleanup(p.stdout.close)
570 self.addCleanup(p.stderr.close)
571 out, err = p.communicate()
572 self.assertEqual(p.returncode, 0, err)
573 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000574
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200575 def test_stdout_devnull(self):
576 p = subprocess.Popen([sys.executable, "-c",
577 'for i in range(10240):'
578 'print("x" * 1024)'],
579 stdout=subprocess.DEVNULL)
580 p.wait()
581 self.assertEqual(p.stdout, None)
582
583 def test_stderr_devnull(self):
584 p = subprocess.Popen([sys.executable, "-c",
585 'import sys\n'
586 'for i in range(10240):'
587 'sys.stderr.write("x" * 1024)'],
588 stderr=subprocess.DEVNULL)
589 p.wait()
590 self.assertEqual(p.stderr, None)
591
592 def test_stdin_devnull(self):
593 p = subprocess.Popen([sys.executable, "-c",
594 'import sys;'
595 'sys.stdin.read(1)'],
596 stdin=subprocess.DEVNULL)
597 p.wait()
598 self.assertEqual(p.stdin, None)
599
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000600 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000601 newenv = os.environ.copy()
602 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200603 with subprocess.Popen([sys.executable, "-c",
604 'import sys,os;'
605 'sys.stdout.write(os.getenv("FRUIT"))'],
606 stdout=subprocess.PIPE,
607 env=newenv) as p:
608 stdout, stderr = p.communicate()
609 self.assertEqual(stdout, b"orange")
610
Victor Stinner62d51182011-06-23 01:02:25 +0200611 # Windows requires at least the SYSTEMROOT environment variable to start
612 # Python
613 @unittest.skipIf(sys.platform == 'win32',
614 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200615 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200616 'the python library cannot be loaded '
617 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200618 def test_empty_env(self):
619 with subprocess.Popen([sys.executable, "-c",
620 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200621 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200622 stdout=subprocess.PIPE,
623 env={}) as p:
624 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200625 self.assertIn(stdout.strip(),
626 (b"[]",
627 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
628 # environment
629 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000630
Peter Astrandcbac93c2005-03-03 20:24:28 +0000631 def test_communicate_stdin(self):
632 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000633 'import sys;'
634 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000635 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000636 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000637 self.assertEqual(p.returncode, 1)
638
639 def test_communicate_stdout(self):
640 p = subprocess.Popen([sys.executable, "-c",
641 'import sys; sys.stdout.write("pineapple")'],
642 stdout=subprocess.PIPE)
643 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000644 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000645 self.assertEqual(stderr, None)
646
647 def test_communicate_stderr(self):
648 p = subprocess.Popen([sys.executable, "-c",
649 'import sys; sys.stderr.write("pineapple")'],
650 stderr=subprocess.PIPE)
651 (stdout, stderr) = p.communicate()
652 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000653 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000654
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000655 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000656 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000657 'import sys,os;'
658 'sys.stderr.write("pineapple");'
659 'sys.stdout.write(sys.stdin.read())'],
660 stdin=subprocess.PIPE,
661 stdout=subprocess.PIPE,
662 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000663 self.addCleanup(p.stdout.close)
664 self.addCleanup(p.stderr.close)
665 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000666 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000667 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000668 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000669
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400670 def test_communicate_timeout(self):
671 p = subprocess.Popen([sys.executable, "-c",
672 'import sys,os,time;'
673 'sys.stderr.write("pineapple\\n");'
674 'time.sleep(1);'
675 'sys.stderr.write("pear\\n");'
676 'sys.stdout.write(sys.stdin.read())'],
677 universal_newlines=True,
678 stdin=subprocess.PIPE,
679 stdout=subprocess.PIPE,
680 stderr=subprocess.PIPE)
681 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
682 timeout=0.3)
683 # Make sure we can keep waiting for it, and that we get the whole output
684 # after it completes.
685 (stdout, stderr) = p.communicate()
686 self.assertEqual(stdout, "banana")
687 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
688
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700689 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200690 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400691 p = subprocess.Popen([sys.executable, "-c",
692 'import sys,os,time;'
693 'sys.stdout.write("a" * (64 * 1024));'
694 'time.sleep(0.2);'
695 'sys.stdout.write("a" * (64 * 1024));'
696 'time.sleep(0.2);'
697 'sys.stdout.write("a" * (64 * 1024));'
698 'time.sleep(0.2);'
699 'sys.stdout.write("a" * (64 * 1024));'],
700 stdout=subprocess.PIPE)
701 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
702 (stdout, _) = p.communicate()
703 self.assertEqual(len(stdout), 4 * 64 * 1024)
704
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000705 # Test for the fd leak reported in http://bugs.python.org/issue2791.
706 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000707 for stdin_pipe in (False, True):
708 for stdout_pipe in (False, True):
709 for stderr_pipe in (False, True):
710 options = {}
711 if stdin_pipe:
712 options['stdin'] = subprocess.PIPE
713 if stdout_pipe:
714 options['stdout'] = subprocess.PIPE
715 if stderr_pipe:
716 options['stderr'] = subprocess.PIPE
717 if not options:
718 continue
719 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
720 p.communicate()
721 if p.stdin is not None:
722 self.assertTrue(p.stdin.closed)
723 if p.stdout is not None:
724 self.assertTrue(p.stdout.closed)
725 if p.stderr is not None:
726 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000727
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000728 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000729 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000730 p = subprocess.Popen([sys.executable, "-c",
731 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000732 (stdout, stderr) = p.communicate()
733 self.assertEqual(stdout, None)
734 self.assertEqual(stderr, None)
735
736 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000737 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000738 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000739 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000740 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000741 os.close(x)
742 os.close(y)
743 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000744 'import sys,os;'
745 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200746 'sys.stderr.write("x" * %d);'
747 'sys.stdout.write(sys.stdin.read())' %
748 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000749 stdin=subprocess.PIPE,
750 stdout=subprocess.PIPE,
751 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000752 self.addCleanup(p.stdout.close)
753 self.addCleanup(p.stderr.close)
754 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200755 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000756 (stdout, stderr) = p.communicate(string_to_write)
757 self.assertEqual(stdout, string_to_write)
758
759 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000760 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000761 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000762 'import sys,os;'
763 'sys.stdout.write(sys.stdin.read())'],
764 stdin=subprocess.PIPE,
765 stdout=subprocess.PIPE,
766 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000767 self.addCleanup(p.stdout.close)
768 self.addCleanup(p.stderr.close)
769 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000770 p.stdin.write(b"banana")
771 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000772 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000773 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000774
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000775 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000776 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000777 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200778 'buf = sys.stdout.buffer;'
779 'buf.write(sys.stdin.readline().encode());'
780 'buf.flush();'
781 'buf.write(b"line2\\n");'
782 'buf.flush();'
783 'buf.write(sys.stdin.read().encode());'
784 'buf.flush();'
785 'buf.write(b"line4\\n");'
786 'buf.flush();'
787 'buf.write(b"line5\\r\\n");'
788 'buf.flush();'
789 'buf.write(b"line6\\r");'
790 'buf.flush();'
791 'buf.write(b"\\nline7");'
792 'buf.flush();'
793 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200794 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000795 stdout=subprocess.PIPE,
796 universal_newlines=1)
Victor Stinner7438c612016-05-20 12:43:15 +0200797 with p:
798 p.stdin.write("line1\n")
799 p.stdin.flush()
800 self.assertEqual(p.stdout.readline(), "line1\n")
801 p.stdin.write("line3\n")
802 p.stdin.close()
803 self.addCleanup(p.stdout.close)
804 self.assertEqual(p.stdout.readline(),
805 "line2\n")
806 self.assertEqual(p.stdout.read(6),
807 "line3\n")
808 self.assertEqual(p.stdout.read(),
809 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000810
811 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000812 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000813 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000814 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200815 'buf = sys.stdout.buffer;'
816 'buf.write(b"line2\\n");'
817 'buf.flush();'
818 'buf.write(b"line4\\n");'
819 'buf.flush();'
820 'buf.write(b"line5\\r\\n");'
821 'buf.flush();'
822 'buf.write(b"line6\\r");'
823 'buf.flush();'
824 'buf.write(b"\\nline7");'
825 'buf.flush();'
826 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200827 stderr=subprocess.PIPE,
828 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000829 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000830 self.addCleanup(p.stdout.close)
831 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000832 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200833 self.assertEqual(stdout,
834 "line2\nline4\nline5\nline6\nline7\nline8")
835
836 def test_universal_newlines_communicate_stdin(self):
837 # universal newlines through communicate(), with only stdin
838 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300839 'import sys,os;' + SETBINARY + textwrap.dedent('''
840 s = sys.stdin.readline()
841 assert s == "line1\\n", repr(s)
842 s = sys.stdin.read()
843 assert s == "line3\\n", repr(s)
844 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200845 stdin=subprocess.PIPE,
846 universal_newlines=1)
847 (stdout, stderr) = p.communicate("line1\nline3\n")
848 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000849
Andrew Svetlovf3765072012-08-14 18:35:17 +0300850 def test_universal_newlines_communicate_input_none(self):
851 # Test communicate(input=None) with universal newlines.
852 #
853 # We set stdout to PIPE because, as of this writing, a different
854 # code path is tested when the number of pipes is zero or one.
855 p = subprocess.Popen([sys.executable, "-c", "pass"],
856 stdin=subprocess.PIPE,
857 stdout=subprocess.PIPE,
858 universal_newlines=True)
859 p.communicate()
860 self.assertEqual(p.returncode, 0)
861
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300862 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300863 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300864 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300865 'import sys,os;' + SETBINARY + textwrap.dedent('''
866 s = sys.stdin.buffer.readline()
867 sys.stdout.buffer.write(s)
868 sys.stdout.buffer.write(b"line2\\r")
869 sys.stderr.buffer.write(b"eline2\\n")
870 s = sys.stdin.buffer.read()
871 sys.stdout.buffer.write(s)
872 sys.stdout.buffer.write(b"line4\\n")
873 sys.stdout.buffer.write(b"line5\\r\\n")
874 sys.stderr.buffer.write(b"eline6\\r")
875 sys.stderr.buffer.write(b"eline7\\r\\nz")
876 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300877 stdin=subprocess.PIPE,
878 stderr=subprocess.PIPE,
879 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300880 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300881 self.addCleanup(p.stdout.close)
882 self.addCleanup(p.stderr.close)
883 (stdout, stderr) = p.communicate("line1\nline3\n")
884 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300885 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300886 # Python debug build push something like "[42442 refs]\n"
887 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300888 # Don't use assertStderrEqual because it strips CR and LF from output.
889 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300890
Andrew Svetlov82860712012-08-19 22:13:41 +0300891 def test_universal_newlines_communicate_encodings(self):
892 # Check that universal newlines mode works for various encodings,
893 # in particular for encodings in the UTF-16 and UTF-32 families.
894 # See issue #15595.
895 #
896 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
897 # without, and UTF-16 and UTF-32.
898 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +0300899 code = ("import sys; "
900 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
901 encoding)
902 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -0700903 # We set stdin to be non-None because, as of this writing,
904 # a different code path is used when the number of pipes is
905 # zero or one.
906 popen = subprocess.Popen(args,
907 stdin=subprocess.PIPE,
908 stdout=subprocess.PIPE,
909 encoding=encoding)
910 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +0300911 self.assertEqual(stdout, '1\n2\n3\n4')
912
Steve Dower050acae2016-09-06 20:16:17 -0700913 def test_communicate_errors(self):
914 for errors, expected in [
915 ('ignore', ''),
916 ('replace', '\ufffd\ufffd'),
917 ('surrogateescape', '\udc80\udc80'),
918 ('backslashreplace', '\\x80\\x80'),
919 ]:
920 code = ("import sys; "
921 r"sys.stdout.buffer.write(b'[\x80\x80]')")
922 args = [sys.executable, '-c', code]
923 # We set stdin to be non-None because, as of this writing,
924 # a different code path is used when the number of pipes is
925 # zero or one.
926 popen = subprocess.Popen(args,
927 stdin=subprocess.PIPE,
928 stdout=subprocess.PIPE,
929 encoding='utf-8',
930 errors=errors)
931 stdout, stderr = popen.communicate(input='')
932 self.assertEqual(stdout, '[{}]'.format(expected))
933
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000934 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000935 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000936 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000937 max_handles = 1026 # too much for most UNIX systems
938 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000939 max_handles = 2050 # too much for (at least some) Windows setups
940 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400941 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000942 try:
943 for i in range(max_handles):
944 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400945 tmpfile = os.path.join(tmpdir, support.TESTFN)
946 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000947 except OSError as e:
948 if e.errno != errno.EMFILE:
949 raise
950 break
951 else:
952 self.skipTest("failed to reach the file descriptor limit "
953 "(tried %d)" % max_handles)
954 # Close a couple of them (should be enough for a subprocess)
955 for i in range(10):
956 os.close(handles.pop())
957 # Loop creating some subprocesses. If one of them leaks some fds,
958 # the next loop iteration will fail by reaching the max fd limit.
959 for i in range(15):
960 p = subprocess.Popen([sys.executable, "-c",
961 "import sys;"
962 "sys.stdout.write(sys.stdin.read())"],
963 stdin=subprocess.PIPE,
964 stdout=subprocess.PIPE,
965 stderr=subprocess.PIPE)
966 data = p.communicate(b"lime")[0]
967 self.assertEqual(data, b"lime")
968 finally:
969 for h in handles:
970 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400971 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000972
973 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000974 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
975 '"a b c" d e')
976 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
977 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000978 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
979 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000980 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
981 'a\\\\\\b "de fg" h')
982 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
983 'a\\\\\\"b c d')
984 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
985 '"a\\\\b c" d e')
986 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
987 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000988 self.assertEqual(subprocess.list2cmdline(['ab', '']),
989 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000990
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000991 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200992 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +0200993 "import os; os.read(0, 1)"],
994 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200995 self.addCleanup(p.stdin.close)
996 self.assertIsNone(p.poll())
997 os.write(p.stdin.fileno(), b'A')
998 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000999 # Subsequent invocations should just return the returncode
1000 self.assertEqual(p.poll(), 0)
1001
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001002 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001003 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001004 self.assertEqual(p.wait(), 0)
1005 # Subsequent invocations should just return the returncode
1006 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001007
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001008 def test_wait_timeout(self):
1009 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001010 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001011 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001012 p.wait(timeout=0.0001)
1013 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -04001014 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
1015 # time to start.
1016 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001017
Gregory P. Smithf0e98c52016-11-20 16:25:14 -08001018 def test_wait_endtime(self):
1019 """Confirm that the deprecated endtime parameter warns."""
1020 p = subprocess.Popen([sys.executable, "-c", "pass"])
1021 try:
1022 with self.assertWarns(DeprecationWarning) as warn_cm:
1023 p.wait(endtime=time.time()+0.01)
1024 except subprocess.TimeoutExpired:
1025 pass # We're not testing endtime timeout behavior.
1026 finally:
1027 p.kill()
1028 self.assertIn('test_subprocess.py', warn_cm.filename)
1029 self.assertIn('endtime', str(warn_cm.warning))
1030
Peter Astrand738131d2004-11-30 21:04:45 +00001031 def test_invalid_bufsize(self):
1032 # an invalid type of the bufsize argument should raise
1033 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001034 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +00001035 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001036
Guido van Rossum46a05a72007-06-07 21:56:45 +00001037 def test_bufsize_is_none(self):
1038 # bufsize=None should be the same as bufsize=0.
1039 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
1040 self.assertEqual(p.wait(), 0)
1041 # Again with keyword arg
1042 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
1043 self.assertEqual(p.wait(), 0)
1044
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001045 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1046 # subprocess may deadlock with bufsize=1, see issue #21332
1047 with subprocess.Popen([sys.executable, "-c", "import sys;"
1048 "sys.stdout.write(sys.stdin.readline());"
1049 "sys.stdout.flush()"],
1050 stdin=subprocess.PIPE,
1051 stdout=subprocess.PIPE,
1052 stderr=subprocess.DEVNULL,
1053 bufsize=1,
1054 universal_newlines=universal_newlines) as p:
1055 p.stdin.write(line) # expect that it flushes the line in text mode
1056 os.close(p.stdin.fileno()) # close it without flushing the buffer
1057 read_line = p.stdout.readline()
1058 try:
1059 p.stdin.close()
1060 except OSError:
1061 pass
1062 p.stdin = None
1063 self.assertEqual(p.returncode, 0)
1064 self.assertEqual(read_line, expected)
1065
1066 def test_bufsize_equal_one_text_mode(self):
1067 # line is flushed in text mode with bufsize=1.
1068 # we should get the full line in return
1069 line = "line\n"
1070 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1071
1072 def test_bufsize_equal_one_binary_mode(self):
1073 # line is not flushed in binary mode with bufsize=1.
1074 # we should get empty response
1075 line = b'line' + os.linesep.encode() # assume ascii-based locale
1076 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
1077
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001078 def test_leaking_fds_on_error(self):
1079 # see bug #5179: Popen leaks file descriptors to PIPEs if
1080 # the child fails to execute; this will eventually exhaust
1081 # the maximum number of open fds. 1024 seems a very common
1082 # value for that limit, but Windows has 2048, so we loop
1083 # 1024 times (each call leaked two fds).
1084 for i in range(1024):
Andrew Svetlov3438fa42012-12-17 23:35:18 +02001085 with self.assertRaises(OSError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001086 subprocess.Popen(['nonexisting_i_hope'],
1087 stdout=subprocess.PIPE,
1088 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -04001089 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -04001090 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001091 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001092
Antoine Pitroua8392712013-08-30 23:38:13 +02001093 @unittest.skipIf(threading is None, "threading required")
1094 def test_double_close_on_error(self):
1095 # Issue #18851
1096 fds = []
1097 def open_fds():
1098 for i in range(20):
1099 fds.extend(os.pipe())
1100 time.sleep(0.001)
1101 t = threading.Thread(target=open_fds)
1102 t.start()
1103 try:
1104 with self.assertRaises(EnvironmentError):
1105 subprocess.Popen(['nonexisting_i_hope'],
1106 stdin=subprocess.PIPE,
1107 stdout=subprocess.PIPE,
1108 stderr=subprocess.PIPE)
1109 finally:
1110 t.join()
1111 exc = None
1112 for fd in fds:
1113 # If a double close occurred, some of those fds will
1114 # already have been closed by mistake, and os.close()
1115 # here will raise.
1116 try:
1117 os.close(fd)
1118 except OSError as e:
1119 exc = e
1120 if exc is not None:
1121 raise exc
1122
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001123 @unittest.skipIf(threading is None, "threading required")
1124 def test_threadsafe_wait(self):
1125 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1126 proc = subprocess.Popen([sys.executable, '-c',
1127 'import time; time.sleep(12)'])
1128 self.assertEqual(proc.returncode, None)
1129 results = []
1130
1131 def kill_proc_timer_thread():
1132 results.append(('thread-start-poll-result', proc.poll()))
1133 # terminate it from the thread and wait for the result.
1134 proc.kill()
1135 proc.wait()
1136 results.append(('thread-after-kill-and-wait', proc.returncode))
1137 # this wait should be a no-op given the above.
1138 proc.wait()
1139 results.append(('thread-after-second-wait', proc.returncode))
1140
1141 # This is a timing sensitive test, the failure mode is
1142 # triggered when both the main thread and this thread are in
1143 # the wait() call at once. The delay here is to allow the
1144 # main thread to most likely be blocked in its wait() call.
1145 t = threading.Timer(0.2, kill_proc_timer_thread)
1146 t.start()
1147
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001148 if mswindows:
1149 expected_errorcode = 1
1150 else:
1151 # Should be -9 because of the proc.kill() from the thread.
1152 expected_errorcode = -9
1153
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001154 # Wait for the process to finish; the thread should kill it
1155 # long before it finishes on its own. Supplying a timeout
1156 # triggers a different code path for better coverage.
1157 proc.wait(timeout=20)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001158 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001159 msg="unexpected result in wait from main thread")
1160
1161 # This should be a no-op with no change in returncode.
1162 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001163 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001164 msg="unexpected result in second main wait.")
1165
1166 t.join()
1167 # Ensure that all of the thread results are as expected.
1168 # When a race condition occurs in wait(), the returncode could
1169 # be set by the wrong thread that doesn't actually have it
1170 # leading to an incorrect value.
1171 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001172 ('thread-after-kill-and-wait', expected_errorcode),
1173 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001174 results)
1175
Victor Stinnerb3693582010-05-21 20:13:12 +00001176 def test_issue8780(self):
1177 # Ensure that stdout is inherited from the parent
1178 # if stdout=PIPE is not used
1179 code = ';'.join((
1180 'import subprocess, sys',
1181 'retcode = subprocess.call('
1182 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1183 'assert retcode == 0'))
1184 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001185 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001186
Tim Goldenaf5ac392010-08-06 13:03:56 +00001187 def test_handles_closed_on_exception(self):
1188 # If CreateProcess exits with an error, ensure the
1189 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001190 ifhandle, ifname = tempfile.mkstemp()
1191 ofhandle, ofname = tempfile.mkstemp()
1192 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001193 try:
1194 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1195 stderr=efhandle)
1196 except OSError:
1197 os.close(ifhandle)
1198 os.remove(ifname)
1199 os.close(ofhandle)
1200 os.remove(ofname)
1201 os.close(efhandle)
1202 os.remove(efname)
1203 self.assertFalse(os.path.exists(ifname))
1204 self.assertFalse(os.path.exists(ofname))
1205 self.assertFalse(os.path.exists(efname))
1206
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001207 def test_communicate_epipe(self):
1208 # Issue 10963: communicate() should hide EPIPE
1209 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1210 stdin=subprocess.PIPE,
1211 stdout=subprocess.PIPE,
1212 stderr=subprocess.PIPE)
1213 self.addCleanup(p.stdout.close)
1214 self.addCleanup(p.stderr.close)
1215 self.addCleanup(p.stdin.close)
1216 p.communicate(b"x" * 2**20)
1217
1218 def test_communicate_epipe_only_stdin(self):
1219 # Issue 10963: communicate() should hide EPIPE
1220 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1221 stdin=subprocess.PIPE)
1222 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001223 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001224 p.communicate(b"x" * 2**20)
1225
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001226 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1227 "Requires signal.SIGUSR1")
1228 @unittest.skipUnless(hasattr(os, 'kill'),
1229 "Requires os.kill")
1230 @unittest.skipUnless(hasattr(os, 'getppid'),
1231 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001232 def test_communicate_eintr(self):
1233 # Issue #12493: communicate() should handle EINTR
1234 def handler(signum, frame):
1235 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001236 old_handler = signal.signal(signal.SIGUSR1, handler)
1237 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001238
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001239 args = [sys.executable, "-c",
1240 'import os, signal;'
1241 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001242 for stream in ('stdout', 'stderr'):
1243 kw = {stream: subprocess.PIPE}
1244 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001245 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001246 process.communicate()
1247
Tim Peterse718f612004-10-12 21:51:32 +00001248
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001249 # This test is Linux-ish specific for simplicity to at least have
1250 # some coverage. It is not a platform specific bug.
1251 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1252 "Linux specific")
1253 def test_failed_child_execute_fd_leak(self):
1254 """Test for the fork() failure fd leak reported in issue16327."""
1255 fd_directory = '/proc/%d/fd' % os.getpid()
1256 fds_before_popen = os.listdir(fd_directory)
1257 with self.assertRaises(PopenTestException):
1258 PopenExecuteChildRaises(
1259 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
1260 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1261
1262 # NOTE: This test doesn't verify that the real _execute_child
1263 # does not close the file descriptors itself on the way out
1264 # during an exception. Code inspection has confirmed that.
1265
1266 fds_after_exception = os.listdir(fd_directory)
1267 self.assertEqual(fds_before_popen, fds_after_exception)
1268
Gregory P. Smith6e730002015-04-14 16:14:25 -07001269
1270class RunFuncTestCase(BaseTestCase):
1271 def run_python(self, code, **kwargs):
1272 """Run Python code in a subprocess using subprocess.run"""
1273 argv = [sys.executable, "-c", code]
1274 return subprocess.run(argv, **kwargs)
1275
1276 def test_returncode(self):
1277 # call() function with sequence argument
1278 cp = self.run_python("import sys; sys.exit(47)")
1279 self.assertEqual(cp.returncode, 47)
1280 with self.assertRaises(subprocess.CalledProcessError):
1281 cp.check_returncode()
1282
1283 def test_check(self):
1284 with self.assertRaises(subprocess.CalledProcessError) as c:
1285 self.run_python("import sys; sys.exit(47)", check=True)
1286 self.assertEqual(c.exception.returncode, 47)
1287
1288 def test_check_zero(self):
1289 # check_returncode shouldn't raise when returncode is zero
1290 cp = self.run_python("import sys; sys.exit(0)", check=True)
1291 self.assertEqual(cp.returncode, 0)
1292
1293 def test_timeout(self):
1294 # run() function with timeout argument; we want to test that the child
1295 # process gets killed when the timeout expires. If the child isn't
1296 # killed, this call will deadlock since subprocess.run waits for the
1297 # child.
1298 with self.assertRaises(subprocess.TimeoutExpired):
1299 self.run_python("while True: pass", timeout=0.0001)
1300
1301 def test_capture_stdout(self):
1302 # capture stdout with zero return code
1303 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1304 self.assertIn(b'BDFL', cp.stdout)
1305
1306 def test_capture_stderr(self):
1307 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1308 stderr=subprocess.PIPE)
1309 self.assertIn(b'BDFL', cp.stderr)
1310
1311 def test_check_output_stdin_arg(self):
1312 # run() can be called with stdin set to a file
1313 tf = tempfile.TemporaryFile()
1314 self.addCleanup(tf.close)
1315 tf.write(b'pear')
1316 tf.seek(0)
1317 cp = self.run_python(
1318 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1319 stdin=tf, stdout=subprocess.PIPE)
1320 self.assertIn(b'PEAR', cp.stdout)
1321
1322 def test_check_output_input_arg(self):
1323 # check_output() can be called with input set to a string
1324 cp = self.run_python(
1325 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1326 input=b'pear', stdout=subprocess.PIPE)
1327 self.assertIn(b'PEAR', cp.stdout)
1328
1329 def test_check_output_stdin_with_input_arg(self):
1330 # run() refuses to accept 'stdin' with 'input'
1331 tf = tempfile.TemporaryFile()
1332 self.addCleanup(tf.close)
1333 tf.write(b'pear')
1334 tf.seek(0)
1335 with self.assertRaises(ValueError,
1336 msg="Expected ValueError when stdin and input args supplied.") as c:
1337 output = self.run_python("print('will not be run')",
1338 stdin=tf, input=b'hare')
1339 self.assertIn('stdin', c.exception.args[0])
1340 self.assertIn('input', c.exception.args[0])
1341
1342 def test_check_output_timeout(self):
1343 with self.assertRaises(subprocess.TimeoutExpired) as c:
1344 cp = self.run_python((
1345 "import sys, time\n"
1346 "sys.stdout.write('BDFL')\n"
1347 "sys.stdout.flush()\n"
1348 "time.sleep(3600)"),
1349 # Some heavily loaded buildbots (sparc Debian 3.x) require
1350 # this much time to start and print.
1351 timeout=3, stdout=subprocess.PIPE)
1352 self.assertEqual(c.exception.output, b'BDFL')
1353 # output is aliased to stdout
1354 self.assertEqual(c.exception.stdout, b'BDFL')
1355
1356 def test_run_kwargs(self):
1357 newenv = os.environ.copy()
1358 newenv["FRUIT"] = "banana"
1359 cp = self.run_python(('import sys, os;'
1360 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1361 env=newenv)
1362 self.assertEqual(cp.returncode, 33)
1363
1364
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001365@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001366class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001367
Gregory P. Smith5591b022012-10-10 03:34:47 -07001368 def setUp(self):
1369 super().setUp()
1370 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1371
1372 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001373 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001374 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001375 except OSError as e:
1376 # This avoids hard coding the errno value or the OS perror()
1377 # string and instead capture the exception that we want to see
1378 # below for comparison.
1379 desired_exception = e
Gregory P. Smith5591b022012-10-10 03:34:47 -07001380 desired_exception.strerror += ': ' + repr(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001381 else:
Martin Pantereb995702016-07-28 01:11:04 +00001382 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001383 self._nonexistent_dir)
1384 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001385
Gregory P. Smith5591b022012-10-10 03:34:47 -07001386 def test_exception_cwd(self):
1387 """Test error in the child raised in the parent for a bad cwd."""
1388 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001389 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001390 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001391 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001392 except OSError as e:
1393 # Test that the child process chdir failure actually makes
1394 # it up to the parent process as the correct exception.
1395 self.assertEqual(desired_exception.errno, e.errno)
1396 self.assertEqual(desired_exception.strerror, e.strerror)
1397 else:
1398 self.fail("Expected OSError: %s" % desired_exception)
1399
Gregory P. Smith5591b022012-10-10 03:34:47 -07001400 def test_exception_bad_executable(self):
1401 """Test error in the child raised in the parent for a bad executable."""
1402 desired_exception = self._get_chdir_exception()
1403 try:
1404 p = subprocess.Popen([sys.executable, "-c", ""],
1405 executable=self._nonexistent_dir)
1406 except OSError as e:
1407 # Test that the child process exec failure actually makes
1408 # it up to the parent process as the correct exception.
1409 self.assertEqual(desired_exception.errno, e.errno)
1410 self.assertEqual(desired_exception.strerror, e.strerror)
1411 else:
1412 self.fail("Expected OSError: %s" % desired_exception)
1413
1414 def test_exception_bad_args_0(self):
1415 """Test error in the child raised in the parent for a bad args[0]."""
1416 desired_exception = self._get_chdir_exception()
1417 try:
1418 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1419 except OSError as e:
1420 # Test that the child process exec failure actually makes
1421 # it up to the parent process as the correct exception.
1422 self.assertEqual(desired_exception.errno, e.errno)
1423 self.assertEqual(desired_exception.strerror, e.strerror)
1424 else:
1425 self.fail("Expected OSError: %s" % desired_exception)
1426
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001427 def test_restore_signals(self):
1428 # Code coverage for both values of restore_signals to make sure it
1429 # at least does not blow up.
1430 # A test for behavior would be complex. Contributions welcome.
1431 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1432 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1433
1434 def test_start_new_session(self):
1435 # For code coverage of calling setsid(). We don't care if we get an
1436 # EPERM error from it depending on the test execution environment, that
1437 # still indicates that it was called.
1438 try:
1439 output = subprocess.check_output(
1440 [sys.executable, "-c",
1441 "import os; print(os.getpgid(os.getpid()))"],
1442 start_new_session=True)
1443 except OSError as e:
1444 if e.errno != errno.EPERM:
1445 raise
1446 else:
1447 parent_pgid = os.getpgid(os.getpid())
1448 child_pgid = int(output)
1449 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001450
1451 def test_run_abort(self):
1452 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001453 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001454 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001455 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001456 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001457 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001458
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001459 def test_CalledProcessError_str_signal(self):
1460 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
1461 error_string = str(err)
1462 # We're relying on the repr() of the signal.Signals intenum to provide
1463 # the word signal, the signal name and the numeric value.
1464 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00001465 # We're not being specific about the signal name as some signals have
1466 # multiple names and which name is revealed can vary.
1467 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001468 self.assertIn(str(signal.SIGABRT), error_string)
1469
1470 def test_CalledProcessError_str_unknown_signal(self):
1471 err = subprocess.CalledProcessError(-9876543, "fake cmd")
1472 error_string = str(err)
1473 self.assertIn("unknown signal 9876543.", error_string)
1474
1475 def test_CalledProcessError_str_non_zero(self):
1476 err = subprocess.CalledProcessError(2, "fake cmd")
1477 error_string = str(err)
1478 self.assertIn("non-zero exit status 2.", error_string)
1479
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001480 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001481 # DISCLAIMER: Setting environment variables is *not* a good use
1482 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001483 p = subprocess.Popen([sys.executable, "-c",
1484 'import sys,os;'
1485 'sys.stdout.write(os.getenv("FRUIT"))'],
1486 stdout=subprocess.PIPE,
1487 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02001488 with p:
1489 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001490
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001491 def test_preexec_exception(self):
1492 def raise_it():
1493 raise ValueError("What if two swallows carried a coconut?")
1494 try:
1495 p = subprocess.Popen([sys.executable, "-c", ""],
1496 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001497 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001498 self.assertTrue(
1499 subprocess._posixsubprocess,
1500 "Expected a ValueError from the preexec_fn")
1501 except ValueError as e:
1502 self.assertIn("coconut", e.args[0])
1503 else:
1504 self.fail("Exception raised by preexec_fn did not make it "
1505 "to the parent process.")
1506
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001507 class _TestExecuteChildPopen(subprocess.Popen):
1508 """Used to test behavior at the end of _execute_child."""
1509 def __init__(self, testcase, *args, **kwargs):
1510 self._testcase = testcase
1511 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001512
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001513 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001514 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001515 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001516 finally:
1517 # Open a bunch of file descriptors and verify that
1518 # none of them are the same as the ones the Popen
1519 # instance is using for stdin/stdout/stderr.
1520 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1521 for _ in range(8)]
1522 try:
1523 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001524 self._testcase.assertNotIn(
1525 fd, (self.stdin.fileno(), self.stdout.fileno(),
1526 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001527 msg="At least one fd was closed early.")
1528 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01001529 for fd in devzero_fds:
1530 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001531
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001532 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1533 def test_preexec_errpipe_does_not_double_close_pipes(self):
1534 """Issue16140: Don't double close pipes on preexec error."""
1535
1536 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08001537 raise subprocess.SubprocessError(
1538 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001539
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08001540 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001541 self._TestExecuteChildPopen(
1542 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001543 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1544 stderr=subprocess.PIPE, preexec_fn=raise_it)
1545
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001546 def test_preexec_gc_module_failure(self):
1547 # This tests the code that disables garbage collection if the child
1548 # process will execute any Python.
1549 def raise_runtime_error():
1550 raise RuntimeError("this shouldn't escape")
1551 enabled = gc.isenabled()
1552 orig_gc_disable = gc.disable
1553 orig_gc_isenabled = gc.isenabled
1554 try:
1555 gc.disable()
1556 self.assertFalse(gc.isenabled())
1557 subprocess.call([sys.executable, '-c', ''],
1558 preexec_fn=lambda: None)
1559 self.assertFalse(gc.isenabled(),
1560 "Popen enabled gc when it shouldn't.")
1561
1562 gc.enable()
1563 self.assertTrue(gc.isenabled())
1564 subprocess.call([sys.executable, '-c', ''],
1565 preexec_fn=lambda: None)
1566 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1567
1568 gc.disable = raise_runtime_error
1569 self.assertRaises(RuntimeError, subprocess.Popen,
1570 [sys.executable, '-c', ''],
1571 preexec_fn=lambda: None)
1572
1573 del gc.isenabled # force an AttributeError
1574 self.assertRaises(AttributeError, subprocess.Popen,
1575 [sys.executable, '-c', ''],
1576 preexec_fn=lambda: None)
1577 finally:
1578 gc.disable = orig_gc_disable
1579 gc.isenabled = orig_gc_isenabled
1580 if not enabled:
1581 gc.disable()
1582
Martin Panterf7fdbda2015-12-05 09:51:52 +00001583 @unittest.skipIf(
1584 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00001585 def test_preexec_fork_failure(self):
1586 # The internal code did not preserve the previous exception when
1587 # re-enabling garbage collection
1588 try:
1589 from resource import getrlimit, setrlimit, RLIMIT_NPROC
1590 except ImportError as err:
1591 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
1592 limits = getrlimit(RLIMIT_NPROC)
1593 [_, hard] = limits
1594 setrlimit(RLIMIT_NPROC, (0, hard))
1595 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00001596 try:
Martin Panterafdd5132015-11-30 02:21:41 +00001597 subprocess.call([sys.executable, '-c', ''],
1598 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00001599 except BlockingIOError:
1600 # Forking should raise EAGAIN, translated to BlockingIOError
1601 pass
1602 else:
1603 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00001604
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001605 def test_args_string(self):
1606 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03001607 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001608 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001609 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001610 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001611 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1612 sys.executable)
1613 os.chmod(fname, 0o700)
1614 p = subprocess.Popen(fname)
1615 p.wait()
1616 os.remove(fname)
1617 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001618
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001619 def test_invalid_args(self):
1620 # invalid arguments should raise ValueError
1621 self.assertRaises(ValueError, subprocess.call,
1622 [sys.executable, "-c",
1623 "import sys; sys.exit(47)"],
1624 startupinfo=47)
1625 self.assertRaises(ValueError, subprocess.call,
1626 [sys.executable, "-c",
1627 "import sys; sys.exit(47)"],
1628 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001629
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001630 def test_shell_sequence(self):
1631 # Run command through the shell (sequence)
1632 newenv = os.environ.copy()
1633 newenv["FRUIT"] = "apple"
1634 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1635 stdout=subprocess.PIPE,
1636 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001637 with p:
1638 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001639
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001640 def test_shell_string(self):
1641 # Run command through the shell (string)
1642 newenv = os.environ.copy()
1643 newenv["FRUIT"] = "apple"
1644 p = subprocess.Popen("echo $FRUIT", shell=1,
1645 stdout=subprocess.PIPE,
1646 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001647 with p:
1648 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001649
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001650 def test_call_string(self):
1651 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03001652 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001653 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001654 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001655 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001656 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1657 sys.executable)
1658 os.chmod(fname, 0o700)
1659 rc = subprocess.call(fname)
1660 os.remove(fname)
1661 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001662
Stefan Krah9542cc62010-07-19 14:20:53 +00001663 def test_specific_shell(self):
1664 # Issue #9265: Incorrect name passed as arg[0].
1665 shells = []
1666 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1667 for name in ['bash', 'ksh']:
1668 sh = os.path.join(prefix, name)
1669 if os.path.isfile(sh):
1670 shells.append(sh)
1671 if not shells: # Will probably work for any shell but csh.
1672 self.skipTest("bash or ksh required for this test")
1673 sh = '/bin/sh'
1674 if os.path.isfile(sh) and not os.path.islink(sh):
1675 # Test will fail if /bin/sh is a symlink to csh.
1676 shells.append(sh)
1677 for sh in shells:
1678 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1679 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02001680 with p:
1681 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00001682
Florent Xicluna4886d242010-03-08 13:27:26 +00001683 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001684 # Do not inherit file handles from the parent.
1685 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07001686 # Also set the SIGINT handler to the default to make sure it's not
1687 # being ignored (some tests rely on that.)
1688 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
1689 try:
1690 p = subprocess.Popen([sys.executable, "-c", """if 1:
1691 import sys, time
1692 sys.stdout.write('x\\n')
1693 sys.stdout.flush()
1694 time.sleep(30)
1695 """],
1696 close_fds=True,
1697 stdin=subprocess.PIPE,
1698 stdout=subprocess.PIPE,
1699 stderr=subprocess.PIPE)
1700 finally:
1701 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001702 # Wait for the interpreter to be completely initialized before
1703 # sending any signal.
1704 p.stdout.read(1)
1705 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001706 return p
1707
Charles-François Natali53221e32013-01-12 16:52:20 +01001708 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1709 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001710 def _kill_dead_process(self, method, *args):
1711 # Do not inherit file handles from the parent.
1712 # It should fix failures on some platforms.
1713 p = subprocess.Popen([sys.executable, "-c", """if 1:
1714 import sys, time
1715 sys.stdout.write('x\\n')
1716 sys.stdout.flush()
1717 """],
1718 close_fds=True,
1719 stdin=subprocess.PIPE,
1720 stdout=subprocess.PIPE,
1721 stderr=subprocess.PIPE)
1722 # Wait for the interpreter to be completely initialized before
1723 # sending any signal.
1724 p.stdout.read(1)
1725 # The process should end after this
1726 time.sleep(1)
1727 # This shouldn't raise even though the child is now dead
1728 getattr(p, method)(*args)
1729 p.communicate()
1730
Florent Xicluna4886d242010-03-08 13:27:26 +00001731 def test_send_signal(self):
1732 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001733 _, stderr = p.communicate()
1734 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001735 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001736
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001737 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001738 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001739 _, stderr = p.communicate()
1740 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001741 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001742
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001743 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001744 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001745 _, stderr = p.communicate()
1746 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001747 self.assertEqual(p.wait(), -signal.SIGTERM)
1748
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001749 def test_send_signal_dead(self):
1750 # Sending a signal to a dead process
1751 self._kill_dead_process('send_signal', signal.SIGINT)
1752
1753 def test_kill_dead(self):
1754 # Killing a dead process
1755 self._kill_dead_process('kill')
1756
1757 def test_terminate_dead(self):
1758 # Terminating a dead process
1759 self._kill_dead_process('terminate')
1760
Victor Stinnerdaf45552013-08-28 00:53:59 +02001761 def _save_fds(self, save_fds):
1762 fds = []
1763 for fd in save_fds:
1764 inheritable = os.get_inheritable(fd)
1765 saved = os.dup(fd)
1766 fds.append((fd, saved, inheritable))
1767 return fds
1768
1769 def _restore_fds(self, fds):
1770 for fd, saved, inheritable in fds:
1771 os.dup2(saved, fd, inheritable=inheritable)
1772 os.close(saved)
1773
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001774 def check_close_std_fds(self, fds):
1775 # Issue #9905: test that subprocess pipes still work properly with
1776 # some standard fds closed
1777 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02001778 saved_fds = self._save_fds(fds)
1779 for fd, saved, inheritable in saved_fds:
1780 if fd == 0:
1781 stdin = saved
1782 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001783 try:
1784 for fd in fds:
1785 os.close(fd)
1786 out, err = subprocess.Popen([sys.executable, "-c",
1787 'import sys;'
1788 'sys.stdout.write("apple");'
1789 'sys.stdout.flush();'
1790 'sys.stderr.write("orange")'],
1791 stdin=stdin,
1792 stdout=subprocess.PIPE,
1793 stderr=subprocess.PIPE).communicate()
1794 err = support.strip_python_stderr(err)
1795 self.assertEqual((out, err), (b'apple', b'orange'))
1796 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001797 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001798
1799 def test_close_fd_0(self):
1800 self.check_close_std_fds([0])
1801
1802 def test_close_fd_1(self):
1803 self.check_close_std_fds([1])
1804
1805 def test_close_fd_2(self):
1806 self.check_close_std_fds([2])
1807
1808 def test_close_fds_0_1(self):
1809 self.check_close_std_fds([0, 1])
1810
1811 def test_close_fds_0_2(self):
1812 self.check_close_std_fds([0, 2])
1813
1814 def test_close_fds_1_2(self):
1815 self.check_close_std_fds([1, 2])
1816
1817 def test_close_fds_0_1_2(self):
1818 # Issue #10806: test that subprocess pipes still work properly with
1819 # all standard fds closed.
1820 self.check_close_std_fds([0, 1, 2])
1821
Gregory P. Smith53dd8162013-12-01 16:03:24 -08001822 def test_small_errpipe_write_fd(self):
1823 """Issue #15798: Popen should work when stdio fds are available."""
1824 new_stdin = os.dup(0)
1825 new_stdout = os.dup(1)
1826 try:
1827 os.close(0)
1828 os.close(1)
1829
1830 # Side test: if errpipe_write fails to have its CLOEXEC
1831 # flag set this should cause the parent to think the exec
1832 # failed. Extremely unlikely: everyone supports CLOEXEC.
1833 subprocess.Popen([
1834 sys.executable, "-c",
1835 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
1836 finally:
1837 # Restore original stdin and stdout
1838 os.dup2(new_stdin, 0)
1839 os.dup2(new_stdout, 1)
1840 os.close(new_stdin)
1841 os.close(new_stdout)
1842
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001843 def test_remapping_std_fds(self):
1844 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03001845 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001846 try:
1847 temp_fds = [fd for fd, fname in temps]
1848
1849 # unlink the files -- we won't need to reopen them
1850 for fd, fname in temps:
1851 os.unlink(fname)
1852
1853 # write some data to what will become stdin, and rewind
1854 os.write(temp_fds[1], b"STDIN")
1855 os.lseek(temp_fds[1], 0, 0)
1856
1857 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02001858 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001859 try:
1860 # duplicate the file objects over the standard fd's
1861 for fd, temp_fd in enumerate(temp_fds):
1862 os.dup2(temp_fd, fd)
1863
1864 # now use those files in the "wrong" order, so that subprocess
1865 # has to rearrange them in the child
1866 p = subprocess.Popen([sys.executable, "-c",
1867 'import sys; got = sys.stdin.read();'
1868 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1869 stdin=temp_fds[1],
1870 stdout=temp_fds[2],
1871 stderr=temp_fds[0])
1872 p.wait()
1873 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001874 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001875
1876 for fd in temp_fds:
1877 os.lseek(fd, 0, 0)
1878
1879 out = os.read(temp_fds[2], 1024)
1880 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1881 self.assertEqual(out, b"got STDIN")
1882 self.assertEqual(err, b"err")
1883
1884 finally:
1885 for fd in temp_fds:
1886 os.close(fd)
1887
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001888 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1889 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03001890 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001891 temp_fds = [fd for fd, fname in temps]
1892 try:
1893 # unlink the files -- we won't need to reopen them
1894 for fd, fname in temps:
1895 os.unlink(fname)
1896
1897 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02001898 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001899 try:
1900 # duplicate the temp files over the standard fd's 0, 1, 2
1901 for fd, temp_fd in enumerate(temp_fds):
1902 os.dup2(temp_fd, fd)
1903
1904 # write some data to what will become stdin, and rewind
1905 os.write(stdin_no, b"STDIN")
1906 os.lseek(stdin_no, 0, 0)
1907
1908 # now use those files in the given order, so that subprocess
1909 # has to rearrange them in the child
1910 p = subprocess.Popen([sys.executable, "-c",
1911 'import sys; got = sys.stdin.read();'
1912 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1913 stdin=stdin_no,
1914 stdout=stdout_no,
1915 stderr=stderr_no)
1916 p.wait()
1917
1918 for fd in temp_fds:
1919 os.lseek(fd, 0, 0)
1920
1921 out = os.read(stdout_no, 1024)
1922 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1923 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001924 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001925
1926 self.assertEqual(out, b"got STDIN")
1927 self.assertEqual(err, b"err")
1928
1929 finally:
1930 for fd in temp_fds:
1931 os.close(fd)
1932
1933 # When duping fds, if there arises a situation where one of the fds is
1934 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1935 # This tests all combinations of this.
1936 def test_swap_fds(self):
1937 self.check_swap_fds(0, 1, 2)
1938 self.check_swap_fds(0, 2, 1)
1939 self.check_swap_fds(1, 0, 2)
1940 self.check_swap_fds(1, 2, 0)
1941 self.check_swap_fds(2, 0, 1)
1942 self.check_swap_fds(2, 1, 0)
1943
Victor Stinner13bb71c2010-04-23 21:41:56 +00001944 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001945 def prepare():
1946 raise ValueError("surrogate:\uDCff")
1947
1948 try:
1949 subprocess.call(
1950 [sys.executable, "-c", "pass"],
1951 preexec_fn=prepare)
1952 except ValueError as err:
1953 # Pure Python implementations keeps the message
1954 self.assertIsNone(subprocess._posixsubprocess)
1955 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001956 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00001957 # _posixsubprocess uses a default message
1958 self.assertIsNotNone(subprocess._posixsubprocess)
1959 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1960 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001961 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00001962
Victor Stinner13bb71c2010-04-23 21:41:56 +00001963 def test_undecodable_env(self):
1964 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01001965 encoded_value = value.encode("ascii", "surrogateescape")
1966
Victor Stinner13bb71c2010-04-23 21:41:56 +00001967 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001968 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001969 env = os.environ.copy()
1970 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01001971 # Use C locale to get ASCII for the locale encoding to force
Victor Stinner89f3ad12010-10-14 10:43:31 +00001972 # surrogate-escaping of \xFF in the child process; otherwise it can
1973 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001974 env['LC_ALL'] = 'C'
Victor Stinner5323fb02013-11-19 23:46:06 +01001975 if sys.platform.startswith("aix"):
1976 # On AIX, the C locale uses the Latin1 encoding
1977 decoded_value = encoded_value.decode("latin1", "surrogateescape")
1978 else:
1979 # On other UNIXes, the C locale uses the ASCII encoding
1980 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001981 stdout = subprocess.check_output(
1982 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001983 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001984 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01001985 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001986
1987 # test bytes
1988 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001989 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001990 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01001991 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001992 stdout = subprocess.check_output(
1993 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001994 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001995 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01001996 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001997
Victor Stinnerb745a742010-05-18 17:17:23 +00001998 def test_bytes_program(self):
1999 abs_program = os.fsencode(sys.executable)
2000 path, program = os.path.split(sys.executable)
2001 program = os.fsencode(program)
2002
2003 # absolute bytes path
2004 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00002005 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002006
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002007 # absolute bytes path as a string
2008 cmd = b"'" + abs_program + b"' -c pass"
2009 exitcode = subprocess.call(cmd, shell=True)
2010 self.assertEqual(exitcode, 0)
2011
Victor Stinnerb745a742010-05-18 17:17:23 +00002012 # bytes program, unicode PATH
2013 env = os.environ.copy()
2014 env["PATH"] = path
2015 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002016 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002017
2018 # bytes program, bytes PATH
2019 envb = os.environb.copy()
2020 envb[b"PATH"] = os.fsencode(path)
2021 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002022 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002023
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002024 def test_pipe_cloexec(self):
2025 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2026 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2027
2028 p1 = subprocess.Popen([sys.executable, sleeper],
2029 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2030 stderr=subprocess.PIPE, close_fds=False)
2031
2032 self.addCleanup(p1.communicate, b'')
2033
2034 p2 = subprocess.Popen([sys.executable, fd_status],
2035 stdout=subprocess.PIPE, close_fds=False)
2036
2037 output, error = p2.communicate()
2038 result_fds = set(map(int, output.split(b',')))
2039 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2040 p1.stderr.fileno()])
2041
2042 self.assertFalse(result_fds & unwanted_fds,
2043 "Expected no fds from %r to be open in child, "
2044 "found %r" %
2045 (unwanted_fds, result_fds & unwanted_fds))
2046
2047 def test_pipe_cloexec_real_tools(self):
2048 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2049 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2050
2051 subdata = b'zxcvbn'
2052 data = subdata * 4 + b'\n'
2053
2054 p1 = subprocess.Popen([sys.executable, qcat],
2055 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2056 close_fds=False)
2057
2058 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2059 stdin=p1.stdout, stdout=subprocess.PIPE,
2060 close_fds=False)
2061
2062 self.addCleanup(p1.wait)
2063 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002064 def kill_p1():
2065 try:
2066 p1.terminate()
2067 except ProcessLookupError:
2068 pass
2069 def kill_p2():
2070 try:
2071 p2.terminate()
2072 except ProcessLookupError:
2073 pass
2074 self.addCleanup(kill_p1)
2075 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002076
2077 p1.stdin.write(data)
2078 p1.stdin.close()
2079
2080 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2081
2082 self.assertTrue(readfiles, "The child hung")
2083 self.assertEqual(p2.stdout.read(), data)
2084
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002085 p1.stdout.close()
2086 p2.stdout.close()
2087
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002088 def test_close_fds(self):
2089 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2090
2091 fds = os.pipe()
2092 self.addCleanup(os.close, fds[0])
2093 self.addCleanup(os.close, fds[1])
2094
2095 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002096 # add a bunch more fds
2097 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002098 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002099 self.addCleanup(os.close, fd)
2100 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002101
Victor Stinnerdaf45552013-08-28 00:53:59 +02002102 for fd in open_fds:
2103 os.set_inheritable(fd, True)
2104
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002105 p = subprocess.Popen([sys.executable, fd_status],
2106 stdout=subprocess.PIPE, close_fds=False)
2107 output, ignored = p.communicate()
2108 remaining_fds = set(map(int, output.split(b',')))
2109
2110 self.assertEqual(remaining_fds & open_fds, open_fds,
2111 "Some fds were closed")
2112
2113 p = subprocess.Popen([sys.executable, fd_status],
2114 stdout=subprocess.PIPE, close_fds=True)
2115 output, ignored = p.communicate()
2116 remaining_fds = set(map(int, output.split(b',')))
2117
2118 self.assertFalse(remaining_fds & open_fds,
2119 "Some fds were left open")
2120 self.assertIn(1, remaining_fds, "Subprocess failed")
2121
Gregory P. Smith8facece2012-01-21 14:01:08 -08002122 # Keep some of the fd's we opened open in the subprocess.
2123 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2124 fds_to_keep = set(open_fds.pop() for _ in range(8))
2125 p = subprocess.Popen([sys.executable, fd_status],
2126 stdout=subprocess.PIPE, close_fds=True,
2127 pass_fds=())
2128 output, ignored = p.communicate()
2129 remaining_fds = set(map(int, output.split(b',')))
2130
2131 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
2132 "Some fds not in pass_fds were left open")
2133 self.assertIn(1, remaining_fds, "Subprocess failed")
2134
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002135
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002136 @unittest.skipIf(sys.platform.startswith("freebsd") and
2137 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2138 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002139 def test_close_fds_when_max_fd_is_lowered(self):
2140 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2141 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2142
Gregory P. Smith634aa682014-06-15 17:51:04 -07002143 # This launches the meat of the test in a child process to
2144 # avoid messing with the larger unittest processes maximum
2145 # number of file descriptors.
2146 # This process launches:
2147 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2148 # a bunch of high open fds above the new lower rlimit.
2149 # Those are reported via stdout before launching a new
2150 # process with close_fds=False to run the actual test:
2151 # +--> The TEST: This one launches a fd_status.py
2152 # subprocess with close_fds=True so we can find out if
2153 # any of the fds above the lowered rlimit are still open.
2154 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2155 '''
2156 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002157 open_fds = set()
2158 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002159 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002160 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002161 open_fds.add(fd)
2162
2163 # Leave a two pairs of low ones available for use by the
2164 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002165 # We also leave 10 more open as some Python buildbots run into
2166 # "too many open files" errors during the test if we do not.
2167 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002168 os.close(fd)
2169 open_fds.remove(fd)
2170
2171 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002172 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002173 os.set_inheritable(fd, True)
2174
2175 max_fd_open = max(open_fds)
2176
Gregory P. Smith634aa682014-06-15 17:51:04 -07002177 # Communicate the open_fds to the parent unittest.TestCase process.
2178 print(','.join(map(str, sorted(open_fds))))
2179 sys.stdout.flush()
2180
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002181 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2182 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002183 # 29 is lower than the highest fds we are leaving open.
2184 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002185 # Launch a new Python interpreter with our low fd rlim_cur that
2186 # inherits open fds above that limit. It then uses subprocess
2187 # with close_fds=True to get a report of open fds in the child.
2188 # An explicit list of fds to check is passed to fd_status.py as
2189 # letting fd_status rely on its default logic would miss the
2190 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002191 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002192 [sys.executable, '-c',
2193 textwrap.dedent("""
2194 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002195 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002196 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002197 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002198 """.format(max_fd=max_fd_open+1))],
2199 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002200 finally:
2201 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002202 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002203
2204 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002205 output_lines = output.splitlines()
2206 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002207 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002208 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2209 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002210
Gregory P. Smith634aa682014-06-15 17:51:04 -07002211 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002212 msg="Some fds were left open.")
2213
2214
Victor Stinner88701e22011-06-01 13:13:04 +02002215 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2216 # descriptor of a pipe closed in the parent process is valid in the
2217 # child process according to fstat(), but the mode of the file
2218 # descriptor is invalid, and read or write raise an error.
2219 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002220 def test_pass_fds(self):
2221 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2222
2223 open_fds = set()
2224
2225 for x in range(5):
2226 fds = os.pipe()
2227 self.addCleanup(os.close, fds[0])
2228 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002229 os.set_inheritable(fds[0], True)
2230 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002231 open_fds.update(fds)
2232
2233 for fd in open_fds:
2234 p = subprocess.Popen([sys.executable, fd_status],
2235 stdout=subprocess.PIPE, close_fds=True,
2236 pass_fds=(fd, ))
2237 output, ignored = p.communicate()
2238
2239 remaining_fds = set(map(int, output.split(b',')))
2240 to_be_closed = open_fds - {fd}
2241
2242 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2243 self.assertFalse(remaining_fds & to_be_closed,
2244 "fd to be closed passed")
2245
2246 # pass_fds overrides close_fds with a warning.
2247 with self.assertWarns(RuntimeWarning) as context:
2248 self.assertFalse(subprocess.call(
2249 [sys.executable, "-c", "import sys; sys.exit(0)"],
2250 close_fds=False, pass_fds=(fd, )))
2251 self.assertIn('overriding close_fds', str(context.warning))
2252
Victor Stinnerdaf45552013-08-28 00:53:59 +02002253 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002254 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002255
2256 inheritable, non_inheritable = os.pipe()
2257 self.addCleanup(os.close, inheritable)
2258 self.addCleanup(os.close, non_inheritable)
2259 os.set_inheritable(inheritable, True)
2260 os.set_inheritable(non_inheritable, False)
2261 pass_fds = (inheritable, non_inheritable)
2262 args = [sys.executable, script]
2263 args += list(map(str, pass_fds))
2264
2265 p = subprocess.Popen(args,
2266 stdout=subprocess.PIPE, close_fds=True,
2267 pass_fds=pass_fds)
2268 output, ignored = p.communicate()
2269 fds = set(map(int, output.split(b',')))
2270
2271 # the inheritable file descriptor must be inherited, so its inheritable
2272 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002273 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002274
2275 # inheritable flag must not be changed in the parent process
2276 self.assertEqual(os.get_inheritable(inheritable), True)
2277 self.assertEqual(os.get_inheritable(non_inheritable), False)
2278
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002279 def test_stdout_stdin_are_single_inout_fd(self):
2280 with io.open(os.devnull, "r+") as inout:
2281 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2282 stdout=inout, stdin=inout)
2283 p.wait()
2284
2285 def test_stdout_stderr_are_single_inout_fd(self):
2286 with io.open(os.devnull, "r+") as inout:
2287 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2288 stdout=inout, stderr=inout)
2289 p.wait()
2290
2291 def test_stderr_stdin_are_single_inout_fd(self):
2292 with io.open(os.devnull, "r+") as inout:
2293 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2294 stderr=inout, stdin=inout)
2295 p.wait()
2296
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002297 def test_wait_when_sigchild_ignored(self):
2298 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2299 sigchild_ignore = support.findfile("sigchild_ignore.py",
2300 subdir="subprocessdata")
2301 p = subprocess.Popen([sys.executable, sigchild_ignore],
2302 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2303 stdout, stderr = p.communicate()
2304 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002305 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002306 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002307
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002308 def test_select_unbuffered(self):
2309 # Issue #11459: bufsize=0 should really set the pipes as
2310 # unbuffered (and therefore let select() work properly).
2311 select = support.import_module("select")
2312 p = subprocess.Popen([sys.executable, "-c",
2313 'import sys;'
2314 'sys.stdout.write("apple")'],
2315 stdout=subprocess.PIPE,
2316 bufsize=0)
2317 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002318 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002319 try:
2320 self.assertEqual(f.read(4), b"appl")
2321 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2322 finally:
2323 p.wait()
2324
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002325 def test_zombie_fast_process_del(self):
2326 # Issue #12650: on Unix, if Popen.__del__() was called before the
2327 # process exited, it wouldn't be added to subprocess._active, and would
2328 # remain a zombie.
2329 # spawn a Popen, and delete its reference before it exits
2330 p = subprocess.Popen([sys.executable, "-c",
2331 'import sys, time;'
2332 'time.sleep(0.2)'],
2333 stdout=subprocess.PIPE,
2334 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002335 self.addCleanup(p.stdout.close)
2336 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002337 ident = id(p)
2338 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002339 with support.check_warnings(('', ResourceWarning)):
2340 p = None
2341
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002342 # check that p is in the active processes list
2343 self.assertIn(ident, [id(o) for o in subprocess._active])
2344
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002345 def test_leak_fast_process_del_killed(self):
2346 # Issue #12650: on Unix, if Popen.__del__() was called before the
2347 # process exited, and the process got killed by a signal, it would never
2348 # be removed from subprocess._active, which triggered a FD and memory
2349 # leak.
2350 # spawn a Popen, delete its reference and kill it
2351 p = subprocess.Popen([sys.executable, "-c",
2352 'import time;'
2353 'time.sleep(3)'],
2354 stdout=subprocess.PIPE,
2355 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002356 self.addCleanup(p.stdout.close)
2357 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002358 ident = id(p)
2359 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002360 with support.check_warnings(('', ResourceWarning)):
2361 p = None
2362
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002363 os.kill(pid, signal.SIGKILL)
2364 # check that p is in the active processes list
2365 self.assertIn(ident, [id(o) for o in subprocess._active])
2366
2367 # let some time for the process to exit, and create a new Popen: this
2368 # should trigger the wait() of p
2369 time.sleep(0.2)
Andrew Svetlov3438fa42012-12-17 23:35:18 +02002370 with self.assertRaises(OSError) as c:
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002371 with subprocess.Popen(['nonexisting_i_hope'],
2372 stdout=subprocess.PIPE,
2373 stderr=subprocess.PIPE) as proc:
2374 pass
2375 # p should have been wait()ed on, and removed from the _active list
2376 self.assertRaises(OSError, os.waitpid, pid, 0)
2377 self.assertNotIn(ident, [id(o) for o in subprocess._active])
2378
Charles-François Natali249cdc32013-08-25 18:24:45 +02002379 def test_close_fds_after_preexec(self):
2380 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2381
2382 # this FD is used as dup2() target by preexec_fn, and should be closed
2383 # in the child process
2384 fd = os.dup(1)
2385 self.addCleanup(os.close, fd)
2386
2387 p = subprocess.Popen([sys.executable, fd_status],
2388 stdout=subprocess.PIPE, close_fds=True,
2389 preexec_fn=lambda: os.dup2(1, fd))
2390 output, ignored = p.communicate()
2391
2392 remaining_fds = set(map(int, output.split(b',')))
2393
2394 self.assertNotIn(fd, remaining_fds)
2395
Victor Stinner8f437aa2014-10-05 17:25:19 +02002396 @support.cpython_only
2397 def test_fork_exec(self):
2398 # Issue #22290: fork_exec() must not crash on memory allocation failure
2399 # or other errors
2400 import _posixsubprocess
2401 gc_enabled = gc.isenabled()
2402 try:
2403 # Use a preexec function and enable the garbage collector
2404 # to force fork_exec() to re-enable the garbage collector
2405 # on error.
2406 func = lambda: None
2407 gc.enable()
2408
Victor Stinner8f437aa2014-10-05 17:25:19 +02002409 for args, exe_list, cwd, env_list in (
2410 (123, [b"exe"], None, [b"env"]),
2411 ([b"arg"], 123, None, [b"env"]),
2412 ([b"arg"], [b"exe"], 123, [b"env"]),
2413 ([b"arg"], [b"exe"], None, 123),
2414 ):
2415 with self.assertRaises(TypeError):
2416 _posixsubprocess.fork_exec(
2417 args, exe_list,
2418 True, [], cwd, env_list,
2419 -1, -1, -1, -1,
2420 1, 2, 3, 4,
2421 True, True, func)
2422 finally:
2423 if not gc_enabled:
2424 gc.disable()
2425
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002426 @support.cpython_only
2427 def test_fork_exec_sorted_fd_sanity_check(self):
2428 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
2429 import _posixsubprocess
2430 gc_enabled = gc.isenabled()
2431 try:
2432 gc.enable()
2433
2434 for fds_to_keep in (
2435 (-1, 2, 3, 4, 5), # Negative number.
2436 ('str', 4), # Not an int.
2437 (18, 23, 42, 2**63), # Out of range.
2438 (5, 4), # Not sorted.
2439 (6, 7, 7, 8), # Duplicate.
2440 ):
2441 with self.assertRaises(
2442 ValueError,
2443 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
2444 _posixsubprocess.fork_exec(
2445 [b"false"], [b"false"],
2446 True, fds_to_keep, None, [b"env"],
2447 -1, -1, -1, -1,
2448 1, 2, 3, 4,
2449 True, True, None)
2450 self.assertIn('fds_to_keep', str(c.exception))
2451 finally:
2452 if not gc_enabled:
2453 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02002454
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00002455 def test_communicate_BrokenPipeError_stdin_close(self):
2456 # By not setting stdout or stderr or a timeout we force the fast path
2457 # that just calls _stdin_write() internally due to our mock.
2458 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2459 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2460 mock_proc_stdin.close.side_effect = BrokenPipeError
2461 proc.communicate() # Should swallow BrokenPipeError from close.
2462 mock_proc_stdin.close.assert_called_with()
2463
2464 def test_communicate_BrokenPipeError_stdin_write(self):
2465 # By not setting stdout or stderr or a timeout we force the fast path
2466 # that just calls _stdin_write() internally due to our mock.
2467 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2468 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2469 mock_proc_stdin.write.side_effect = BrokenPipeError
2470 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
2471 mock_proc_stdin.write.assert_called_once_with(b'stuff')
2472 mock_proc_stdin.close.assert_called_once_with()
2473
2474 def test_communicate_BrokenPipeError_stdin_flush(self):
2475 # Setting stdin and stdout forces the ._communicate() code path.
2476 # python -h exits faster than python -c pass (but spams stdout).
2477 proc = subprocess.Popen([sys.executable, '-h'],
2478 stdin=subprocess.PIPE,
2479 stdout=subprocess.PIPE)
2480 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
2481 open(os.devnull, 'wb') as dev_null:
2482 mock_proc_stdin.flush.side_effect = BrokenPipeError
2483 # because _communicate registers a selector using proc.stdin...
2484 mock_proc_stdin.fileno.return_value = dev_null.fileno()
2485 # _communicate() should swallow BrokenPipeError from flush.
2486 proc.communicate(b'stuff')
2487 mock_proc_stdin.flush.assert_called_once_with()
2488
2489 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
2490 # Setting stdin and stdout forces the ._communicate() code path.
2491 # python -h exits faster than python -c pass (but spams stdout).
2492 proc = subprocess.Popen([sys.executable, '-h'],
2493 stdin=subprocess.PIPE,
2494 stdout=subprocess.PIPE)
2495 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2496 mock_proc_stdin.close.side_effect = BrokenPipeError
2497 # _communicate() should swallow BrokenPipeError from close.
2498 proc.communicate(timeout=999)
2499 mock_proc_stdin.close.assert_called_once_with()
2500
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002501
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002502@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00002503class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002504
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002505 def test_startupinfo(self):
2506 # startupinfo argument
2507 # We uses hardcoded constants, because we do not want to
2508 # depend on win32all.
2509 STARTF_USESHOWWINDOW = 1
2510 SW_MAXIMIZE = 3
2511 startupinfo = subprocess.STARTUPINFO()
2512 startupinfo.dwFlags = STARTF_USESHOWWINDOW
2513 startupinfo.wShowWindow = SW_MAXIMIZE
2514 # Since Python is a console process, it won't be affected
2515 # by wShowWindow, but the argument should be silently
2516 # ignored
2517 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002518 startupinfo=startupinfo)
2519
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002520 def test_creationflags(self):
2521 # creationflags argument
2522 CREATE_NEW_CONSOLE = 16
2523 sys.stderr.write(" a DOS box should flash briefly ...\n")
2524 subprocess.call(sys.executable +
2525 ' -c "import time; time.sleep(0.25)"',
2526 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002527
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002528 def test_invalid_args(self):
2529 # invalid arguments should raise ValueError
2530 self.assertRaises(ValueError, subprocess.call,
2531 [sys.executable, "-c",
2532 "import sys; sys.exit(47)"],
2533 preexec_fn=lambda: 1)
2534 self.assertRaises(ValueError, subprocess.call,
2535 [sys.executable, "-c",
2536 "import sys; sys.exit(47)"],
2537 stdout=subprocess.PIPE,
2538 close_fds=True)
2539
2540 def test_close_fds(self):
2541 # close file descriptors
2542 rc = subprocess.call([sys.executable, "-c",
2543 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002544 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002545 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002546
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002547 def test_shell_sequence(self):
2548 # Run command through the shell (sequence)
2549 newenv = os.environ.copy()
2550 newenv["FRUIT"] = "physalis"
2551 p = subprocess.Popen(["set"], shell=1,
2552 stdout=subprocess.PIPE,
2553 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002554 with p:
2555 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00002556
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002557 def test_shell_string(self):
2558 # Run command through the shell (string)
2559 newenv = os.environ.copy()
2560 newenv["FRUIT"] = "physalis"
2561 p = subprocess.Popen("set", shell=1,
2562 stdout=subprocess.PIPE,
2563 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002564 with p:
2565 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002566
Steve Dower050acae2016-09-06 20:16:17 -07002567 def test_shell_encodings(self):
2568 # Run command through the shell (string)
2569 for enc in ['ansi', 'oem']:
2570 newenv = os.environ.copy()
2571 newenv["FRUIT"] = "physalis"
2572 p = subprocess.Popen("set", shell=1,
2573 stdout=subprocess.PIPE,
2574 env=newenv,
2575 encoding=enc)
2576 with p:
2577 self.assertIn("physalis", p.stdout.read(), enc)
2578
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002579 def test_call_string(self):
2580 # call() function with string argument on Windows
2581 rc = subprocess.call(sys.executable +
2582 ' -c "import sys; sys.exit(47)"')
2583 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002584
Florent Xicluna4886d242010-03-08 13:27:26 +00002585 def _kill_process(self, method, *args):
2586 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00002587 p = subprocess.Popen([sys.executable, "-c", """if 1:
2588 import sys, time
2589 sys.stdout.write('x\\n')
2590 sys.stdout.flush()
2591 time.sleep(30)
2592 """],
2593 stdin=subprocess.PIPE,
2594 stdout=subprocess.PIPE,
2595 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002596 with p:
2597 # Wait for the interpreter to be completely initialized before
2598 # sending any signal.
2599 p.stdout.read(1)
2600 getattr(p, method)(*args)
2601 _, stderr = p.communicate()
2602 self.assertStderrEqual(stderr, b'')
2603 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00002604 self.assertNotEqual(returncode, 0)
2605
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002606 def _kill_dead_process(self, method, *args):
2607 p = subprocess.Popen([sys.executable, "-c", """if 1:
2608 import sys, time
2609 sys.stdout.write('x\\n')
2610 sys.stdout.flush()
2611 sys.exit(42)
2612 """],
2613 stdin=subprocess.PIPE,
2614 stdout=subprocess.PIPE,
2615 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002616 with p:
2617 # Wait for the interpreter to be completely initialized before
2618 # sending any signal.
2619 p.stdout.read(1)
2620 # The process should end after this
2621 time.sleep(1)
2622 # This shouldn't raise even though the child is now dead
2623 getattr(p, method)(*args)
2624 _, stderr = p.communicate()
2625 self.assertStderrEqual(stderr, b'')
2626 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002627 self.assertEqual(rc, 42)
2628
Florent Xicluna4886d242010-03-08 13:27:26 +00002629 def test_send_signal(self):
2630 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00002631
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002632 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002633 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00002634
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002635 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002636 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00002637
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002638 def test_send_signal_dead(self):
2639 self._kill_dead_process('send_signal', signal.SIGTERM)
2640
2641 def test_kill_dead(self):
2642 self._kill_dead_process('kill')
2643
2644 def test_terminate_dead(self):
2645 self._kill_dead_process('terminate')
2646
Martin Panter23172bd2016-04-16 11:28:10 +00002647class MiscTests(unittest.TestCase):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002648 def test_getoutput(self):
2649 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
2650 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
2651 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00002652
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002653 # we use mkdtemp in the next line to create an empty directory
2654 # under our exclusive control; from that, we can invent a pathname
2655 # that we _know_ won't exist. This is guaranteed to fail.
2656 dir = None
2657 try:
2658 dir = tempfile.mkdtemp()
2659 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00002660 status, output = subprocess.getstatusoutput(
2661 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002662 self.assertNotEqual(status, 0)
2663 finally:
2664 if dir is not None:
2665 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00002666
Gregory P. Smithace55862015-04-07 15:57:54 -07002667 def test__all__(self):
2668 """Ensure that __all__ is populated properly."""
Martin Panter528619b2016-04-16 23:42:37 +00002669 intentionally_excluded = {"list2cmdline", "Handle"}
Gregory P. Smithace55862015-04-07 15:57:54 -07002670 exported = set(subprocess.__all__)
2671 possible_exports = set()
2672 import types
2673 for name, value in subprocess.__dict__.items():
2674 if name.startswith('_'):
2675 continue
2676 if isinstance(value, (types.ModuleType,)):
2677 continue
2678 possible_exports.add(name)
2679 self.assertEqual(exported, possible_exports - intentionally_excluded)
2680
2681
Martin Panter23172bd2016-04-16 11:28:10 +00002682@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
2683 "Test needs selectors.PollSelector")
2684class ProcessTestCaseNoPoll(ProcessTestCase):
2685 def setUp(self):
2686 self.orig_selector = subprocess._PopenSelector
2687 subprocess._PopenSelector = selectors.SelectSelector
2688 ProcessTestCase.setUp(self)
2689
2690 def tearDown(self):
2691 subprocess._PopenSelector = self.orig_selector
2692 ProcessTestCase.tearDown(self)
2693
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002694
Tim Golden126c2962010-08-11 14:20:40 +00002695@unittest.skipUnless(mswindows, "Windows-specific tests")
2696class CommandsWithSpaces (BaseTestCase):
2697
2698 def setUp(self):
2699 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03002700 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00002701 self.fname = fname.lower ()
2702 os.write(f, b"import sys;"
2703 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
2704 )
2705 os.close(f)
2706
2707 def tearDown(self):
2708 os.remove(self.fname)
2709 super().tearDown()
2710
2711 def with_spaces(self, *args, **kwargs):
2712 kwargs['stdout'] = subprocess.PIPE
2713 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02002714 with p:
2715 self.assertEqual(
2716 p.stdout.read ().decode("mbcs"),
2717 "2 [%r, 'ab cd']" % self.fname
2718 )
Tim Golden126c2962010-08-11 14:20:40 +00002719
2720 def test_shell_string_with_spaces(self):
2721 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002722 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2723 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002724
2725 def test_shell_sequence_with_spaces(self):
2726 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002727 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002728
2729 def test_noshell_string_with_spaces(self):
2730 # call() function with string argument with spaces on Windows
2731 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2732 "ab cd"))
2733
2734 def test_noshell_sequence_with_spaces(self):
2735 # call() function with sequence argument with spaces on Windows
2736 self.with_spaces([sys.executable, self.fname, "ab cd"])
2737
Brian Curtin79cdb662010-12-03 02:46:02 +00002738
Georg Brandla86b2622012-02-20 21:34:57 +01002739class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00002740
2741 def test_pipe(self):
2742 with subprocess.Popen([sys.executable, "-c",
2743 "import sys;"
2744 "sys.stdout.write('stdout');"
2745 "sys.stderr.write('stderr');"],
2746 stdout=subprocess.PIPE,
2747 stderr=subprocess.PIPE) as proc:
2748 self.assertEqual(proc.stdout.read(), b"stdout")
2749 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2750
2751 self.assertTrue(proc.stdout.closed)
2752 self.assertTrue(proc.stderr.closed)
2753
2754 def test_returncode(self):
2755 with subprocess.Popen([sys.executable, "-c",
2756 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002757 pass
2758 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002759 self.assertEqual(proc.returncode, 100)
2760
2761 def test_communicate_stdin(self):
2762 with subprocess.Popen([sys.executable, "-c",
2763 "import sys;"
2764 "sys.exit(sys.stdin.read() == 'context')"],
2765 stdin=subprocess.PIPE) as proc:
2766 proc.communicate(b"context")
2767 self.assertEqual(proc.returncode, 1)
2768
2769 def test_invalid_args(self):
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +01002770 with self.assertRaises((FileNotFoundError, PermissionError)) as c:
Brian Curtin79cdb662010-12-03 02:46:02 +00002771 with subprocess.Popen(['nonexisting_i_hope'],
2772 stdout=subprocess.PIPE,
2773 stderr=subprocess.PIPE) as proc:
2774 pass
2775
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002776 def test_broken_pipe_cleanup(self):
2777 """Broken pipe error should not prevent wait() (Issue 21619)"""
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002778 proc = subprocess.Popen([sys.executable, '-c', 'pass'],
Victor Stinner20f4bd42015-03-05 02:38:41 +01002779 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01002780 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002781 proc = proc.__enter__()
2782 # Prepare to send enough data to overflow any OS pipe buffering and
2783 # guarantee a broken pipe error. Data is held in BufferedWriter
2784 # buffer until closed.
2785 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002786 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002787 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02002788 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002789 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002790 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002791
Brian Curtin79cdb662010-12-03 02:46:02 +00002792
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002793if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002794 unittest.main()