blob: 6b8acb258ee36e9be50e15fa7e47398ffae9758f [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +00002from unittest import mock
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003from test import support
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00004import subprocess
5import sys
Gregory P. Smith50e16e32017-01-22 17:28:38 -08006import platform
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00007import signal
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04008import io
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +03009import itertools
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000010import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +000011import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000012import tempfile
13import time
Charles-François Natali3a4586a2013-11-08 19:56:59 +010014import selectors
Ezio Melotti184bdfb2010-02-18 09:37:05 +000015import sysconfig
Gregory P. Smith51ee2702010-12-13 07:59:39 +000016import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040017import shutil
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020018import threading
Benjamin Petersonb870aa12011-12-10 12:44:25 -050019import gc
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030020import textwrap
Serhiy Storchakab21d1552018-03-02 11:53:51 +020021from test.support import FakePath
Benjamin Peterson964561b2011-12-10 12:31:42 -050022
23try:
Gregory P. Smith1fa08bc2017-01-22 22:19:38 -080024 import ctypes
25except ImportError:
26 ctypes = None
Gregory P. Smith56bc3b72017-05-23 07:49:13 -070027else:
28 import ctypes.util
Gregory P. Smith1fa08bc2017-01-22 22:19:38 -080029
30try:
Victor Stinner7b7c6dc2017-08-10 12:37:39 +020031 import _testcapi
32except ImportError:
33 _testcapi = None
34
Steve Dower22d06982016-09-06 19:38:15 -070035if support.PGO:
36 raise unittest.SkipTest("test is not helpful for PGO")
37
Victor Stinner937ee9e2018-06-26 02:11:06 +020038mswindows = (sys.platform == "win32")
39
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000040#
41# Depends on the following external programs: Python
42#
43
Victor Stinner937ee9e2018-06-26 02:11:06 +020044if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000045 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
46 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000047else:
48 SETBINARY = ''
49
Victor Stinner9a83f652017-08-21 23:51:31 +020050NONEXISTING_CMD = ('nonexisting_i_hope',)
Victor Stinnerb31206a2018-01-25 19:06:05 +010051# Ignore errors that indicate the command was not found
52NONEXISTING_ERRORS = (FileNotFoundError, NotADirectoryError, PermissionError)
Victor Stinner9a83f652017-08-21 23:51:31 +020053
Florent Xiclunab1e94e82010-02-27 22:12:37 +000054
Florent Xiclunac049d872010-03-27 22:47:23 +000055class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000056 def setUp(self):
57 # Try to minimize the number of children we have so this test
58 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000059 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000060
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000061 def tearDown(self):
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +030062 if not mswindows:
63 # subprocess._active is not used on Windows and is set to None.
64 for inst in subprocess._active:
65 inst.wait()
66 subprocess._cleanup()
67 self.assertFalse(
68 subprocess._active, "subprocess._active not empty"
69 )
Victor Stinnercc42c122017-07-28 18:00:22 +020070 self.doCleanups()
71 support.reap_children()
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000072
Florent Xiclunab1e94e82010-02-27 22:12:37 +000073 def assertStderrEqual(self, stderr, expected, msg=None):
74 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
75 # shutdown time. That frustrates tests trying to check stderr produced
76 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000077 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040078 # strip_python_stderr also strips whitespace, so we do too.
79 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000080 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000081
Florent Xiclunac049d872010-03-27 22:47:23 +000082
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080083class PopenTestException(Exception):
84 pass
85
86
87class PopenExecuteChildRaises(subprocess.Popen):
88 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
89 _execute_child fails.
90 """
91 def _execute_child(self, *args, **kwargs):
92 raise PopenTestException("Forced Exception for Test")
93
94
Florent Xiclunac049d872010-03-27 22:47:23 +000095class ProcessTestCase(BaseTestCase):
96
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070097 def test_io_buffered_by_default(self):
98 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
99 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
100 stderr=subprocess.PIPE)
101 try:
102 self.assertIsInstance(p.stdin, io.BufferedIOBase)
103 self.assertIsInstance(p.stdout, io.BufferedIOBase)
104 self.assertIsInstance(p.stderr, io.BufferedIOBase)
105 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700106 p.stdin.close()
107 p.stdout.close()
108 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700109 p.wait()
110
111 def test_io_unbuffered_works(self):
112 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
113 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
114 stderr=subprocess.PIPE, bufsize=0)
115 try:
116 self.assertIsInstance(p.stdin, io.RawIOBase)
117 self.assertIsInstance(p.stdout, io.RawIOBase)
118 self.assertIsInstance(p.stderr, io.RawIOBase)
119 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700120 p.stdin.close()
121 p.stdout.close()
122 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700123 p.wait()
124
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000125 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000126 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000127 rc = subprocess.call([sys.executable, "-c",
128 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000129 self.assertEqual(rc, 47)
130
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400131 def test_call_timeout(self):
132 # call() function with timeout argument; we want to test that the child
133 # process gets killed when the timeout expires. If the child isn't
134 # killed, this call will deadlock since subprocess.call waits for the
135 # child.
136 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
137 [sys.executable, "-c", "while True: pass"],
138 timeout=0.1)
139
Peter Astrand454f7672005-01-01 09:36:35 +0000140 def test_check_call_zero(self):
141 # check_call() function with zero return code
142 rc = subprocess.check_call([sys.executable, "-c",
143 "import sys; sys.exit(0)"])
144 self.assertEqual(rc, 0)
145
146 def test_check_call_nonzero(self):
147 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000148 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000149 subprocess.check_call([sys.executable, "-c",
150 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000151 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000152
Georg Brandlf9734072008-12-07 15:30:06 +0000153 def test_check_output(self):
154 # check_output() function with zero return code
155 output = subprocess.check_output(
156 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000157 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000158
159 def test_check_output_nonzero(self):
160 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000161 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000162 subprocess.check_output(
163 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000164 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000165
166 def test_check_output_stderr(self):
167 # check_output() function stderr redirected to stdout
168 output = subprocess.check_output(
169 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
170 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000171 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000172
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300173 def test_check_output_stdin_arg(self):
174 # check_output() can be called with stdin set to a file
175 tf = tempfile.TemporaryFile()
176 self.addCleanup(tf.close)
177 tf.write(b'pear')
178 tf.seek(0)
179 output = subprocess.check_output(
180 [sys.executable, "-c",
181 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
182 stdin=tf)
183 self.assertIn(b'PEAR', output)
184
185 def test_check_output_input_arg(self):
186 # check_output() can be called with input set to a string
187 output = subprocess.check_output(
188 [sys.executable, "-c",
189 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
190 input=b'pear')
191 self.assertIn(b'PEAR', output)
192
Georg Brandlf9734072008-12-07 15:30:06 +0000193 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300194 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000195 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000196 output = subprocess.check_output(
197 [sys.executable, "-c", "print('will not be run')"],
198 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000199 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000200 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000201
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300202 def test_check_output_stdin_with_input_arg(self):
203 # check_output() refuses to accept 'stdin' with 'input'
204 tf = tempfile.TemporaryFile()
205 self.addCleanup(tf.close)
206 tf.write(b'pear')
207 tf.seek(0)
208 with self.assertRaises(ValueError) as c:
209 output = subprocess.check_output(
210 [sys.executable, "-c", "print('will not be run')"],
211 stdin=tf, input=b'hare')
212 self.fail("Expected ValueError when stdin and input args supplied.")
213 self.assertIn('stdin', c.exception.args[0])
214 self.assertIn('input', c.exception.args[0])
215
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400216 def test_check_output_timeout(self):
217 # check_output() function with timeout arg
218 with self.assertRaises(subprocess.TimeoutExpired) as c:
219 output = subprocess.check_output(
220 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200221 "import sys, time\n"
222 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400223 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200224 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400225 # Some heavily loaded buildbots (sparc Debian 3.x) require
226 # this much time to start and print.
227 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400228 self.fail("Expected TimeoutExpired.")
229 self.assertEqual(c.exception.output, b'BDFL')
230
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000231 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000232 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000233 newenv = os.environ.copy()
234 newenv["FRUIT"] = "banana"
235 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000236 'import sys, os;'
237 'sys.exit(os.getenv("FRUIT")=="banana")'],
238 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000239 self.assertEqual(rc, 1)
240
Victor Stinner87b9bc32011-06-01 00:57:47 +0200241 def test_invalid_args(self):
242 # Popen() called with invalid arguments should raise TypeError
243 # but Popen.__del__ should not complain (issue #12085)
244 with support.captured_stderr() as s:
245 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
246 argcount = subprocess.Popen.__init__.__code__.co_argcount
247 too_many_args = [0] * (argcount + 1)
248 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
249 self.assertEqual(s.getvalue(), '')
250
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000251 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000252 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000253 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000254 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000255 self.addCleanup(p.stdout.close)
256 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000257 p.wait()
258 self.assertEqual(p.stdin, None)
259
260 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200261 # .stdout is None when not redirected, and the child's stdout will
262 # be inherited from the parent. In order to test this we run a
263 # subprocess in a subprocess:
264 # this_test
265 # \-- subprocess created by this test (parent)
266 # \-- subprocess created by the parent subprocess (child)
267 # The parent doesn't specify stdout, so the child will use the
268 # parent's stdout. This test checks that the message printed by the
269 # child goes to the parent stdout. The parent also checks that the
270 # child's stdout is None. See #11963.
271 code = ('import sys; from subprocess import Popen, PIPE;'
272 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
273 ' stdin=PIPE, stderr=PIPE);'
274 'p.wait(); assert p.stdout is None;')
275 p = subprocess.Popen([sys.executable, "-c", code],
276 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
277 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000278 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200279 out, err = p.communicate()
280 self.assertEqual(p.returncode, 0, err)
281 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000282
283 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000284 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000285 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000286 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000287 self.addCleanup(p.stdout.close)
288 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000289 p.wait()
290 self.assertEqual(p.stderr, None)
291
Chris Jerdonek776cb192012-10-08 15:56:43 -0700292 def _assert_python(self, pre_args, **kwargs):
293 # We include sys.exit() to prevent the test runner from hanging
294 # whenever python is found.
295 args = pre_args + ["import sys; sys.exit(47)"]
296 p = subprocess.Popen(args, **kwargs)
297 p.wait()
298 self.assertEqual(47, p.returncode)
299
300 def test_executable(self):
301 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700302 #
303 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
304 # determine where its standard library is, so we need the directory
305 # of args[0] to be valid for the Popen() call to Python to succeed.
306 # See also issue #16170 and issue #7774.
307 doesnotexist = os.path.join(os.path.dirname(sys.executable),
308 "doesnotexist")
309 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700310
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300311 def test_bytes_executable(self):
312 doesnotexist = os.path.join(os.path.dirname(sys.executable),
313 "doesnotexist")
314 self._assert_python([doesnotexist, "-c"],
315 executable=os.fsencode(sys.executable))
316
317 def test_pathlike_executable(self):
318 doesnotexist = os.path.join(os.path.dirname(sys.executable),
319 "doesnotexist")
320 self._assert_python([doesnotexist, "-c"],
321 executable=FakePath(sys.executable))
322
Chris Jerdonek776cb192012-10-08 15:56:43 -0700323 def test_executable_takes_precedence(self):
324 # Check that the executable argument takes precedence over args[0].
325 #
326 # Verify first that the call succeeds without the executable arg.
327 pre_args = [sys.executable, "-c"]
328 self._assert_python(pre_args)
Victor Stinnerb31206a2018-01-25 19:06:05 +0100329 self.assertRaises(NONEXISTING_ERRORS,
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +0100330 self._assert_python, pre_args,
Victor Stinnerb31206a2018-01-25 19:06:05 +0100331 executable=NONEXISTING_CMD[0])
Chris Jerdonek776cb192012-10-08 15:56:43 -0700332
Victor Stinner937ee9e2018-06-26 02:11:06 +0200333 @unittest.skipIf(mswindows, "executable argument replaces shell")
Chris Jerdonek776cb192012-10-08 15:56:43 -0700334 def test_executable_replaces_shell(self):
335 # Check that the executable argument replaces the default shell
336 # when shell=True.
337 self._assert_python([], executable=sys.executable, shell=True)
338
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300339 @unittest.skipIf(mswindows, "executable argument replaces shell")
340 def test_bytes_executable_replaces_shell(self):
341 self._assert_python([], executable=os.fsencode(sys.executable),
342 shell=True)
343
344 @unittest.skipIf(mswindows, "executable argument replaces shell")
345 def test_pathlike_executable_replaces_shell(self):
346 self._assert_python([], executable=FakePath(sys.executable),
347 shell=True)
348
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700349 # For use in the test_cwd* tests below.
350 def _normalize_cwd(self, cwd):
351 # Normalize an expected cwd (for Tru64 support).
352 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
353 # strings. See bug #1063571.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300354 with support.change_cwd(cwd):
355 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700356
357 # For use in the test_cwd* tests below.
358 def _split_python_path(self):
359 # Return normalized (python_dir, python_base).
360 python_path = os.path.realpath(sys.executable)
361 return os.path.split(python_path)
362
363 # For use in the test_cwd* tests below.
364 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
365 # Invoke Python via Popen, and assert that (1) the call succeeds,
366 # and that (2) the current working directory of the child process
367 # matches *expected_cwd*.
368 p = subprocess.Popen([python_arg, "-c",
369 "import os, sys; "
370 "sys.stdout.write(os.getcwd()); "
371 "sys.exit(47)"],
372 stdout=subprocess.PIPE,
373 **kwargs)
374 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000375 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700376 self.assertEqual(47, p.returncode)
377 normcase = os.path.normcase
378 self.assertEqual(normcase(expected_cwd),
379 normcase(p.stdout.read().decode("utf-8")))
380
381 def test_cwd(self):
382 # Check that cwd changes the cwd for the child process.
383 temp_dir = tempfile.gettempdir()
384 temp_dir = self._normalize_cwd(temp_dir)
385 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
386
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300387 def test_cwd_with_bytes(self):
388 temp_dir = tempfile.gettempdir()
389 temp_dir = self._normalize_cwd(temp_dir)
390 self._assert_cwd(temp_dir, sys.executable, cwd=os.fsencode(temp_dir))
391
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530392 def test_cwd_with_pathlike(self):
393 temp_dir = tempfile.gettempdir()
394 temp_dir = self._normalize_cwd(temp_dir)
Serhiy Storchakab21d1552018-03-02 11:53:51 +0200395 self._assert_cwd(temp_dir, sys.executable, cwd=FakePath(temp_dir))
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530396
Victor Stinner937ee9e2018-06-26 02:11:06 +0200397 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700398 def test_cwd_with_relative_arg(self):
399 # Check that Popen looks for args[0] relative to cwd if args[0]
400 # is relative.
401 python_dir, python_base = self._split_python_path()
402 rel_python = os.path.join(os.curdir, python_base)
403 with support.temp_cwd() as wrong_dir:
404 # Before calling with the correct cwd, confirm that the call fails
405 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700406 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700407 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700408 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700409 [rel_python], cwd=wrong_dir)
410 python_dir = self._normalize_cwd(python_dir)
411 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
412
Victor Stinner937ee9e2018-06-26 02:11:06 +0200413 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700414 def test_cwd_with_relative_executable(self):
415 # Check that Popen looks for executable relative to cwd if executable
416 # is relative (and that executable takes precedence over args[0]).
417 python_dir, python_base = self._split_python_path()
418 rel_python = os.path.join(os.curdir, python_base)
419 doesntexist = "somethingyoudonthave"
420 with support.temp_cwd() as wrong_dir:
421 # Before calling with the correct cwd, confirm that the call fails
422 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700423 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700424 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700425 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700426 [doesntexist], executable=rel_python,
427 cwd=wrong_dir)
428 python_dir = self._normalize_cwd(python_dir)
429 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
430 cwd=python_dir)
431
432 def test_cwd_with_absolute_arg(self):
433 # Check that Popen can find the executable when the cwd is wrong
434 # if args[0] is an absolute path.
435 python_dir, python_base = self._split_python_path()
436 abs_python = os.path.join(python_dir, python_base)
437 rel_python = os.path.join(os.curdir, python_base)
Berker Peksagce643912015-05-06 06:33:17 +0300438 with support.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700439 # Before calling with an absolute path, confirm that using a
440 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700441 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700442 [rel_python], cwd=wrong_dir)
443 wrong_dir = self._normalize_cwd(wrong_dir)
444 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
445
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100446 @unittest.skipIf(sys.base_prefix != sys.prefix,
447 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000448 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700449 python_dir, python_base = self._split_python_path()
450 python_dir = self._normalize_cwd(python_dir)
451 self._assert_cwd(python_dir, "somethingyoudonthave",
452 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000453
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100454 @unittest.skipIf(sys.base_prefix != sys.prefix,
455 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000456 @unittest.skipIf(sysconfig.is_python_build(),
457 "need an installed Python. See #7774")
458 def test_executable_without_cwd(self):
459 # For a normal installation, it should work without 'cwd'
460 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700461 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
462 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000463
464 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000465 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000466 p = subprocess.Popen([sys.executable, "-c",
467 'import sys; sys.exit(sys.stdin.read() == "pear")'],
468 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000469 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000470 p.stdin.close()
471 p.wait()
472 self.assertEqual(p.returncode, 1)
473
474 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000475 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000476 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000477 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000478 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000479 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000480 os.lseek(d, 0, 0)
481 p = subprocess.Popen([sys.executable, "-c",
482 'import sys; sys.exit(sys.stdin.read() == "pear")'],
483 stdin=d)
484 p.wait()
485 self.assertEqual(p.returncode, 1)
486
487 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000488 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000489 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000490 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000491 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000492 tf.seek(0)
493 p = subprocess.Popen([sys.executable, "-c",
494 'import sys; sys.exit(sys.stdin.read() == "pear")'],
495 stdin=tf)
496 p.wait()
497 self.assertEqual(p.returncode, 1)
498
499 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000500 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000501 p = subprocess.Popen([sys.executable, "-c",
502 'import sys; sys.stdout.write("orange")'],
503 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200504 with p:
505 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000506
507 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000508 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000509 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000510 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000511 d = tf.fileno()
512 p = subprocess.Popen([sys.executable, "-c",
513 'import sys; sys.stdout.write("orange")'],
514 stdout=d)
515 p.wait()
516 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000517 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000518
519 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000520 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000521 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000522 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000523 p = subprocess.Popen([sys.executable, "-c",
524 'import sys; sys.stdout.write("orange")'],
525 stdout=tf)
526 p.wait()
527 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000528 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000529
530 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000531 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000532 p = subprocess.Popen([sys.executable, "-c",
533 'import sys; sys.stderr.write("strawberry")'],
534 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200535 with p:
536 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000537
538 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000539 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000540 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000541 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000542 d = tf.fileno()
543 p = subprocess.Popen([sys.executable, "-c",
544 'import sys; sys.stderr.write("strawberry")'],
545 stderr=d)
546 p.wait()
547 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000548 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000549
550 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000551 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000552 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000553 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000554 p = subprocess.Popen([sys.executable, "-c",
555 'import sys; sys.stderr.write("strawberry")'],
556 stderr=tf)
557 p.wait()
558 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000559 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000560
Martin Panterc7635892016-05-13 01:54:44 +0000561 def test_stderr_redirect_with_no_stdout_redirect(self):
562 # test stderr=STDOUT while stdout=None (not set)
563
564 # - grandchild prints to stderr
565 # - child redirects grandchild's stderr to its stdout
566 # - the parent should get grandchild's stderr in child's stdout
567 p = subprocess.Popen([sys.executable, "-c",
568 'import sys, subprocess;'
569 'rc = subprocess.call([sys.executable, "-c",'
570 ' "import sys;"'
571 ' "sys.stderr.write(\'42\')"],'
572 ' stderr=subprocess.STDOUT);'
573 'sys.exit(rc)'],
574 stdout=subprocess.PIPE,
575 stderr=subprocess.PIPE)
576 stdout, stderr = p.communicate()
577 #NOTE: stdout should get stderr from grandchild
578 self.assertStderrEqual(stdout, b'42')
579 self.assertStderrEqual(stderr, b'') # should be empty
580 self.assertEqual(p.returncode, 0)
581
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000582 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000583 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000584 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000585 'import sys;'
586 'sys.stdout.write("apple");'
587 'sys.stdout.flush();'
588 'sys.stderr.write("orange")'],
589 stdout=subprocess.PIPE,
590 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200591 with p:
592 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000593
594 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000595 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000596 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000597 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000598 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000599 'import sys;'
600 'sys.stdout.write("apple");'
601 'sys.stdout.flush();'
602 'sys.stderr.write("orange")'],
603 stdout=tf,
604 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000605 p.wait()
606 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000607 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000608
Thomas Wouters89f507f2006-12-13 04:49:30 +0000609 def test_stdout_filedes_of_stdout(self):
610 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200611 # To avoid printing the text on stdout, we do something similar to
612 # test_stdout_none (see above). The parent subprocess calls the child
613 # subprocess passing stdout=1, and this test uses stdout=PIPE in
614 # order to capture and check the output of the parent. See #11963.
615 code = ('import sys, subprocess; '
616 'rc = subprocess.call([sys.executable, "-c", '
617 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
618 'b\'test with stdout=1\'))"], stdout=1); '
619 'assert rc == 18')
620 p = subprocess.Popen([sys.executable, "-c", code],
621 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
622 self.addCleanup(p.stdout.close)
623 self.addCleanup(p.stderr.close)
624 out, err = p.communicate()
625 self.assertEqual(p.returncode, 0, err)
626 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000627
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200628 def test_stdout_devnull(self):
629 p = subprocess.Popen([sys.executable, "-c",
630 'for i in range(10240):'
631 'print("x" * 1024)'],
632 stdout=subprocess.DEVNULL)
633 p.wait()
634 self.assertEqual(p.stdout, None)
635
636 def test_stderr_devnull(self):
637 p = subprocess.Popen([sys.executable, "-c",
638 'import sys\n'
639 'for i in range(10240):'
640 'sys.stderr.write("x" * 1024)'],
641 stderr=subprocess.DEVNULL)
642 p.wait()
643 self.assertEqual(p.stderr, None)
644
645 def test_stdin_devnull(self):
646 p = subprocess.Popen([sys.executable, "-c",
647 'import sys;'
648 'sys.stdin.read(1)'],
649 stdin=subprocess.DEVNULL)
650 p.wait()
651 self.assertEqual(p.stdin, None)
652
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000653 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000654 newenv = os.environ.copy()
655 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200656 with subprocess.Popen([sys.executable, "-c",
657 'import sys,os;'
658 'sys.stdout.write(os.getenv("FRUIT"))'],
659 stdout=subprocess.PIPE,
660 env=newenv) as p:
661 stdout, stderr = p.communicate()
662 self.assertEqual(stdout, b"orange")
663
Victor Stinner62d51182011-06-23 01:02:25 +0200664 # Windows requires at least the SYSTEMROOT environment variable to start
665 # Python
666 @unittest.skipIf(sys.platform == 'win32',
667 'cannot test an empty env on Windows')
Gregory P. Smithb3512482017-05-30 14:40:37 -0700668 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
669 'The Python shared library cannot be loaded '
670 'with an empty environment.')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200671 def test_empty_env(self):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700672 """Verify that env={} is as empty as possible."""
673
Gregory P. Smith85aba232017-05-30 16:21:47 -0700674 def is_env_var_to_ignore(n):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700675 """Determine if an environment variable is under our control."""
676 # This excludes some __CF_* and VERSIONER_* keys MacOS insists
677 # on adding even when the environment in exec is empty.
678 # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist.
Gregory P. Smith85aba232017-05-30 16:21:47 -0700679 return ('VERSIONER' in n or '__CF' in n or # MacOS
Ned Deily918edc02017-09-04 00:00:21 -0400680 '__PYVENV_LAUNCHER__' in n or # MacOS framework build
Nick Coghlan6ea41862017-06-11 13:16:15 +1000681 n == 'LD_PRELOAD' or n.startswith('SANDBOX') or # Gentoo
682 n == 'LC_CTYPE') # Locale coercion triggered
Gregory P. Smithb3512482017-05-30 14:40:37 -0700683
Victor Stinnerf1512a22011-06-21 17:18:38 +0200684 with subprocess.Popen([sys.executable, "-c",
Gregory P. Smithb3512482017-05-30 14:40:37 -0700685 'import os; print(list(os.environ.keys()))'],
686 stdout=subprocess.PIPE, env={}) as p:
Victor Stinnerf1512a22011-06-21 17:18:38 +0200687 stdout, stderr = p.communicate()
Gregory P. Smithb3512482017-05-30 14:40:37 -0700688 child_env_names = eval(stdout.strip())
689 self.assertIsInstance(child_env_names, list)
690 child_env_names = [k for k in child_env_names
691 if not is_env_var_to_ignore(k)]
692 self.assertEqual(child_env_names, [])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000693
Serhiy Storchakad174d242017-06-23 19:39:27 +0300694 def test_invalid_cmd(self):
695 # null character in the command name
696 cmd = sys.executable + '\0'
697 with self.assertRaises(ValueError):
698 subprocess.Popen([cmd, "-c", "pass"])
699
700 # null character in the command argument
701 with self.assertRaises(ValueError):
702 subprocess.Popen([sys.executable, "-c", "pass#\0"])
703
704 def test_invalid_env(self):
Ville Skyttä49b27342017-08-03 09:00:59 +0300705 # null character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300706 newenv = os.environ.copy()
707 newenv["FRUIT\0VEGETABLE"] = "cabbage"
708 with self.assertRaises(ValueError):
709 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
710
Ville Skyttä49b27342017-08-03 09:00:59 +0300711 # null character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300712 newenv = os.environ.copy()
713 newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
714 with self.assertRaises(ValueError):
715 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
716
Ville Skyttä49b27342017-08-03 09:00:59 +0300717 # equal character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300718 newenv = os.environ.copy()
719 newenv["FRUIT=ORANGE"] = "lemon"
720 with self.assertRaises(ValueError):
721 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
722
Ville Skyttä49b27342017-08-03 09:00:59 +0300723 # equal character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300724 newenv = os.environ.copy()
725 newenv["FRUIT"] = "orange=lemon"
726 with subprocess.Popen([sys.executable, "-c",
727 'import sys, os;'
728 'sys.stdout.write(os.getenv("FRUIT"))'],
729 stdout=subprocess.PIPE,
730 env=newenv) as p:
731 stdout, stderr = p.communicate()
732 self.assertEqual(stdout, b"orange=lemon")
733
Peter Astrandcbac93c2005-03-03 20:24:28 +0000734 def test_communicate_stdin(self):
735 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000736 'import sys;'
737 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000738 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000739 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000740 self.assertEqual(p.returncode, 1)
741
742 def test_communicate_stdout(self):
743 p = subprocess.Popen([sys.executable, "-c",
744 'import sys; sys.stdout.write("pineapple")'],
745 stdout=subprocess.PIPE)
746 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000747 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000748 self.assertEqual(stderr, None)
749
750 def test_communicate_stderr(self):
751 p = subprocess.Popen([sys.executable, "-c",
752 'import sys; sys.stderr.write("pineapple")'],
753 stderr=subprocess.PIPE)
754 (stdout, stderr) = p.communicate()
755 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000756 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000757
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000758 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000759 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000760 'import sys,os;'
761 'sys.stderr.write("pineapple");'
762 'sys.stdout.write(sys.stdin.read())'],
763 stdin=subprocess.PIPE,
764 stdout=subprocess.PIPE,
765 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000766 self.addCleanup(p.stdout.close)
767 self.addCleanup(p.stderr.close)
768 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000769 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000770 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000771 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000772
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400773 def test_communicate_timeout(self):
774 p = subprocess.Popen([sys.executable, "-c",
775 'import sys,os,time;'
776 'sys.stderr.write("pineapple\\n");'
777 'time.sleep(1);'
778 'sys.stderr.write("pear\\n");'
779 'sys.stdout.write(sys.stdin.read())'],
780 universal_newlines=True,
781 stdin=subprocess.PIPE,
782 stdout=subprocess.PIPE,
783 stderr=subprocess.PIPE)
784 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
785 timeout=0.3)
786 # Make sure we can keep waiting for it, and that we get the whole output
787 # after it completes.
788 (stdout, stderr) = p.communicate()
789 self.assertEqual(stdout, "banana")
790 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
791
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700792 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200793 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400794 p = subprocess.Popen([sys.executable, "-c",
795 'import sys,os,time;'
796 'sys.stdout.write("a" * (64 * 1024));'
797 'time.sleep(0.2);'
798 'sys.stdout.write("a" * (64 * 1024));'
799 'time.sleep(0.2);'
800 'sys.stdout.write("a" * (64 * 1024));'
801 'time.sleep(0.2);'
802 'sys.stdout.write("a" * (64 * 1024));'],
803 stdout=subprocess.PIPE)
804 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
805 (stdout, _) = p.communicate()
806 self.assertEqual(len(stdout), 4 * 64 * 1024)
807
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000808 # Test for the fd leak reported in http://bugs.python.org/issue2791.
809 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000810 for stdin_pipe in (False, True):
811 for stdout_pipe in (False, True):
812 for stderr_pipe in (False, True):
813 options = {}
814 if stdin_pipe:
815 options['stdin'] = subprocess.PIPE
816 if stdout_pipe:
817 options['stdout'] = subprocess.PIPE
818 if stderr_pipe:
819 options['stderr'] = subprocess.PIPE
820 if not options:
821 continue
822 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
823 p.communicate()
824 if p.stdin is not None:
825 self.assertTrue(p.stdin.closed)
826 if p.stdout is not None:
827 self.assertTrue(p.stdout.closed)
828 if p.stderr is not None:
829 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000830
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000831 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000832 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000833 p = subprocess.Popen([sys.executable, "-c",
834 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000835 (stdout, stderr) = p.communicate()
836 self.assertEqual(stdout, None)
837 self.assertEqual(stderr, None)
838
839 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000840 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000841 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000842 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000843 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000844 os.close(x)
845 os.close(y)
846 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000847 'import sys,os;'
848 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200849 'sys.stderr.write("x" * %d);'
850 'sys.stdout.write(sys.stdin.read())' %
851 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000852 stdin=subprocess.PIPE,
853 stdout=subprocess.PIPE,
854 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000855 self.addCleanup(p.stdout.close)
856 self.addCleanup(p.stderr.close)
857 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200858 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000859 (stdout, stderr) = p.communicate(string_to_write)
860 self.assertEqual(stdout, string_to_write)
861
862 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000863 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000864 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000865 'import sys,os;'
866 'sys.stdout.write(sys.stdin.read())'],
867 stdin=subprocess.PIPE,
868 stdout=subprocess.PIPE,
869 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000870 self.addCleanup(p.stdout.close)
871 self.addCleanup(p.stderr.close)
872 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000873 p.stdin.write(b"banana")
874 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000875 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000876 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000877
andyclegg7fed7bd2017-10-23 03:01:19 +0100878 def test_universal_newlines_and_text(self):
879 args = [
880 sys.executable, "-c",
881 'import sys,os;' + SETBINARY +
882 'buf = sys.stdout.buffer;'
883 'buf.write(sys.stdin.readline().encode());'
884 'buf.flush();'
885 'buf.write(b"line2\\n");'
886 'buf.flush();'
887 'buf.write(sys.stdin.read().encode());'
888 'buf.flush();'
889 'buf.write(b"line4\\n");'
890 'buf.flush();'
891 'buf.write(b"line5\\r\\n");'
892 'buf.flush();'
893 'buf.write(b"line6\\r");'
894 'buf.flush();'
895 'buf.write(b"\\nline7");'
896 'buf.flush();'
897 'buf.write(b"\\nline8");']
898
899 for extra_kwarg in ('universal_newlines', 'text'):
900 p = subprocess.Popen(args, **{'stdin': subprocess.PIPE,
901 'stdout': subprocess.PIPE,
902 extra_kwarg: True})
903 with p:
904 p.stdin.write("line1\n")
905 p.stdin.flush()
906 self.assertEqual(p.stdout.readline(), "line1\n")
907 p.stdin.write("line3\n")
908 p.stdin.close()
909 self.addCleanup(p.stdout.close)
910 self.assertEqual(p.stdout.readline(),
911 "line2\n")
912 self.assertEqual(p.stdout.read(6),
913 "line3\n")
914 self.assertEqual(p.stdout.read(),
915 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000916
917 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000918 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000919 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000920 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200921 'buf = sys.stdout.buffer;'
922 'buf.write(b"line2\\n");'
923 'buf.flush();'
924 'buf.write(b"line4\\n");'
925 'buf.flush();'
926 'buf.write(b"line5\\r\\n");'
927 'buf.flush();'
928 'buf.write(b"line6\\r");'
929 'buf.flush();'
930 'buf.write(b"\\nline7");'
931 'buf.flush();'
932 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200933 stderr=subprocess.PIPE,
934 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000935 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000936 self.addCleanup(p.stdout.close)
937 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000938 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200939 self.assertEqual(stdout,
940 "line2\nline4\nline5\nline6\nline7\nline8")
941
942 def test_universal_newlines_communicate_stdin(self):
943 # universal newlines through communicate(), with only stdin
944 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300945 'import sys,os;' + SETBINARY + textwrap.dedent('''
946 s = sys.stdin.readline()
947 assert s == "line1\\n", repr(s)
948 s = sys.stdin.read()
949 assert s == "line3\\n", repr(s)
950 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200951 stdin=subprocess.PIPE,
952 universal_newlines=1)
953 (stdout, stderr) = p.communicate("line1\nline3\n")
954 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000955
Andrew Svetlovf3765072012-08-14 18:35:17 +0300956 def test_universal_newlines_communicate_input_none(self):
957 # Test communicate(input=None) with universal newlines.
958 #
959 # We set stdout to PIPE because, as of this writing, a different
960 # code path is tested when the number of pipes is zero or one.
961 p = subprocess.Popen([sys.executable, "-c", "pass"],
962 stdin=subprocess.PIPE,
963 stdout=subprocess.PIPE,
964 universal_newlines=True)
965 p.communicate()
966 self.assertEqual(p.returncode, 0)
967
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300968 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300969 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300970 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300971 'import sys,os;' + SETBINARY + textwrap.dedent('''
972 s = sys.stdin.buffer.readline()
973 sys.stdout.buffer.write(s)
974 sys.stdout.buffer.write(b"line2\\r")
975 sys.stderr.buffer.write(b"eline2\\n")
976 s = sys.stdin.buffer.read()
977 sys.stdout.buffer.write(s)
978 sys.stdout.buffer.write(b"line4\\n")
979 sys.stdout.buffer.write(b"line5\\r\\n")
980 sys.stderr.buffer.write(b"eline6\\r")
981 sys.stderr.buffer.write(b"eline7\\r\\nz")
982 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300983 stdin=subprocess.PIPE,
984 stderr=subprocess.PIPE,
985 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300986 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300987 self.addCleanup(p.stdout.close)
988 self.addCleanup(p.stderr.close)
989 (stdout, stderr) = p.communicate("line1\nline3\n")
990 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300991 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300992 # Python debug build push something like "[42442 refs]\n"
993 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300994 # Don't use assertStderrEqual because it strips CR and LF from output.
995 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300996
Andrew Svetlov82860712012-08-19 22:13:41 +0300997 def test_universal_newlines_communicate_encodings(self):
998 # Check that universal newlines mode works for various encodings,
999 # in particular for encodings in the UTF-16 and UTF-32 families.
1000 # See issue #15595.
1001 #
1002 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
1003 # without, and UTF-16 and UTF-32.
1004 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +03001005 code = ("import sys; "
1006 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
1007 encoding)
1008 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -07001009 # We set stdin to be non-None because, as of this writing,
1010 # a different code path is used when the number of pipes is
1011 # zero or one.
1012 popen = subprocess.Popen(args,
1013 stdin=subprocess.PIPE,
1014 stdout=subprocess.PIPE,
1015 encoding=encoding)
1016 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +03001017 self.assertEqual(stdout, '1\n2\n3\n4')
1018
Steve Dower050acae2016-09-06 20:16:17 -07001019 def test_communicate_errors(self):
1020 for errors, expected in [
1021 ('ignore', ''),
1022 ('replace', '\ufffd\ufffd'),
1023 ('surrogateescape', '\udc80\udc80'),
1024 ('backslashreplace', '\\x80\\x80'),
1025 ]:
1026 code = ("import sys; "
1027 r"sys.stdout.buffer.write(b'[\x80\x80]')")
1028 args = [sys.executable, '-c', code]
1029 # We set stdin to be non-None because, as of this writing,
1030 # a different code path is used when the number of pipes is
1031 # zero or one.
1032 popen = subprocess.Popen(args,
1033 stdin=subprocess.PIPE,
1034 stdout=subprocess.PIPE,
1035 encoding='utf-8',
1036 errors=errors)
1037 stdout, stderr = popen.communicate(input='')
1038 self.assertEqual(stdout, '[{}]'.format(expected))
1039
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001040 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +00001041 # Make sure we leak no resources
Victor Stinner937ee9e2018-06-26 02:11:06 +02001042 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +00001043 max_handles = 1026 # too much for most UNIX systems
1044 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +00001045 max_handles = 2050 # too much for (at least some) Windows setups
1046 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001047 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +00001048 try:
1049 for i in range(max_handles):
1050 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001051 tmpfile = os.path.join(tmpdir, support.TESTFN)
1052 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +00001053 except OSError as e:
1054 if e.errno != errno.EMFILE:
1055 raise
1056 break
1057 else:
1058 self.skipTest("failed to reach the file descriptor limit "
1059 "(tried %d)" % max_handles)
1060 # Close a couple of them (should be enough for a subprocess)
1061 for i in range(10):
1062 os.close(handles.pop())
1063 # Loop creating some subprocesses. If one of them leaks some fds,
1064 # the next loop iteration will fail by reaching the max fd limit.
1065 for i in range(15):
1066 p = subprocess.Popen([sys.executable, "-c",
1067 "import sys;"
1068 "sys.stdout.write(sys.stdin.read())"],
1069 stdin=subprocess.PIPE,
1070 stdout=subprocess.PIPE,
1071 stderr=subprocess.PIPE)
1072 data = p.communicate(b"lime")[0]
1073 self.assertEqual(data, b"lime")
1074 finally:
1075 for h in handles:
1076 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001077 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001078
1079 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001080 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
1081 '"a b c" d e')
1082 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
1083 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +00001084 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
1085 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001086 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
1087 'a\\\\\\b "de fg" h')
1088 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
1089 'a\\\\\\"b c d')
1090 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
1091 '"a\\\\b c" d e')
1092 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
1093 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001094 self.assertEqual(subprocess.list2cmdline(['ab', '']),
1095 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001096
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001097 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001098 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +02001099 "import os; os.read(0, 1)"],
1100 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001101 self.addCleanup(p.stdin.close)
1102 self.assertIsNone(p.poll())
1103 os.write(p.stdin.fileno(), b'A')
1104 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001105 # Subsequent invocations should just return the returncode
1106 self.assertEqual(p.poll(), 0)
1107
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001108 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001109 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001110 self.assertEqual(p.wait(), 0)
1111 # Subsequent invocations should just return the returncode
1112 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001113
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001114 def test_wait_timeout(self):
1115 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001116 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001117 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001118 p.wait(timeout=0.0001)
1119 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -04001120 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
1121 # time to start.
1122 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001123
Peter Astrand738131d2004-11-30 21:04:45 +00001124 def test_invalid_bufsize(self):
1125 # an invalid type of the bufsize argument should raise
1126 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001127 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +00001128 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001129
Guido van Rossum46a05a72007-06-07 21:56:45 +00001130 def test_bufsize_is_none(self):
1131 # bufsize=None should be the same as bufsize=0.
1132 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
1133 self.assertEqual(p.wait(), 0)
1134 # Again with keyword arg
1135 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
1136 self.assertEqual(p.wait(), 0)
1137
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001138 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1139 # subprocess may deadlock with bufsize=1, see issue #21332
1140 with subprocess.Popen([sys.executable, "-c", "import sys;"
1141 "sys.stdout.write(sys.stdin.readline());"
1142 "sys.stdout.flush()"],
1143 stdin=subprocess.PIPE,
1144 stdout=subprocess.PIPE,
1145 stderr=subprocess.DEVNULL,
1146 bufsize=1,
1147 universal_newlines=universal_newlines) as p:
1148 p.stdin.write(line) # expect that it flushes the line in text mode
1149 os.close(p.stdin.fileno()) # close it without flushing the buffer
1150 read_line = p.stdout.readline()
Segev Finer4d385172017-08-18 16:18:13 +03001151 with support.SuppressCrashReport():
1152 try:
1153 p.stdin.close()
1154 except OSError:
1155 pass
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001156 p.stdin = None
1157 self.assertEqual(p.returncode, 0)
1158 self.assertEqual(read_line, expected)
1159
1160 def test_bufsize_equal_one_text_mode(self):
1161 # line is flushed in text mode with bufsize=1.
1162 # we should get the full line in return
1163 line = "line\n"
1164 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1165
1166 def test_bufsize_equal_one_binary_mode(self):
1167 # line is not flushed in binary mode with bufsize=1.
1168 # we should get empty response
1169 line = b'line' + os.linesep.encode() # assume ascii-based locale
Alexey Izbysheva2670562018-10-20 03:22:31 +03001170 with self.assertWarnsRegex(RuntimeWarning, 'line buffering'):
1171 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001172
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001173 def test_leaking_fds_on_error(self):
1174 # see bug #5179: Popen leaks file descriptors to PIPEs if
1175 # the child fails to execute; this will eventually exhaust
1176 # the maximum number of open fds. 1024 seems a very common
1177 # value for that limit, but Windows has 2048, so we loop
1178 # 1024 times (each call leaked two fds).
1179 for i in range(1024):
Victor Stinnerb31206a2018-01-25 19:06:05 +01001180 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02001181 subprocess.Popen(NONEXISTING_CMD,
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001182 stdout=subprocess.PIPE,
1183 stderr=subprocess.PIPE)
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001184
Victor Stinner9a83f652017-08-21 23:51:31 +02001185 def test_nonexisting_with_pipes(self):
1186 # bpo-30121: Popen with pipes must close properly pipes on error.
1187 # Previously, os.close() was called with a Windows handle which is not
1188 # a valid file descriptor.
1189 #
1190 # Run the test in a subprocess to control how the CRT reports errors
1191 # and to get stderr content.
1192 try:
1193 import msvcrt
1194 msvcrt.CrtSetReportMode
1195 except (AttributeError, ImportError):
1196 self.skipTest("need msvcrt.CrtSetReportMode")
1197
1198 code = textwrap.dedent(f"""
1199 import msvcrt
1200 import subprocess
1201
1202 cmd = {NONEXISTING_CMD!r}
1203
1204 for report_type in [msvcrt.CRT_WARN,
1205 msvcrt.CRT_ERROR,
1206 msvcrt.CRT_ASSERT]:
1207 msvcrt.CrtSetReportMode(report_type, msvcrt.CRTDBG_MODE_FILE)
1208 msvcrt.CrtSetReportFile(report_type, msvcrt.CRTDBG_FILE_STDERR)
1209
1210 try:
Zachary Ware55376462018-02-19 14:02:38 -06001211 subprocess.Popen(cmd,
Victor Stinner9a83f652017-08-21 23:51:31 +02001212 stdout=subprocess.PIPE,
1213 stderr=subprocess.PIPE)
1214 except OSError:
1215 pass
1216 """)
1217 cmd = [sys.executable, "-c", code]
1218 proc = subprocess.Popen(cmd,
1219 stderr=subprocess.PIPE,
1220 universal_newlines=True)
1221 with proc:
1222 stderr = proc.communicate()[1]
1223 self.assertEqual(stderr, "")
1224 self.assertEqual(proc.returncode, 0)
1225
Antoine Pitroua8392712013-08-30 23:38:13 +02001226 def test_double_close_on_error(self):
1227 # Issue #18851
1228 fds = []
1229 def open_fds():
1230 for i in range(20):
1231 fds.extend(os.pipe())
1232 time.sleep(0.001)
1233 t = threading.Thread(target=open_fds)
1234 t.start()
1235 try:
1236 with self.assertRaises(EnvironmentError):
Victor Stinner9a83f652017-08-21 23:51:31 +02001237 subprocess.Popen(NONEXISTING_CMD,
Antoine Pitroua8392712013-08-30 23:38:13 +02001238 stdin=subprocess.PIPE,
1239 stdout=subprocess.PIPE,
1240 stderr=subprocess.PIPE)
1241 finally:
1242 t.join()
1243 exc = None
1244 for fd in fds:
1245 # If a double close occurred, some of those fds will
1246 # already have been closed by mistake, and os.close()
1247 # here will raise.
1248 try:
1249 os.close(fd)
1250 except OSError as e:
1251 exc = e
1252 if exc is not None:
1253 raise exc
1254
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001255 def test_threadsafe_wait(self):
1256 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1257 proc = subprocess.Popen([sys.executable, '-c',
1258 'import time; time.sleep(12)'])
1259 self.assertEqual(proc.returncode, None)
1260 results = []
1261
1262 def kill_proc_timer_thread():
1263 results.append(('thread-start-poll-result', proc.poll()))
1264 # terminate it from the thread and wait for the result.
1265 proc.kill()
1266 proc.wait()
1267 results.append(('thread-after-kill-and-wait', proc.returncode))
1268 # this wait should be a no-op given the above.
1269 proc.wait()
1270 results.append(('thread-after-second-wait', proc.returncode))
1271
1272 # This is a timing sensitive test, the failure mode is
1273 # triggered when both the main thread and this thread are in
1274 # the wait() call at once. The delay here is to allow the
1275 # main thread to most likely be blocked in its wait() call.
1276 t = threading.Timer(0.2, kill_proc_timer_thread)
1277 t.start()
1278
Victor Stinner937ee9e2018-06-26 02:11:06 +02001279 if mswindows:
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001280 expected_errorcode = 1
1281 else:
1282 # Should be -9 because of the proc.kill() from the thread.
1283 expected_errorcode = -9
1284
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001285 # Wait for the process to finish; the thread should kill it
1286 # long before it finishes on its own. Supplying a timeout
1287 # triggers a different code path for better coverage.
1288 proc.wait(timeout=20)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001289 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001290 msg="unexpected result in wait from main thread")
1291
1292 # This should be a no-op with no change in returncode.
1293 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001294 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001295 msg="unexpected result in second main wait.")
1296
1297 t.join()
1298 # Ensure that all of the thread results are as expected.
1299 # When a race condition occurs in wait(), the returncode could
1300 # be set by the wrong thread that doesn't actually have it
1301 # leading to an incorrect value.
1302 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001303 ('thread-after-kill-and-wait', expected_errorcode),
1304 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001305 results)
1306
Victor Stinnerb3693582010-05-21 20:13:12 +00001307 def test_issue8780(self):
1308 # Ensure that stdout is inherited from the parent
1309 # if stdout=PIPE is not used
1310 code = ';'.join((
1311 'import subprocess, sys',
1312 'retcode = subprocess.call('
1313 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1314 'assert retcode == 0'))
1315 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001316 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001317
Tim Goldenaf5ac392010-08-06 13:03:56 +00001318 def test_handles_closed_on_exception(self):
1319 # If CreateProcess exits with an error, ensure the
1320 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001321 ifhandle, ifname = tempfile.mkstemp()
1322 ofhandle, ofname = tempfile.mkstemp()
1323 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001324 try:
1325 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1326 stderr=efhandle)
1327 except OSError:
1328 os.close(ifhandle)
1329 os.remove(ifname)
1330 os.close(ofhandle)
1331 os.remove(ofname)
1332 os.close(efhandle)
1333 os.remove(efname)
1334 self.assertFalse(os.path.exists(ifname))
1335 self.assertFalse(os.path.exists(ofname))
1336 self.assertFalse(os.path.exists(efname))
1337
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001338 def test_communicate_epipe(self):
1339 # Issue 10963: communicate() should hide EPIPE
1340 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1341 stdin=subprocess.PIPE,
1342 stdout=subprocess.PIPE,
1343 stderr=subprocess.PIPE)
1344 self.addCleanup(p.stdout.close)
1345 self.addCleanup(p.stderr.close)
1346 self.addCleanup(p.stdin.close)
1347 p.communicate(b"x" * 2**20)
1348
1349 def test_communicate_epipe_only_stdin(self):
1350 # Issue 10963: communicate() should hide EPIPE
1351 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1352 stdin=subprocess.PIPE)
1353 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001354 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001355 p.communicate(b"x" * 2**20)
1356
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001357 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1358 "Requires signal.SIGUSR1")
1359 @unittest.skipUnless(hasattr(os, 'kill'),
1360 "Requires os.kill")
1361 @unittest.skipUnless(hasattr(os, 'getppid'),
1362 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001363 def test_communicate_eintr(self):
1364 # Issue #12493: communicate() should handle EINTR
1365 def handler(signum, frame):
1366 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001367 old_handler = signal.signal(signal.SIGUSR1, handler)
1368 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001369
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001370 args = [sys.executable, "-c",
1371 'import os, signal;'
1372 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001373 for stream in ('stdout', 'stderr'):
1374 kw = {stream: subprocess.PIPE}
1375 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001376 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001377 process.communicate()
1378
Tim Peterse718f612004-10-12 21:51:32 +00001379
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001380 # This test is Linux-ish specific for simplicity to at least have
1381 # some coverage. It is not a platform specific bug.
1382 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1383 "Linux specific")
1384 def test_failed_child_execute_fd_leak(self):
1385 """Test for the fork() failure fd leak reported in issue16327."""
1386 fd_directory = '/proc/%d/fd' % os.getpid()
1387 fds_before_popen = os.listdir(fd_directory)
1388 with self.assertRaises(PopenTestException):
1389 PopenExecuteChildRaises(
1390 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
1391 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1392
1393 # NOTE: This test doesn't verify that the real _execute_child
1394 # does not close the file descriptors itself on the way out
1395 # during an exception. Code inspection has confirmed that.
1396
1397 fds_after_exception = os.listdir(fd_directory)
1398 self.assertEqual(fds_before_popen, fds_after_exception)
1399
Victor Stinner937ee9e2018-06-26 02:11:06 +02001400 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001401 def test_file_not_found_includes_filename(self):
1402 with self.assertRaises(FileNotFoundError) as c:
1403 subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args'])
1404 self.assertEqual(c.exception.filename, '/opt/nonexistent_binary')
1405
Victor Stinner937ee9e2018-06-26 02:11:06 +02001406 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001407 def test_file_not_found_with_bad_cwd(self):
1408 with self.assertRaises(FileNotFoundError) as c:
1409 subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory')
1410 self.assertEqual(c.exception.filename, '/some/nonexistent/directory')
1411
Gregory P. Smith6e730002015-04-14 16:14:25 -07001412
1413class RunFuncTestCase(BaseTestCase):
1414 def run_python(self, code, **kwargs):
1415 """Run Python code in a subprocess using subprocess.run"""
1416 argv = [sys.executable, "-c", code]
1417 return subprocess.run(argv, **kwargs)
1418
1419 def test_returncode(self):
1420 # call() function with sequence argument
1421 cp = self.run_python("import sys; sys.exit(47)")
1422 self.assertEqual(cp.returncode, 47)
1423 with self.assertRaises(subprocess.CalledProcessError):
1424 cp.check_returncode()
1425
1426 def test_check(self):
1427 with self.assertRaises(subprocess.CalledProcessError) as c:
1428 self.run_python("import sys; sys.exit(47)", check=True)
1429 self.assertEqual(c.exception.returncode, 47)
1430
1431 def test_check_zero(self):
1432 # check_returncode shouldn't raise when returncode is zero
1433 cp = self.run_python("import sys; sys.exit(0)", check=True)
1434 self.assertEqual(cp.returncode, 0)
1435
1436 def test_timeout(self):
1437 # run() function with timeout argument; we want to test that the child
1438 # process gets killed when the timeout expires. If the child isn't
1439 # killed, this call will deadlock since subprocess.run waits for the
1440 # child.
1441 with self.assertRaises(subprocess.TimeoutExpired):
1442 self.run_python("while True: pass", timeout=0.0001)
1443
1444 def test_capture_stdout(self):
1445 # capture stdout with zero return code
1446 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1447 self.assertIn(b'BDFL', cp.stdout)
1448
1449 def test_capture_stderr(self):
1450 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1451 stderr=subprocess.PIPE)
1452 self.assertIn(b'BDFL', cp.stderr)
1453
1454 def test_check_output_stdin_arg(self):
1455 # run() can be called with stdin set to a file
1456 tf = tempfile.TemporaryFile()
1457 self.addCleanup(tf.close)
1458 tf.write(b'pear')
1459 tf.seek(0)
1460 cp = self.run_python(
1461 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1462 stdin=tf, stdout=subprocess.PIPE)
1463 self.assertIn(b'PEAR', cp.stdout)
1464
1465 def test_check_output_input_arg(self):
1466 # check_output() can be called with input set to a string
1467 cp = self.run_python(
1468 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1469 input=b'pear', stdout=subprocess.PIPE)
1470 self.assertIn(b'PEAR', cp.stdout)
1471
1472 def test_check_output_stdin_with_input_arg(self):
1473 # run() refuses to accept 'stdin' with 'input'
1474 tf = tempfile.TemporaryFile()
1475 self.addCleanup(tf.close)
1476 tf.write(b'pear')
1477 tf.seek(0)
1478 with self.assertRaises(ValueError,
1479 msg="Expected ValueError when stdin and input args supplied.") as c:
1480 output = self.run_python("print('will not be run')",
1481 stdin=tf, input=b'hare')
1482 self.assertIn('stdin', c.exception.args[0])
1483 self.assertIn('input', c.exception.args[0])
1484
1485 def test_check_output_timeout(self):
1486 with self.assertRaises(subprocess.TimeoutExpired) as c:
1487 cp = self.run_python((
1488 "import sys, time\n"
1489 "sys.stdout.write('BDFL')\n"
1490 "sys.stdout.flush()\n"
1491 "time.sleep(3600)"),
1492 # Some heavily loaded buildbots (sparc Debian 3.x) require
1493 # this much time to start and print.
1494 timeout=3, stdout=subprocess.PIPE)
1495 self.assertEqual(c.exception.output, b'BDFL')
1496 # output is aliased to stdout
1497 self.assertEqual(c.exception.stdout, b'BDFL')
1498
1499 def test_run_kwargs(self):
1500 newenv = os.environ.copy()
1501 newenv["FRUIT"] = "banana"
1502 cp = self.run_python(('import sys, os;'
1503 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1504 env=newenv)
1505 self.assertEqual(cp.returncode, 33)
1506
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001507 def test_run_with_pathlike_path(self):
1508 # bpo-31961: test run(pathlike_object)
1509 # the name of a command that can be run without
1510 # any argumenets that exit fast
1511 prog = 'tree.com' if mswindows else 'ls'
1512 path = shutil.which(prog)
1513 if path is None:
1514 self.skipTest(f'{prog} required for this test')
1515 path = FakePath(path)
1516 res = subprocess.run(path, stdout=subprocess.DEVNULL)
1517 self.assertEqual(res.returncode, 0)
1518 with self.assertRaises(TypeError):
1519 subprocess.run(path, stdout=subprocess.DEVNULL, shell=True)
1520
1521 def test_run_with_bytes_path_and_arguments(self):
1522 # bpo-31961: test run([bytes_object, b'additional arguments'])
1523 path = os.fsencode(sys.executable)
1524 args = [path, '-c', b'import sys; sys.exit(57)']
1525 res = subprocess.run(args)
1526 self.assertEqual(res.returncode, 57)
1527
1528 def test_run_with_pathlike_path_and_arguments(self):
1529 # bpo-31961: test run([pathlike_object, 'additional arguments'])
1530 path = FakePath(sys.executable)
1531 args = [path, '-c', 'import sys; sys.exit(57)']
1532 res = subprocess.run(args)
1533 self.assertEqual(res.returncode, 57)
1534
Bo Baylesce0f33d2018-01-30 00:40:39 -06001535 def test_capture_output(self):
1536 cp = self.run_python(("import sys;"
1537 "sys.stdout.write('BDFL'); "
1538 "sys.stderr.write('FLUFL')"),
1539 capture_output=True)
1540 self.assertIn(b'BDFL', cp.stdout)
1541 self.assertIn(b'FLUFL', cp.stderr)
1542
1543 def test_stdout_with_capture_output_arg(self):
1544 # run() refuses to accept 'stdout' with 'capture_output'
1545 tf = tempfile.TemporaryFile()
1546 self.addCleanup(tf.close)
1547 with self.assertRaises(ValueError,
1548 msg=("Expected ValueError when stdout and capture_output "
1549 "args supplied.")) as c:
1550 output = self.run_python("print('will not be run')",
1551 capture_output=True, stdout=tf)
1552 self.assertIn('stdout', c.exception.args[0])
1553 self.assertIn('capture_output', c.exception.args[0])
1554
1555 def test_stderr_with_capture_output_arg(self):
1556 # run() refuses to accept 'stderr' with 'capture_output'
1557 tf = tempfile.TemporaryFile()
1558 self.addCleanup(tf.close)
1559 with self.assertRaises(ValueError,
1560 msg=("Expected ValueError when stderr and capture_output "
1561 "args supplied.")) as c:
1562 output = self.run_python("print('will not be run')",
1563 capture_output=True, stderr=tf)
1564 self.assertIn('stderr', c.exception.args[0])
1565 self.assertIn('capture_output', c.exception.args[0])
1566
Gregory P. Smith6e730002015-04-14 16:14:25 -07001567
Victor Stinner937ee9e2018-06-26 02:11:06 +02001568@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001569class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001570
Gregory P. Smith5591b022012-10-10 03:34:47 -07001571 def setUp(self):
1572 super().setUp()
1573 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1574
1575 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001576 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001577 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001578 except OSError as e:
1579 # This avoids hard coding the errno value or the OS perror()
1580 # string and instead capture the exception that we want to see
1581 # below for comparison.
1582 desired_exception = e
1583 else:
Martin Pantereb995702016-07-28 01:11:04 +00001584 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001585 self._nonexistent_dir)
1586 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001587
Gregory P. Smith5591b022012-10-10 03:34:47 -07001588 def test_exception_cwd(self):
1589 """Test error in the child raised in the parent for a bad cwd."""
1590 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001591 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001592 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001593 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001594 except OSError as e:
1595 # Test that the child process chdir failure actually makes
1596 # it up to the parent process as the correct exception.
1597 self.assertEqual(desired_exception.errno, e.errno)
1598 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001599 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001600 else:
1601 self.fail("Expected OSError: %s" % desired_exception)
1602
Gregory P. Smith5591b022012-10-10 03:34:47 -07001603 def test_exception_bad_executable(self):
1604 """Test error in the child raised in the parent for a bad executable."""
1605 desired_exception = self._get_chdir_exception()
1606 try:
1607 p = subprocess.Popen([sys.executable, "-c", ""],
1608 executable=self._nonexistent_dir)
1609 except OSError as e:
1610 # Test that the child process exec failure actually makes
1611 # it up to the parent process as the correct exception.
1612 self.assertEqual(desired_exception.errno, e.errno)
1613 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001614 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001615 else:
1616 self.fail("Expected OSError: %s" % desired_exception)
1617
1618 def test_exception_bad_args_0(self):
1619 """Test error in the child raised in the parent for a bad args[0]."""
1620 desired_exception = self._get_chdir_exception()
1621 try:
1622 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1623 except OSError as e:
1624 # Test that the child process exec failure actually makes
1625 # it up to the parent process as the correct exception.
1626 self.assertEqual(desired_exception.errno, e.errno)
1627 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001628 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001629 else:
1630 self.fail("Expected OSError: %s" % desired_exception)
1631
Ammar Askar3fc499b2017-09-06 02:41:30 -04001632 # We mock the __del__ method for Popen in the next two tests
1633 # because it does cleanup based on the pid returned by fork_exec
1634 # along with issuing a resource warning if it still exists. Since
1635 # we don't actually spawn a process in these tests we can forego
1636 # the destructor. An alternative would be to set _child_created to
1637 # False before the destructor is called but there is no easy way
1638 # to do that
1639 class PopenNoDestructor(subprocess.Popen):
1640 def __del__(self):
1641 pass
1642
1643 @mock.patch("subprocess._posixsubprocess.fork_exec")
1644 def test_exception_errpipe_normal(self, fork_exec):
1645 """Test error passing done through errpipe_write in the good case"""
1646 def proper_error(*args):
1647 errpipe_write = args[13]
1648 # Write the hex for the error code EISDIR: 'is a directory'
1649 err_code = '{:x}'.format(errno.EISDIR).encode()
1650 os.write(errpipe_write, b"OSError:" + err_code + b":")
1651 return 0
1652
1653 fork_exec.side_effect = proper_error
1654
Victor Stinner11045c92017-10-05 06:32:53 -07001655 with mock.patch("subprocess.os.waitpid",
1656 side_effect=ChildProcessError):
1657 with self.assertRaises(IsADirectoryError):
1658 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001659
1660 @mock.patch("subprocess._posixsubprocess.fork_exec")
1661 def test_exception_errpipe_bad_data(self, fork_exec):
1662 """Test error passing done through errpipe_write where its not
1663 in the expected format"""
1664 error_data = b"\xFF\x00\xDE\xAD"
1665 def bad_error(*args):
1666 errpipe_write = args[13]
1667 # Anything can be in the pipe, no assumptions should
1668 # be made about its encoding, so we'll write some
1669 # arbitrary hex bytes to test it out
1670 os.write(errpipe_write, error_data)
1671 return 0
1672
1673 fork_exec.side_effect = bad_error
1674
Victor Stinner11045c92017-10-05 06:32:53 -07001675 with mock.patch("subprocess.os.waitpid",
1676 side_effect=ChildProcessError):
1677 with self.assertRaises(subprocess.SubprocessError) as e:
1678 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001679
1680 self.assertIn(repr(error_data), str(e.exception))
1681
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001682 @unittest.skipIf(not os.path.exists('/proc/self/status'),
1683 "need /proc/self/status")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001684 def test_restore_signals(self):
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001685 # Blindly assume that cat exists on systems with /proc/self/status...
1686 default_proc_status = subprocess.check_output(
1687 ['cat', '/proc/self/status'],
1688 restore_signals=False)
1689 for line in default_proc_status.splitlines():
1690 if line.startswith(b'SigIgn'):
1691 default_sig_ign_mask = line
1692 break
1693 else:
1694 self.skipTest("SigIgn not found in /proc/self/status.")
1695 restored_proc_status = subprocess.check_output(
1696 ['cat', '/proc/self/status'],
1697 restore_signals=True)
1698 for line in restored_proc_status.splitlines():
1699 if line.startswith(b'SigIgn'):
1700 restored_sig_ign_mask = line
1701 break
1702 self.assertNotEqual(default_sig_ign_mask, restored_sig_ign_mask,
1703 msg="restore_signals=True should've unblocked "
1704 "SIGPIPE and friends.")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001705
1706 def test_start_new_session(self):
1707 # For code coverage of calling setsid(). We don't care if we get an
1708 # EPERM error from it depending on the test execution environment, that
1709 # still indicates that it was called.
1710 try:
1711 output = subprocess.check_output(
Victor Stinner58840432019-06-14 19:31:43 +02001712 [sys.executable, "-c", "import os; print(os.getsid(0))"],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001713 start_new_session=True)
1714 except OSError as e:
1715 if e.errno != errno.EPERM:
1716 raise
1717 else:
Victor Stinner58840432019-06-14 19:31:43 +02001718 parent_sid = os.getsid(0)
1719 child_sid = int(output)
1720 self.assertNotEqual(parent_sid, child_sid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001721
1722 def test_run_abort(self):
1723 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001724 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001725 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001726 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001727 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001728 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001729
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001730 def test_CalledProcessError_str_signal(self):
1731 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
1732 error_string = str(err)
1733 # We're relying on the repr() of the signal.Signals intenum to provide
1734 # the word signal, the signal name and the numeric value.
1735 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00001736 # We're not being specific about the signal name as some signals have
1737 # multiple names and which name is revealed can vary.
1738 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001739 self.assertIn(str(signal.SIGABRT), error_string)
1740
1741 def test_CalledProcessError_str_unknown_signal(self):
1742 err = subprocess.CalledProcessError(-9876543, "fake cmd")
1743 error_string = str(err)
1744 self.assertIn("unknown signal 9876543.", error_string)
1745
1746 def test_CalledProcessError_str_non_zero(self):
1747 err = subprocess.CalledProcessError(2, "fake cmd")
1748 error_string = str(err)
1749 self.assertIn("non-zero exit status 2.", error_string)
1750
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001751 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001752 # DISCLAIMER: Setting environment variables is *not* a good use
1753 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001754 p = subprocess.Popen([sys.executable, "-c",
1755 'import sys,os;'
1756 'sys.stdout.write(os.getenv("FRUIT"))'],
1757 stdout=subprocess.PIPE,
1758 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02001759 with p:
1760 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001761
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001762 def test_preexec_exception(self):
1763 def raise_it():
1764 raise ValueError("What if two swallows carried a coconut?")
1765 try:
1766 p = subprocess.Popen([sys.executable, "-c", ""],
1767 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001768 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001769 self.assertTrue(
1770 subprocess._posixsubprocess,
1771 "Expected a ValueError from the preexec_fn")
1772 except ValueError as e:
1773 self.assertIn("coconut", e.args[0])
1774 else:
1775 self.fail("Exception raised by preexec_fn did not make it "
1776 "to the parent process.")
1777
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001778 class _TestExecuteChildPopen(subprocess.Popen):
1779 """Used to test behavior at the end of _execute_child."""
1780 def __init__(self, testcase, *args, **kwargs):
1781 self._testcase = testcase
1782 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001783
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001784 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001785 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001786 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001787 finally:
1788 # Open a bunch of file descriptors and verify that
1789 # none of them are the same as the ones the Popen
1790 # instance is using for stdin/stdout/stderr.
1791 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1792 for _ in range(8)]
1793 try:
1794 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001795 self._testcase.assertNotIn(
1796 fd, (self.stdin.fileno(), self.stdout.fileno(),
1797 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001798 msg="At least one fd was closed early.")
1799 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01001800 for fd in devzero_fds:
1801 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001802
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001803 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1804 def test_preexec_errpipe_does_not_double_close_pipes(self):
1805 """Issue16140: Don't double close pipes on preexec error."""
1806
1807 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08001808 raise subprocess.SubprocessError(
1809 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001810
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08001811 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001812 self._TestExecuteChildPopen(
1813 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001814 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1815 stderr=subprocess.PIPE, preexec_fn=raise_it)
1816
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001817 def test_preexec_gc_module_failure(self):
1818 # This tests the code that disables garbage collection if the child
1819 # process will execute any Python.
1820 def raise_runtime_error():
1821 raise RuntimeError("this shouldn't escape")
1822 enabled = gc.isenabled()
1823 orig_gc_disable = gc.disable
1824 orig_gc_isenabled = gc.isenabled
1825 try:
1826 gc.disable()
1827 self.assertFalse(gc.isenabled())
1828 subprocess.call([sys.executable, '-c', ''],
1829 preexec_fn=lambda: None)
1830 self.assertFalse(gc.isenabled(),
1831 "Popen enabled gc when it shouldn't.")
1832
1833 gc.enable()
1834 self.assertTrue(gc.isenabled())
1835 subprocess.call([sys.executable, '-c', ''],
1836 preexec_fn=lambda: None)
1837 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1838
1839 gc.disable = raise_runtime_error
1840 self.assertRaises(RuntimeError, subprocess.Popen,
1841 [sys.executable, '-c', ''],
1842 preexec_fn=lambda: None)
1843
1844 del gc.isenabled # force an AttributeError
1845 self.assertRaises(AttributeError, subprocess.Popen,
1846 [sys.executable, '-c', ''],
1847 preexec_fn=lambda: None)
1848 finally:
1849 gc.disable = orig_gc_disable
1850 gc.isenabled = orig_gc_isenabled
1851 if not enabled:
1852 gc.disable()
1853
Martin Panterf7fdbda2015-12-05 09:51:52 +00001854 @unittest.skipIf(
1855 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00001856 def test_preexec_fork_failure(self):
1857 # The internal code did not preserve the previous exception when
1858 # re-enabling garbage collection
1859 try:
1860 from resource import getrlimit, setrlimit, RLIMIT_NPROC
1861 except ImportError as err:
1862 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
1863 limits = getrlimit(RLIMIT_NPROC)
1864 [_, hard] = limits
1865 setrlimit(RLIMIT_NPROC, (0, hard))
1866 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00001867 try:
Martin Panterafdd5132015-11-30 02:21:41 +00001868 subprocess.call([sys.executable, '-c', ''],
1869 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00001870 except BlockingIOError:
1871 # Forking should raise EAGAIN, translated to BlockingIOError
1872 pass
1873 else:
1874 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00001875
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001876 def test_args_string(self):
1877 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03001878 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001879 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001880 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001881 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001882 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1883 sys.executable)
1884 os.chmod(fname, 0o700)
1885 p = subprocess.Popen(fname)
1886 p.wait()
1887 os.remove(fname)
1888 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001889
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001890 def test_invalid_args(self):
1891 # invalid arguments should raise ValueError
1892 self.assertRaises(ValueError, subprocess.call,
1893 [sys.executable, "-c",
1894 "import sys; sys.exit(47)"],
1895 startupinfo=47)
1896 self.assertRaises(ValueError, subprocess.call,
1897 [sys.executable, "-c",
1898 "import sys; sys.exit(47)"],
1899 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001900
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001901 def test_shell_sequence(self):
1902 # Run command through the shell (sequence)
1903 newenv = os.environ.copy()
1904 newenv["FRUIT"] = "apple"
1905 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1906 stdout=subprocess.PIPE,
1907 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001908 with p:
1909 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001910
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001911 def test_shell_string(self):
1912 # Run command through the shell (string)
1913 newenv = os.environ.copy()
1914 newenv["FRUIT"] = "apple"
1915 p = subprocess.Popen("echo $FRUIT", shell=1,
1916 stdout=subprocess.PIPE,
1917 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001918 with p:
1919 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001920
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001921 def test_call_string(self):
1922 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03001923 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001924 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001925 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001926 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001927 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1928 sys.executable)
1929 os.chmod(fname, 0o700)
1930 rc = subprocess.call(fname)
1931 os.remove(fname)
1932 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001933
Stefan Krah9542cc62010-07-19 14:20:53 +00001934 def test_specific_shell(self):
1935 # Issue #9265: Incorrect name passed as arg[0].
1936 shells = []
1937 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1938 for name in ['bash', 'ksh']:
1939 sh = os.path.join(prefix, name)
1940 if os.path.isfile(sh):
1941 shells.append(sh)
1942 if not shells: # Will probably work for any shell but csh.
1943 self.skipTest("bash or ksh required for this test")
1944 sh = '/bin/sh'
1945 if os.path.isfile(sh) and not os.path.islink(sh):
1946 # Test will fail if /bin/sh is a symlink to csh.
1947 shells.append(sh)
1948 for sh in shells:
1949 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1950 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02001951 with p:
1952 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00001953
Florent Xicluna4886d242010-03-08 13:27:26 +00001954 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001955 # Do not inherit file handles from the parent.
1956 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07001957 # Also set the SIGINT handler to the default to make sure it's not
1958 # being ignored (some tests rely on that.)
1959 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
1960 try:
1961 p = subprocess.Popen([sys.executable, "-c", """if 1:
1962 import sys, time
1963 sys.stdout.write('x\\n')
1964 sys.stdout.flush()
1965 time.sleep(30)
1966 """],
1967 close_fds=True,
1968 stdin=subprocess.PIPE,
1969 stdout=subprocess.PIPE,
1970 stderr=subprocess.PIPE)
1971 finally:
1972 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001973 # Wait for the interpreter to be completely initialized before
1974 # sending any signal.
1975 p.stdout.read(1)
1976 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001977 return p
1978
Charles-François Natali53221e32013-01-12 16:52:20 +01001979 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1980 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001981 def _kill_dead_process(self, method, *args):
1982 # Do not inherit file handles from the parent.
1983 # It should fix failures on some platforms.
1984 p = subprocess.Popen([sys.executable, "-c", """if 1:
1985 import sys, time
1986 sys.stdout.write('x\\n')
1987 sys.stdout.flush()
1988 """],
1989 close_fds=True,
1990 stdin=subprocess.PIPE,
1991 stdout=subprocess.PIPE,
1992 stderr=subprocess.PIPE)
1993 # Wait for the interpreter to be completely initialized before
1994 # sending any signal.
1995 p.stdout.read(1)
1996 # The process should end after this
1997 time.sleep(1)
1998 # This shouldn't raise even though the child is now dead
1999 getattr(p, method)(*args)
2000 p.communicate()
2001
Florent Xicluna4886d242010-03-08 13:27:26 +00002002 def test_send_signal(self):
2003 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00002004 _, stderr = p.communicate()
2005 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002006 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00002007
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002008 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002009 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00002010 _, stderr = p.communicate()
2011 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002012 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00002013
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002014 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002015 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00002016 _, stderr = p.communicate()
2017 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002018 self.assertEqual(p.wait(), -signal.SIGTERM)
2019
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002020 def test_send_signal_dead(self):
2021 # Sending a signal to a dead process
2022 self._kill_dead_process('send_signal', signal.SIGINT)
2023
2024 def test_kill_dead(self):
2025 # Killing a dead process
2026 self._kill_dead_process('kill')
2027
2028 def test_terminate_dead(self):
2029 # Terminating a dead process
2030 self._kill_dead_process('terminate')
2031
Victor Stinnerdaf45552013-08-28 00:53:59 +02002032 def _save_fds(self, save_fds):
2033 fds = []
2034 for fd in save_fds:
2035 inheritable = os.get_inheritable(fd)
2036 saved = os.dup(fd)
2037 fds.append((fd, saved, inheritable))
2038 return fds
2039
2040 def _restore_fds(self, fds):
2041 for fd, saved, inheritable in fds:
2042 os.dup2(saved, fd, inheritable=inheritable)
2043 os.close(saved)
2044
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002045 def check_close_std_fds(self, fds):
2046 # Issue #9905: test that subprocess pipes still work properly with
2047 # some standard fds closed
2048 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02002049 saved_fds = self._save_fds(fds)
2050 for fd, saved, inheritable in saved_fds:
2051 if fd == 0:
2052 stdin = saved
2053 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002054 try:
2055 for fd in fds:
2056 os.close(fd)
2057 out, err = subprocess.Popen([sys.executable, "-c",
2058 'import sys;'
2059 'sys.stdout.write("apple");'
2060 'sys.stdout.flush();'
2061 'sys.stderr.write("orange")'],
2062 stdin=stdin,
2063 stdout=subprocess.PIPE,
2064 stderr=subprocess.PIPE).communicate()
2065 err = support.strip_python_stderr(err)
2066 self.assertEqual((out, err), (b'apple', b'orange'))
2067 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002068 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002069
2070 def test_close_fd_0(self):
2071 self.check_close_std_fds([0])
2072
2073 def test_close_fd_1(self):
2074 self.check_close_std_fds([1])
2075
2076 def test_close_fd_2(self):
2077 self.check_close_std_fds([2])
2078
2079 def test_close_fds_0_1(self):
2080 self.check_close_std_fds([0, 1])
2081
2082 def test_close_fds_0_2(self):
2083 self.check_close_std_fds([0, 2])
2084
2085 def test_close_fds_1_2(self):
2086 self.check_close_std_fds([1, 2])
2087
2088 def test_close_fds_0_1_2(self):
2089 # Issue #10806: test that subprocess pipes still work properly with
2090 # all standard fds closed.
2091 self.check_close_std_fds([0, 1, 2])
2092
Gregory P. Smith53dd8162013-12-01 16:03:24 -08002093 def test_small_errpipe_write_fd(self):
2094 """Issue #15798: Popen should work when stdio fds are available."""
2095 new_stdin = os.dup(0)
2096 new_stdout = os.dup(1)
2097 try:
2098 os.close(0)
2099 os.close(1)
2100
2101 # Side test: if errpipe_write fails to have its CLOEXEC
2102 # flag set this should cause the parent to think the exec
2103 # failed. Extremely unlikely: everyone supports CLOEXEC.
2104 subprocess.Popen([
2105 sys.executable, "-c",
2106 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
2107 finally:
2108 # Restore original stdin and stdout
2109 os.dup2(new_stdin, 0)
2110 os.dup2(new_stdout, 1)
2111 os.close(new_stdin)
2112 os.close(new_stdout)
2113
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002114 def test_remapping_std_fds(self):
2115 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002116 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002117 try:
2118 temp_fds = [fd for fd, fname in temps]
2119
2120 # unlink the files -- we won't need to reopen them
2121 for fd, fname in temps:
2122 os.unlink(fname)
2123
2124 # write some data to what will become stdin, and rewind
2125 os.write(temp_fds[1], b"STDIN")
2126 os.lseek(temp_fds[1], 0, 0)
2127
2128 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02002129 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002130 try:
2131 # duplicate the file objects over the standard fd's
2132 for fd, temp_fd in enumerate(temp_fds):
2133 os.dup2(temp_fd, fd)
2134
2135 # now use those files in the "wrong" order, so that subprocess
2136 # has to rearrange them in the child
2137 p = subprocess.Popen([sys.executable, "-c",
2138 'import sys; got = sys.stdin.read();'
2139 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2140 stdin=temp_fds[1],
2141 stdout=temp_fds[2],
2142 stderr=temp_fds[0])
2143 p.wait()
2144 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002145 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002146
2147 for fd in temp_fds:
2148 os.lseek(fd, 0, 0)
2149
2150 out = os.read(temp_fds[2], 1024)
2151 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
2152 self.assertEqual(out, b"got STDIN")
2153 self.assertEqual(err, b"err")
2154
2155 finally:
2156 for fd in temp_fds:
2157 os.close(fd)
2158
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002159 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
2160 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002161 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002162 temp_fds = [fd for fd, fname in temps]
2163 try:
2164 # unlink the files -- we won't need to reopen them
2165 for fd, fname in temps:
2166 os.unlink(fname)
2167
2168 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02002169 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002170 try:
2171 # duplicate the temp files over the standard fd's 0, 1, 2
2172 for fd, temp_fd in enumerate(temp_fds):
2173 os.dup2(temp_fd, fd)
2174
2175 # write some data to what will become stdin, and rewind
2176 os.write(stdin_no, b"STDIN")
2177 os.lseek(stdin_no, 0, 0)
2178
2179 # now use those files in the given order, so that subprocess
2180 # has to rearrange them in the child
2181 p = subprocess.Popen([sys.executable, "-c",
2182 'import sys; got = sys.stdin.read();'
2183 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2184 stdin=stdin_no,
2185 stdout=stdout_no,
2186 stderr=stderr_no)
2187 p.wait()
2188
2189 for fd in temp_fds:
2190 os.lseek(fd, 0, 0)
2191
2192 out = os.read(stdout_no, 1024)
2193 err = support.strip_python_stderr(os.read(stderr_no, 1024))
2194 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002195 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002196
2197 self.assertEqual(out, b"got STDIN")
2198 self.assertEqual(err, b"err")
2199
2200 finally:
2201 for fd in temp_fds:
2202 os.close(fd)
2203
2204 # When duping fds, if there arises a situation where one of the fds is
2205 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
2206 # This tests all combinations of this.
2207 def test_swap_fds(self):
2208 self.check_swap_fds(0, 1, 2)
2209 self.check_swap_fds(0, 2, 1)
2210 self.check_swap_fds(1, 0, 2)
2211 self.check_swap_fds(1, 2, 0)
2212 self.check_swap_fds(2, 0, 1)
2213 self.check_swap_fds(2, 1, 0)
2214
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +03002215 def _check_swap_std_fds_with_one_closed(self, from_fds, to_fds):
2216 saved_fds = self._save_fds(range(3))
2217 try:
2218 for from_fd in from_fds:
2219 with tempfile.TemporaryFile() as f:
2220 os.dup2(f.fileno(), from_fd)
2221
2222 fd_to_close = (set(range(3)) - set(from_fds)).pop()
2223 os.close(fd_to_close)
2224
2225 arg_names = ['stdin', 'stdout', 'stderr']
2226 kwargs = {}
2227 for from_fd, to_fd in zip(from_fds, to_fds):
2228 kwargs[arg_names[to_fd]] = from_fd
2229
2230 code = textwrap.dedent(r'''
2231 import os, sys
2232 skipped_fd = int(sys.argv[1])
2233 for fd in range(3):
2234 if fd != skipped_fd:
2235 os.write(fd, str(fd).encode('ascii'))
2236 ''')
2237
2238 skipped_fd = (set(range(3)) - set(to_fds)).pop()
2239
2240 rc = subprocess.call([sys.executable, '-c', code, str(skipped_fd)],
2241 **kwargs)
2242 self.assertEqual(rc, 0)
2243
2244 for from_fd, to_fd in zip(from_fds, to_fds):
2245 os.lseek(from_fd, 0, os.SEEK_SET)
2246 read_bytes = os.read(from_fd, 1024)
2247 read_fds = list(map(int, read_bytes.decode('ascii')))
2248 msg = textwrap.dedent(f"""
2249 When testing {from_fds} to {to_fds} redirection,
2250 parent descriptor {from_fd} got redirected
2251 to descriptor(s) {read_fds} instead of descriptor {to_fd}.
2252 """)
2253 self.assertEqual([to_fd], read_fds, msg)
2254 finally:
2255 self._restore_fds(saved_fds)
2256
2257 # Check that subprocess can remap std fds correctly even
2258 # if one of them is closed (#32844).
2259 def test_swap_std_fds_with_one_closed(self):
2260 for from_fds in itertools.combinations(range(3), 2):
2261 for to_fds in itertools.permutations(range(3), 2):
2262 self._check_swap_std_fds_with_one_closed(from_fds, to_fds)
2263
Victor Stinner13bb71c2010-04-23 21:41:56 +00002264 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00002265 def prepare():
2266 raise ValueError("surrogate:\uDCff")
2267
2268 try:
2269 subprocess.call(
2270 [sys.executable, "-c", "pass"],
2271 preexec_fn=prepare)
2272 except ValueError as err:
2273 # Pure Python implementations keeps the message
2274 self.assertIsNone(subprocess._posixsubprocess)
2275 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002276 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00002277 # _posixsubprocess uses a default message
2278 self.assertIsNotNone(subprocess._posixsubprocess)
2279 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
2280 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002281 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00002282
Victor Stinner13bb71c2010-04-23 21:41:56 +00002283 def test_undecodable_env(self):
2284 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01002285 encoded_value = value.encode("ascii", "surrogateescape")
2286
Victor Stinner13bb71c2010-04-23 21:41:56 +00002287 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002288 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002289 env = os.environ.copy()
2290 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01002291 # Use C locale to get ASCII for the locale encoding to force
Michael Felt89d79b12018-08-26 19:29:36 +02002292 # surrogate-escaping of \xFF in the child process
Victor Stinnerebc78d22010-10-14 10:38:17 +00002293 env['LC_ALL'] = 'C'
Michael Felt89d79b12018-08-26 19:29:36 +02002294 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002295 stdout = subprocess.check_output(
2296 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002297 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002298 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002299 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002300
2301 # test bytes
2302 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002303 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002304 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01002305 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002306 stdout = subprocess.check_output(
2307 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002308 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002309 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002310 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002311
Victor Stinnerb745a742010-05-18 17:17:23 +00002312 def test_bytes_program(self):
2313 abs_program = os.fsencode(sys.executable)
2314 path, program = os.path.split(sys.executable)
2315 program = os.fsencode(program)
2316
2317 # absolute bytes path
2318 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00002319 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002320
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002321 # absolute bytes path as a string
2322 cmd = b"'" + abs_program + b"' -c pass"
2323 exitcode = subprocess.call(cmd, shell=True)
2324 self.assertEqual(exitcode, 0)
2325
Victor Stinnerb745a742010-05-18 17:17:23 +00002326 # bytes program, unicode PATH
2327 env = os.environ.copy()
2328 env["PATH"] = path
2329 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002330 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002331
2332 # bytes program, bytes PATH
2333 envb = os.environb.copy()
2334 envb[b"PATH"] = os.fsencode(path)
2335 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002336 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002337
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002338 def test_pipe_cloexec(self):
2339 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2340 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2341
2342 p1 = subprocess.Popen([sys.executable, sleeper],
2343 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2344 stderr=subprocess.PIPE, close_fds=False)
2345
2346 self.addCleanup(p1.communicate, b'')
2347
2348 p2 = subprocess.Popen([sys.executable, fd_status],
2349 stdout=subprocess.PIPE, close_fds=False)
2350
2351 output, error = p2.communicate()
2352 result_fds = set(map(int, output.split(b',')))
2353 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2354 p1.stderr.fileno()])
2355
2356 self.assertFalse(result_fds & unwanted_fds,
2357 "Expected no fds from %r to be open in child, "
2358 "found %r" %
2359 (unwanted_fds, result_fds & unwanted_fds))
2360
2361 def test_pipe_cloexec_real_tools(self):
2362 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2363 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2364
2365 subdata = b'zxcvbn'
2366 data = subdata * 4 + b'\n'
2367
2368 p1 = subprocess.Popen([sys.executable, qcat],
2369 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2370 close_fds=False)
2371
2372 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2373 stdin=p1.stdout, stdout=subprocess.PIPE,
2374 close_fds=False)
2375
2376 self.addCleanup(p1.wait)
2377 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002378 def kill_p1():
2379 try:
2380 p1.terminate()
2381 except ProcessLookupError:
2382 pass
2383 def kill_p2():
2384 try:
2385 p2.terminate()
2386 except ProcessLookupError:
2387 pass
2388 self.addCleanup(kill_p1)
2389 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002390
2391 p1.stdin.write(data)
2392 p1.stdin.close()
2393
2394 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2395
2396 self.assertTrue(readfiles, "The child hung")
2397 self.assertEqual(p2.stdout.read(), data)
2398
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002399 p1.stdout.close()
2400 p2.stdout.close()
2401
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002402 def test_close_fds(self):
2403 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2404
2405 fds = os.pipe()
2406 self.addCleanup(os.close, fds[0])
2407 self.addCleanup(os.close, fds[1])
2408
2409 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002410 # add a bunch more fds
2411 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002412 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002413 self.addCleanup(os.close, fd)
2414 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002415
Victor Stinnerdaf45552013-08-28 00:53:59 +02002416 for fd in open_fds:
2417 os.set_inheritable(fd, True)
2418
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002419 p = subprocess.Popen([sys.executable, fd_status],
2420 stdout=subprocess.PIPE, close_fds=False)
2421 output, ignored = p.communicate()
2422 remaining_fds = set(map(int, output.split(b',')))
2423
2424 self.assertEqual(remaining_fds & open_fds, open_fds,
2425 "Some fds were closed")
2426
2427 p = subprocess.Popen([sys.executable, fd_status],
2428 stdout=subprocess.PIPE, close_fds=True)
2429 output, ignored = p.communicate()
2430 remaining_fds = set(map(int, output.split(b',')))
2431
2432 self.assertFalse(remaining_fds & open_fds,
2433 "Some fds were left open")
2434 self.assertIn(1, remaining_fds, "Subprocess failed")
2435
Gregory P. Smith8facece2012-01-21 14:01:08 -08002436 # Keep some of the fd's we opened open in the subprocess.
2437 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2438 fds_to_keep = set(open_fds.pop() for _ in range(8))
2439 p = subprocess.Popen([sys.executable, fd_status],
2440 stdout=subprocess.PIPE, close_fds=True,
izbyshev2d8f0632017-12-19 03:26:49 +07002441 pass_fds=fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002442 output, ignored = p.communicate()
2443 remaining_fds = set(map(int, output.split(b',')))
2444
izbyshev2d8f0632017-12-19 03:26:49 +07002445 self.assertFalse((remaining_fds - fds_to_keep) & open_fds,
Gregory P. Smith8facece2012-01-21 14:01:08 -08002446 "Some fds not in pass_fds were left open")
2447 self.assertIn(1, remaining_fds, "Subprocess failed")
2448
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002449
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002450 @unittest.skipIf(sys.platform.startswith("freebsd") and
2451 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2452 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002453 def test_close_fds_when_max_fd_is_lowered(self):
2454 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2455 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2456
Gregory P. Smith634aa682014-06-15 17:51:04 -07002457 # This launches the meat of the test in a child process to
2458 # avoid messing with the larger unittest processes maximum
2459 # number of file descriptors.
2460 # This process launches:
2461 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2462 # a bunch of high open fds above the new lower rlimit.
2463 # Those are reported via stdout before launching a new
2464 # process with close_fds=False to run the actual test:
2465 # +--> The TEST: This one launches a fd_status.py
2466 # subprocess with close_fds=True so we can find out if
2467 # any of the fds above the lowered rlimit are still open.
2468 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2469 '''
2470 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002471 open_fds = set()
2472 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002473 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002474 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002475 open_fds.add(fd)
2476
2477 # Leave a two pairs of low ones available for use by the
2478 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002479 # We also leave 10 more open as some Python buildbots run into
2480 # "too many open files" errors during the test if we do not.
2481 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002482 os.close(fd)
2483 open_fds.remove(fd)
2484
2485 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002486 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002487 os.set_inheritable(fd, True)
2488
2489 max_fd_open = max(open_fds)
2490
Gregory P. Smith634aa682014-06-15 17:51:04 -07002491 # Communicate the open_fds to the parent unittest.TestCase process.
2492 print(','.join(map(str, sorted(open_fds))))
2493 sys.stdout.flush()
2494
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002495 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2496 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002497 # 29 is lower than the highest fds we are leaving open.
2498 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002499 # Launch a new Python interpreter with our low fd rlim_cur that
2500 # inherits open fds above that limit. It then uses subprocess
2501 # with close_fds=True to get a report of open fds in the child.
2502 # An explicit list of fds to check is passed to fd_status.py as
2503 # letting fd_status rely on its default logic would miss the
2504 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002505 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002506 [sys.executable, '-c',
2507 textwrap.dedent("""
2508 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002509 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002510 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002511 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002512 """.format(max_fd=max_fd_open+1))],
2513 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002514 finally:
2515 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002516 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002517
2518 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002519 output_lines = output.splitlines()
2520 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002521 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002522 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2523 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002524
Gregory P. Smith634aa682014-06-15 17:51:04 -07002525 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002526 msg="Some fds were left open.")
2527
2528
Victor Stinner88701e22011-06-01 13:13:04 +02002529 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2530 # descriptor of a pipe closed in the parent process is valid in the
2531 # child process according to fstat(), but the mode of the file
2532 # descriptor is invalid, and read or write raise an error.
2533 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002534 def test_pass_fds(self):
2535 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2536
2537 open_fds = set()
2538
2539 for x in range(5):
2540 fds = os.pipe()
2541 self.addCleanup(os.close, fds[0])
2542 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002543 os.set_inheritable(fds[0], True)
2544 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002545 open_fds.update(fds)
2546
2547 for fd in open_fds:
2548 p = subprocess.Popen([sys.executable, fd_status],
2549 stdout=subprocess.PIPE, close_fds=True,
2550 pass_fds=(fd, ))
2551 output, ignored = p.communicate()
2552
2553 remaining_fds = set(map(int, output.split(b',')))
2554 to_be_closed = open_fds - {fd}
2555
2556 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2557 self.assertFalse(remaining_fds & to_be_closed,
2558 "fd to be closed passed")
2559
2560 # pass_fds overrides close_fds with a warning.
2561 with self.assertWarns(RuntimeWarning) as context:
2562 self.assertFalse(subprocess.call(
2563 [sys.executable, "-c", "import sys; sys.exit(0)"],
2564 close_fds=False, pass_fds=(fd, )))
2565 self.assertIn('overriding close_fds', str(context.warning))
2566
Victor Stinnerdaf45552013-08-28 00:53:59 +02002567 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002568 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002569
2570 inheritable, non_inheritable = os.pipe()
2571 self.addCleanup(os.close, inheritable)
2572 self.addCleanup(os.close, non_inheritable)
2573 os.set_inheritable(inheritable, True)
2574 os.set_inheritable(non_inheritable, False)
2575 pass_fds = (inheritable, non_inheritable)
2576 args = [sys.executable, script]
2577 args += list(map(str, pass_fds))
2578
2579 p = subprocess.Popen(args,
2580 stdout=subprocess.PIPE, close_fds=True,
2581 pass_fds=pass_fds)
2582 output, ignored = p.communicate()
2583 fds = set(map(int, output.split(b',')))
2584
2585 # the inheritable file descriptor must be inherited, so its inheritable
2586 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002587 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002588
2589 # inheritable flag must not be changed in the parent process
2590 self.assertEqual(os.get_inheritable(inheritable), True)
2591 self.assertEqual(os.get_inheritable(non_inheritable), False)
2592
Gregory P. Smithce344102018-09-10 17:46:22 -07002593
2594 # bpo-32270: Ensure that descriptors specified in pass_fds
2595 # are inherited even if they are used in redirections.
2596 # Contributed by @izbyshev.
2597 def test_pass_fds_redirected(self):
2598 """Regression test for https://bugs.python.org/issue32270."""
2599 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2600 pass_fds = []
2601 for _ in range(2):
2602 fd = os.open(os.devnull, os.O_RDWR)
2603 self.addCleanup(os.close, fd)
2604 pass_fds.append(fd)
2605
2606 stdout_r, stdout_w = os.pipe()
2607 self.addCleanup(os.close, stdout_r)
2608 self.addCleanup(os.close, stdout_w)
2609 pass_fds.insert(1, stdout_w)
2610
2611 with subprocess.Popen([sys.executable, fd_status],
2612 stdin=pass_fds[0],
2613 stdout=pass_fds[1],
2614 stderr=pass_fds[2],
2615 close_fds=True,
2616 pass_fds=pass_fds):
2617 output = os.read(stdout_r, 1024)
2618 fds = {int(num) for num in output.split(b',')}
2619
2620 self.assertEqual(fds, {0, 1, 2} | frozenset(pass_fds), f"output={output!a}")
2621
2622
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002623 def test_stdout_stdin_are_single_inout_fd(self):
2624 with io.open(os.devnull, "r+") as inout:
2625 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2626 stdout=inout, stdin=inout)
2627 p.wait()
2628
2629 def test_stdout_stderr_are_single_inout_fd(self):
2630 with io.open(os.devnull, "r+") as inout:
2631 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2632 stdout=inout, stderr=inout)
2633 p.wait()
2634
2635 def test_stderr_stdin_are_single_inout_fd(self):
2636 with io.open(os.devnull, "r+") as inout:
2637 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2638 stderr=inout, stdin=inout)
2639 p.wait()
2640
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002641 def test_wait_when_sigchild_ignored(self):
2642 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2643 sigchild_ignore = support.findfile("sigchild_ignore.py",
2644 subdir="subprocessdata")
2645 p = subprocess.Popen([sys.executable, sigchild_ignore],
2646 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2647 stdout, stderr = p.communicate()
2648 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002649 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002650 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002651
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002652 def test_select_unbuffered(self):
2653 # Issue #11459: bufsize=0 should really set the pipes as
2654 # unbuffered (and therefore let select() work properly).
2655 select = support.import_module("select")
2656 p = subprocess.Popen([sys.executable, "-c",
2657 'import sys;'
2658 'sys.stdout.write("apple")'],
2659 stdout=subprocess.PIPE,
2660 bufsize=0)
2661 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002662 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002663 try:
2664 self.assertEqual(f.read(4), b"appl")
2665 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2666 finally:
2667 p.wait()
2668
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002669 def test_zombie_fast_process_del(self):
2670 # Issue #12650: on Unix, if Popen.__del__() was called before the
2671 # process exited, it wouldn't be added to subprocess._active, and would
2672 # remain a zombie.
2673 # spawn a Popen, and delete its reference before it exits
2674 p = subprocess.Popen([sys.executable, "-c",
2675 'import sys, time;'
2676 'time.sleep(0.2)'],
2677 stdout=subprocess.PIPE,
2678 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002679 self.addCleanup(p.stdout.close)
2680 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002681 ident = id(p)
2682 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002683 with support.check_warnings(('', ResourceWarning)):
2684 p = None
2685
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002686 if mswindows:
2687 # subprocess._active is not used on Windows and is set to None.
2688 self.assertIsNone(subprocess._active)
2689 else:
2690 # check that p is in the active processes list
2691 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002692
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002693 def test_leak_fast_process_del_killed(self):
2694 # Issue #12650: on Unix, if Popen.__del__() was called before the
2695 # process exited, and the process got killed by a signal, it would never
2696 # be removed from subprocess._active, which triggered a FD and memory
2697 # leak.
2698 # spawn a Popen, delete its reference and kill it
2699 p = subprocess.Popen([sys.executable, "-c",
2700 'import time;'
2701 'time.sleep(3)'],
2702 stdout=subprocess.PIPE,
2703 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002704 self.addCleanup(p.stdout.close)
2705 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002706 ident = id(p)
2707 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002708 with support.check_warnings(('', ResourceWarning)):
2709 p = None
2710
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002711 os.kill(pid, signal.SIGKILL)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002712 if mswindows:
2713 # subprocess._active is not used on Windows and is set to None.
2714 self.assertIsNone(subprocess._active)
2715 else:
2716 # check that p is in the active processes list
2717 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002718
2719 # let some time for the process to exit, and create a new Popen: this
2720 # should trigger the wait() of p
2721 time.sleep(0.2)
Victor Stinnerb31206a2018-01-25 19:06:05 +01002722 with self.assertRaises(OSError):
Victor Stinner9a83f652017-08-21 23:51:31 +02002723 with subprocess.Popen(NONEXISTING_CMD,
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002724 stdout=subprocess.PIPE,
2725 stderr=subprocess.PIPE) as proc:
2726 pass
2727 # p should have been wait()ed on, and removed from the _active list
2728 self.assertRaises(OSError, os.waitpid, pid, 0)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002729 if mswindows:
2730 # subprocess._active is not used on Windows and is set to None.
2731 self.assertIsNone(subprocess._active)
2732 else:
2733 self.assertNotIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002734
Charles-François Natali249cdc32013-08-25 18:24:45 +02002735 def test_close_fds_after_preexec(self):
2736 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2737
2738 # this FD is used as dup2() target by preexec_fn, and should be closed
2739 # in the child process
2740 fd = os.dup(1)
2741 self.addCleanup(os.close, fd)
2742
2743 p = subprocess.Popen([sys.executable, fd_status],
2744 stdout=subprocess.PIPE, close_fds=True,
2745 preexec_fn=lambda: os.dup2(1, fd))
2746 output, ignored = p.communicate()
2747
2748 remaining_fds = set(map(int, output.split(b',')))
2749
2750 self.assertNotIn(fd, remaining_fds)
2751
Victor Stinner8f437aa2014-10-05 17:25:19 +02002752 @support.cpython_only
2753 def test_fork_exec(self):
2754 # Issue #22290: fork_exec() must not crash on memory allocation failure
2755 # or other errors
2756 import _posixsubprocess
2757 gc_enabled = gc.isenabled()
2758 try:
2759 # Use a preexec function and enable the garbage collector
2760 # to force fork_exec() to re-enable the garbage collector
2761 # on error.
2762 func = lambda: None
2763 gc.enable()
2764
Victor Stinner8f437aa2014-10-05 17:25:19 +02002765 for args, exe_list, cwd, env_list in (
2766 (123, [b"exe"], None, [b"env"]),
2767 ([b"arg"], 123, None, [b"env"]),
2768 ([b"arg"], [b"exe"], 123, [b"env"]),
2769 ([b"arg"], [b"exe"], None, 123),
2770 ):
2771 with self.assertRaises(TypeError):
2772 _posixsubprocess.fork_exec(
2773 args, exe_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002774 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02002775 -1, -1, -1, -1,
2776 1, 2, 3, 4,
2777 True, True, func)
2778 finally:
2779 if not gc_enabled:
2780 gc.disable()
2781
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002782 @support.cpython_only
2783 def test_fork_exec_sorted_fd_sanity_check(self):
2784 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
2785 import _posixsubprocess
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002786 class BadInt:
2787 first = True
2788 def __init__(self, value):
2789 self.value = value
2790 def __int__(self):
2791 if self.first:
2792 self.first = False
2793 return self.value
2794 raise ValueError
2795
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002796 gc_enabled = gc.isenabled()
2797 try:
2798 gc.enable()
2799
2800 for fds_to_keep in (
2801 (-1, 2, 3, 4, 5), # Negative number.
2802 ('str', 4), # Not an int.
2803 (18, 23, 42, 2**63), # Out of range.
2804 (5, 4), # Not sorted.
2805 (6, 7, 7, 8), # Duplicate.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002806 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002807 ):
2808 with self.assertRaises(
2809 ValueError,
2810 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
2811 _posixsubprocess.fork_exec(
2812 [b"false"], [b"false"],
2813 True, fds_to_keep, None, [b"env"],
2814 -1, -1, -1, -1,
2815 1, 2, 3, 4,
2816 True, True, None)
2817 self.assertIn('fds_to_keep', str(c.exception))
2818 finally:
2819 if not gc_enabled:
2820 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02002821
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00002822 def test_communicate_BrokenPipeError_stdin_close(self):
2823 # By not setting stdout or stderr or a timeout we force the fast path
2824 # that just calls _stdin_write() internally due to our mock.
2825 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2826 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2827 mock_proc_stdin.close.side_effect = BrokenPipeError
2828 proc.communicate() # Should swallow BrokenPipeError from close.
2829 mock_proc_stdin.close.assert_called_with()
2830
2831 def test_communicate_BrokenPipeError_stdin_write(self):
2832 # By not setting stdout or stderr or a timeout we force the fast path
2833 # that just calls _stdin_write() internally due to our mock.
2834 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2835 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2836 mock_proc_stdin.write.side_effect = BrokenPipeError
2837 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
2838 mock_proc_stdin.write.assert_called_once_with(b'stuff')
2839 mock_proc_stdin.close.assert_called_once_with()
2840
2841 def test_communicate_BrokenPipeError_stdin_flush(self):
2842 # Setting stdin and stdout forces the ._communicate() code path.
2843 # python -h exits faster than python -c pass (but spams stdout).
2844 proc = subprocess.Popen([sys.executable, '-h'],
2845 stdin=subprocess.PIPE,
2846 stdout=subprocess.PIPE)
2847 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
2848 open(os.devnull, 'wb') as dev_null:
2849 mock_proc_stdin.flush.side_effect = BrokenPipeError
2850 # because _communicate registers a selector using proc.stdin...
2851 mock_proc_stdin.fileno.return_value = dev_null.fileno()
2852 # _communicate() should swallow BrokenPipeError from flush.
2853 proc.communicate(b'stuff')
2854 mock_proc_stdin.flush.assert_called_once_with()
2855
2856 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
2857 # Setting stdin and stdout forces the ._communicate() code path.
2858 # python -h exits faster than python -c pass (but spams stdout).
2859 proc = subprocess.Popen([sys.executable, '-h'],
2860 stdin=subprocess.PIPE,
2861 stdout=subprocess.PIPE)
2862 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2863 mock_proc_stdin.close.side_effect = BrokenPipeError
2864 # _communicate() should swallow BrokenPipeError from close.
2865 proc.communicate(timeout=999)
2866 mock_proc_stdin.close.assert_called_once_with()
2867
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002868 @unittest.skipUnless(_testcapi is not None
2869 and hasattr(_testcapi, 'W_STOPCODE'),
2870 'need _testcapi.W_STOPCODE')
2871 def test_stopped(self):
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002872 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002873 args = [sys.executable, '-c', 'pass']
2874 proc = subprocess.Popen(args)
Victor Stinnercdee3f12017-06-26 17:23:03 +02002875
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002876 # Wait until the real process completes to avoid zombie process
2877 pid = proc.pid
2878 pid, status = os.waitpid(pid, 0)
2879 self.assertEqual(status, 0)
Victor Stinnercdee3f12017-06-26 17:23:03 +02002880
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002881 status = _testcapi.W_STOPCODE(3)
2882 with mock.patch('subprocess.os.waitpid', return_value=(pid, status)):
2883 returncode = proc.wait()
Victor Stinnercdee3f12017-06-26 17:23:03 +02002884
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002885 self.assertEqual(returncode, -3)
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002886
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002887
Victor Stinner937ee9e2018-06-26 02:11:06 +02002888@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00002889class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002890
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002891 def test_startupinfo(self):
2892 # startupinfo argument
2893 # We uses hardcoded constants, because we do not want to
2894 # depend on win32all.
2895 STARTF_USESHOWWINDOW = 1
2896 SW_MAXIMIZE = 3
2897 startupinfo = subprocess.STARTUPINFO()
2898 startupinfo.dwFlags = STARTF_USESHOWWINDOW
2899 startupinfo.wShowWindow = SW_MAXIMIZE
2900 # Since Python is a console process, it won't be affected
2901 # by wShowWindow, but the argument should be silently
2902 # ignored
2903 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002904 startupinfo=startupinfo)
2905
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05302906 def test_startupinfo_keywords(self):
2907 # startupinfo argument
2908 # We use hardcoded constants, because we do not want to
2909 # depend on win32all.
2910 STARTF_USERSHOWWINDOW = 1
2911 SW_MAXIMIZE = 3
2912 startupinfo = subprocess.STARTUPINFO(
2913 dwFlags=STARTF_USERSHOWWINDOW,
2914 wShowWindow=SW_MAXIMIZE
2915 )
2916 # Since Python is a console process, it won't be affected
2917 # by wShowWindow, but the argument should be silently
2918 # ignored
2919 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
2920 startupinfo=startupinfo)
2921
Victor Stinner483422f2018-07-05 22:54:17 +02002922 def test_startupinfo_copy(self):
2923 # bpo-34044: Popen must not modify input STARTUPINFO structure
2924 startupinfo = subprocess.STARTUPINFO()
2925 startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
2926 startupinfo.wShowWindow = subprocess.SW_HIDE
2927
2928 # Call Popen() twice with the same startupinfo object to make sure
2929 # that it's not modified
2930 for _ in range(2):
2931 cmd = [sys.executable, "-c", "pass"]
2932 with open(os.devnull, 'w') as null:
2933 proc = subprocess.Popen(cmd,
2934 stdout=null,
2935 stderr=subprocess.STDOUT,
2936 startupinfo=startupinfo)
2937 with proc:
2938 proc.communicate()
2939 self.assertEqual(proc.returncode, 0)
2940
2941 self.assertEqual(startupinfo.dwFlags,
2942 subprocess.STARTF_USESHOWWINDOW)
2943 self.assertIsNone(startupinfo.hStdInput)
2944 self.assertIsNone(startupinfo.hStdOutput)
2945 self.assertIsNone(startupinfo.hStdError)
2946 self.assertEqual(startupinfo.wShowWindow, subprocess.SW_HIDE)
2947 self.assertEqual(startupinfo.lpAttributeList, {"handle_list": []})
2948
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002949 def test_creationflags(self):
2950 # creationflags argument
2951 CREATE_NEW_CONSOLE = 16
2952 sys.stderr.write(" a DOS box should flash briefly ...\n")
2953 subprocess.call(sys.executable +
2954 ' -c "import time; time.sleep(0.25)"',
2955 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002956
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002957 def test_invalid_args(self):
2958 # invalid arguments should raise ValueError
2959 self.assertRaises(ValueError, subprocess.call,
2960 [sys.executable, "-c",
2961 "import sys; sys.exit(47)"],
2962 preexec_fn=lambda: 1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002963
Oren Milman0b3a87e2017-09-14 22:30:28 +03002964 @support.cpython_only
2965 def test_issue31471(self):
2966 # There shouldn't be an assertion failure in Popen() in case the env
2967 # argument has a bad keys() method.
2968 class BadEnv(dict):
2969 keys = None
2970 with self.assertRaises(TypeError):
2971 subprocess.Popen([sys.executable, "-c", "pass"], env=BadEnv())
2972
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002973 def test_close_fds(self):
2974 # close file descriptors
2975 rc = subprocess.call([sys.executable, "-c",
2976 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002977 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002978 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002979
Segev Finerb2a60832017-12-18 11:28:19 +02002980 def test_close_fds_with_stdio(self):
2981 import msvcrt
2982
2983 fds = os.pipe()
2984 self.addCleanup(os.close, fds[0])
2985 self.addCleanup(os.close, fds[1])
2986
2987 handles = []
2988 for fd in fds:
2989 os.set_inheritable(fd, True)
2990 handles.append(msvcrt.get_osfhandle(fd))
2991
2992 p = subprocess.Popen([sys.executable, "-c",
2993 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
2994 stdout=subprocess.PIPE, close_fds=False)
2995 stdout, stderr = p.communicate()
2996 self.assertEqual(p.returncode, 0)
2997 int(stdout.strip()) # Check that stdout is an integer
2998
2999 p = subprocess.Popen([sys.executable, "-c",
3000 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3001 stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
3002 stdout, stderr = p.communicate()
3003 self.assertEqual(p.returncode, 1)
3004 self.assertIn(b"OSError", stderr)
3005
3006 # The same as the previous call, but with an empty handle_list
3007 handle_list = []
3008 startupinfo = subprocess.STARTUPINFO()
3009 startupinfo.lpAttributeList = {"handle_list": handle_list}
3010 p = subprocess.Popen([sys.executable, "-c",
3011 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3012 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3013 startupinfo=startupinfo, close_fds=True)
3014 stdout, stderr = p.communicate()
3015 self.assertEqual(p.returncode, 1)
3016 self.assertIn(b"OSError", stderr)
3017
3018 # Check for a warning due to using handle_list and close_fds=False
3019 with support.check_warnings((".*overriding close_fds", RuntimeWarning)):
3020 startupinfo = subprocess.STARTUPINFO()
3021 startupinfo.lpAttributeList = {"handle_list": handles[:]}
3022 p = subprocess.Popen([sys.executable, "-c",
3023 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3024 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3025 startupinfo=startupinfo, close_fds=False)
3026 stdout, stderr = p.communicate()
3027 self.assertEqual(p.returncode, 0)
3028
3029 def test_empty_attribute_list(self):
3030 startupinfo = subprocess.STARTUPINFO()
3031 startupinfo.lpAttributeList = {}
3032 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
3033 startupinfo=startupinfo)
3034
3035 def test_empty_handle_list(self):
3036 startupinfo = subprocess.STARTUPINFO()
3037 startupinfo.lpAttributeList = {"handle_list": []}
3038 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
3039 startupinfo=startupinfo)
3040
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003041 def test_shell_sequence(self):
3042 # Run command through the shell (sequence)
3043 newenv = os.environ.copy()
3044 newenv["FRUIT"] = "physalis"
3045 p = subprocess.Popen(["set"], shell=1,
3046 stdout=subprocess.PIPE,
3047 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003048 with p:
3049 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00003050
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003051 def test_shell_string(self):
3052 # Run command through the shell (string)
3053 newenv = os.environ.copy()
3054 newenv["FRUIT"] = "physalis"
3055 p = subprocess.Popen("set", shell=1,
3056 stdout=subprocess.PIPE,
3057 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003058 with p:
3059 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003060
Steve Dower050acae2016-09-06 20:16:17 -07003061 def test_shell_encodings(self):
3062 # Run command through the shell (string)
3063 for enc in ['ansi', 'oem']:
3064 newenv = os.environ.copy()
3065 newenv["FRUIT"] = "physalis"
3066 p = subprocess.Popen("set", shell=1,
3067 stdout=subprocess.PIPE,
3068 env=newenv,
3069 encoding=enc)
3070 with p:
3071 self.assertIn("physalis", p.stdout.read(), enc)
3072
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003073 def test_call_string(self):
3074 # call() function with string argument on Windows
3075 rc = subprocess.call(sys.executable +
3076 ' -c "import sys; sys.exit(47)"')
3077 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003078
Florent Xicluna4886d242010-03-08 13:27:26 +00003079 def _kill_process(self, method, *args):
3080 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00003081 p = subprocess.Popen([sys.executable, "-c", """if 1:
3082 import sys, time
3083 sys.stdout.write('x\\n')
3084 sys.stdout.flush()
3085 time.sleep(30)
3086 """],
3087 stdin=subprocess.PIPE,
3088 stdout=subprocess.PIPE,
3089 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003090 with p:
3091 # Wait for the interpreter to be completely initialized before
3092 # sending any signal.
3093 p.stdout.read(1)
3094 getattr(p, method)(*args)
3095 _, stderr = p.communicate()
3096 self.assertStderrEqual(stderr, b'')
3097 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00003098 self.assertNotEqual(returncode, 0)
3099
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003100 def _kill_dead_process(self, method, *args):
3101 p = subprocess.Popen([sys.executable, "-c", """if 1:
3102 import sys, time
3103 sys.stdout.write('x\\n')
3104 sys.stdout.flush()
3105 sys.exit(42)
3106 """],
3107 stdin=subprocess.PIPE,
3108 stdout=subprocess.PIPE,
3109 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003110 with p:
3111 # Wait for the interpreter to be completely initialized before
3112 # sending any signal.
3113 p.stdout.read(1)
3114 # The process should end after this
3115 time.sleep(1)
3116 # This shouldn't raise even though the child is now dead
3117 getattr(p, method)(*args)
3118 _, stderr = p.communicate()
3119 self.assertStderrEqual(stderr, b'')
3120 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003121 self.assertEqual(rc, 42)
3122
Florent Xicluna4886d242010-03-08 13:27:26 +00003123 def test_send_signal(self):
3124 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00003125
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003126 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003127 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00003128
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003129 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003130 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00003131
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003132 def test_send_signal_dead(self):
3133 self._kill_dead_process('send_signal', signal.SIGTERM)
3134
3135 def test_kill_dead(self):
3136 self._kill_dead_process('kill')
3137
3138 def test_terminate_dead(self):
3139 self._kill_dead_process('terminate')
3140
Martin Panter23172bd2016-04-16 11:28:10 +00003141class MiscTests(unittest.TestCase):
Gregory P. Smithf4d644f2018-01-29 21:27:39 -08003142
3143 class RecordingPopen(subprocess.Popen):
3144 """A Popen that saves a reference to each instance for testing."""
3145 instances_created = []
3146
3147 def __init__(self, *args, **kwargs):
3148 super().__init__(*args, **kwargs)
3149 self.instances_created.append(self)
3150
3151 @mock.patch.object(subprocess.Popen, "_communicate")
3152 def _test_keyboardinterrupt_no_kill(self, popener, mock__communicate,
3153 **kwargs):
3154 """Fake a SIGINT happening during Popen._communicate() and ._wait().
3155
3156 This avoids the need to actually try and get test environments to send
3157 and receive signals reliably across platforms. The net effect of a ^C
3158 happening during a blocking subprocess execution which we want to clean
3159 up from is a KeyboardInterrupt coming out of communicate() or wait().
3160 """
3161
3162 mock__communicate.side_effect = KeyboardInterrupt
3163 try:
3164 with mock.patch.object(subprocess.Popen, "_wait") as mock__wait:
3165 # We patch out _wait() as no signal was involved so the
3166 # child process isn't actually going to exit rapidly.
3167 mock__wait.side_effect = KeyboardInterrupt
3168 with mock.patch.object(subprocess, "Popen",
3169 self.RecordingPopen):
3170 with self.assertRaises(KeyboardInterrupt):
3171 popener([sys.executable, "-c",
3172 "import time\ntime.sleep(9)\nimport sys\n"
3173 "sys.stderr.write('\\n!runaway child!\\n')"],
3174 stdout=subprocess.DEVNULL, **kwargs)
3175 for call in mock__wait.call_args_list[1:]:
3176 self.assertNotEqual(
3177 call, mock.call(timeout=None),
3178 "no open-ended wait() after the first allowed: "
3179 f"{mock__wait.call_args_list}")
3180 sigint_calls = []
3181 for call in mock__wait.call_args_list:
3182 if call == mock.call(timeout=0.25): # from Popen.__init__
3183 sigint_calls.append(call)
3184 self.assertLessEqual(mock__wait.call_count, 2,
3185 msg=mock__wait.call_args_list)
3186 self.assertEqual(len(sigint_calls), 1,
3187 msg=mock__wait.call_args_list)
3188 finally:
3189 # cleanup the forgotten (due to our mocks) child process
3190 process = self.RecordingPopen.instances_created.pop()
3191 process.kill()
3192 process.wait()
3193 self.assertEqual([], self.RecordingPopen.instances_created)
3194
3195 def test_call_keyboardinterrupt_no_kill(self):
3196 self._test_keyboardinterrupt_no_kill(subprocess.call, timeout=6.282)
3197
3198 def test_run_keyboardinterrupt_no_kill(self):
3199 self._test_keyboardinterrupt_no_kill(subprocess.run, timeout=6.282)
3200
3201 def test_context_manager_keyboardinterrupt_no_kill(self):
3202 def popen_via_context_manager(*args, **kwargs):
3203 with subprocess.Popen(*args, **kwargs) as unused_process:
3204 raise KeyboardInterrupt # Test how __exit__ handles ^C.
3205 self._test_keyboardinterrupt_no_kill(popen_via_context_manager)
3206
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003207 def test_getoutput(self):
3208 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
3209 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
3210 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00003211
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003212 # we use mkdtemp in the next line to create an empty directory
3213 # under our exclusive control; from that, we can invent a pathname
3214 # that we _know_ won't exist. This is guaranteed to fail.
3215 dir = None
3216 try:
3217 dir = tempfile.mkdtemp()
3218 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00003219 status, output = subprocess.getstatusoutput(
Victor Stinner937ee9e2018-06-26 02:11:06 +02003220 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003221 self.assertNotEqual(status, 0)
3222 finally:
3223 if dir is not None:
3224 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00003225
Gregory P. Smithace55862015-04-07 15:57:54 -07003226 def test__all__(self):
3227 """Ensure that __all__ is populated properly."""
Martin Panter528619b2016-04-16 23:42:37 +00003228 intentionally_excluded = {"list2cmdline", "Handle"}
Gregory P. Smithace55862015-04-07 15:57:54 -07003229 exported = set(subprocess.__all__)
3230 possible_exports = set()
3231 import types
3232 for name, value in subprocess.__dict__.items():
3233 if name.startswith('_'):
3234 continue
3235 if isinstance(value, (types.ModuleType,)):
3236 continue
3237 possible_exports.add(name)
3238 self.assertEqual(exported, possible_exports - intentionally_excluded)
3239
3240
Martin Panter23172bd2016-04-16 11:28:10 +00003241@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
3242 "Test needs selectors.PollSelector")
3243class ProcessTestCaseNoPoll(ProcessTestCase):
3244 def setUp(self):
3245 self.orig_selector = subprocess._PopenSelector
3246 subprocess._PopenSelector = selectors.SelectSelector
3247 ProcessTestCase.setUp(self)
3248
3249 def tearDown(self):
3250 subprocess._PopenSelector = self.orig_selector
3251 ProcessTestCase.tearDown(self)
3252
Gregory P. Smithd06fa472009-07-04 02:46:54 +00003253
Victor Stinner937ee9e2018-06-26 02:11:06 +02003254@unittest.skipUnless(mswindows, "Windows-specific tests")
Tim Golden126c2962010-08-11 14:20:40 +00003255class CommandsWithSpaces (BaseTestCase):
3256
3257 def setUp(self):
3258 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03003259 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00003260 self.fname = fname.lower ()
3261 os.write(f, b"import sys;"
3262 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
3263 )
3264 os.close(f)
3265
3266 def tearDown(self):
3267 os.remove(self.fname)
3268 super().tearDown()
3269
3270 def with_spaces(self, *args, **kwargs):
3271 kwargs['stdout'] = subprocess.PIPE
3272 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02003273 with p:
3274 self.assertEqual(
3275 p.stdout.read ().decode("mbcs"),
3276 "2 [%r, 'ab cd']" % self.fname
3277 )
Tim Golden126c2962010-08-11 14:20:40 +00003278
3279 def test_shell_string_with_spaces(self):
3280 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003281 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3282 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003283
3284 def test_shell_sequence_with_spaces(self):
3285 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003286 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003287
3288 def test_noshell_string_with_spaces(self):
3289 # call() function with string argument with spaces on Windows
3290 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3291 "ab cd"))
3292
3293 def test_noshell_sequence_with_spaces(self):
3294 # call() function with sequence argument with spaces on Windows
3295 self.with_spaces([sys.executable, self.fname, "ab cd"])
3296
Brian Curtin79cdb662010-12-03 02:46:02 +00003297
Georg Brandla86b2622012-02-20 21:34:57 +01003298class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00003299
3300 def test_pipe(self):
3301 with subprocess.Popen([sys.executable, "-c",
3302 "import sys;"
3303 "sys.stdout.write('stdout');"
3304 "sys.stderr.write('stderr');"],
3305 stdout=subprocess.PIPE,
3306 stderr=subprocess.PIPE) as proc:
3307 self.assertEqual(proc.stdout.read(), b"stdout")
3308 self.assertStderrEqual(proc.stderr.read(), b"stderr")
3309
3310 self.assertTrue(proc.stdout.closed)
3311 self.assertTrue(proc.stderr.closed)
3312
3313 def test_returncode(self):
3314 with subprocess.Popen([sys.executable, "-c",
3315 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07003316 pass
3317 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00003318 self.assertEqual(proc.returncode, 100)
3319
3320 def test_communicate_stdin(self):
3321 with subprocess.Popen([sys.executable, "-c",
3322 "import sys;"
3323 "sys.exit(sys.stdin.read() == 'context')"],
3324 stdin=subprocess.PIPE) as proc:
3325 proc.communicate(b"context")
3326 self.assertEqual(proc.returncode, 1)
3327
3328 def test_invalid_args(self):
Victor Stinnerb31206a2018-01-25 19:06:05 +01003329 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02003330 with subprocess.Popen(NONEXISTING_CMD,
Brian Curtin79cdb662010-12-03 02:46:02 +00003331 stdout=subprocess.PIPE,
3332 stderr=subprocess.PIPE) as proc:
3333 pass
3334
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003335 def test_broken_pipe_cleanup(self):
3336 """Broken pipe error should not prevent wait() (Issue 21619)"""
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003337 proc = subprocess.Popen([sys.executable, '-c', 'pass'],
Victor Stinner20f4bd42015-03-05 02:38:41 +01003338 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003339 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003340 proc = proc.__enter__()
3341 # Prepare to send enough data to overflow any OS pipe buffering and
3342 # guarantee a broken pipe error. Data is held in BufferedWriter
3343 # buffer until closed.
3344 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003345 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003346 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02003347 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003348 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003349 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003350
Brian Curtin79cdb662010-12-03 02:46:02 +00003351
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003352if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04003353 unittest.main()