blob: fca3ed62099bdee6caea5d285f020bda2884000b [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):
62 for inst in subprocess._active:
63 inst.wait()
64 subprocess._cleanup()
65 self.assertFalse(subprocess._active, "subprocess._active not empty")
Victor Stinnercc42c122017-07-28 18:00:22 +020066 self.doCleanups()
67 support.reap_children()
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000068
Florent Xiclunab1e94e82010-02-27 22:12:37 +000069 def assertStderrEqual(self, stderr, expected, msg=None):
70 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
71 # shutdown time. That frustrates tests trying to check stderr produced
72 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000073 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040074 # strip_python_stderr also strips whitespace, so we do too.
75 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000076 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000077
Florent Xiclunac049d872010-03-27 22:47:23 +000078
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080079class PopenTestException(Exception):
80 pass
81
82
83class PopenExecuteChildRaises(subprocess.Popen):
84 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
85 _execute_child fails.
86 """
87 def _execute_child(self, *args, **kwargs):
88 raise PopenTestException("Forced Exception for Test")
89
90
Florent Xiclunac049d872010-03-27 22:47:23 +000091class ProcessTestCase(BaseTestCase):
92
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070093 def test_io_buffered_by_default(self):
94 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
95 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
96 stderr=subprocess.PIPE)
97 try:
98 self.assertIsInstance(p.stdin, io.BufferedIOBase)
99 self.assertIsInstance(p.stdout, io.BufferedIOBase)
100 self.assertIsInstance(p.stderr, io.BufferedIOBase)
101 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700102 p.stdin.close()
103 p.stdout.close()
104 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700105 p.wait()
106
107 def test_io_unbuffered_works(self):
108 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
109 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
110 stderr=subprocess.PIPE, bufsize=0)
111 try:
112 self.assertIsInstance(p.stdin, io.RawIOBase)
113 self.assertIsInstance(p.stdout, io.RawIOBase)
114 self.assertIsInstance(p.stderr, io.RawIOBase)
115 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700116 p.stdin.close()
117 p.stdout.close()
118 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700119 p.wait()
120
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000121 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000122 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000123 rc = subprocess.call([sys.executable, "-c",
124 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000125 self.assertEqual(rc, 47)
126
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400127 def test_call_timeout(self):
128 # call() function with timeout argument; we want to test that the child
129 # process gets killed when the timeout expires. If the child isn't
130 # killed, this call will deadlock since subprocess.call waits for the
131 # child.
132 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
133 [sys.executable, "-c", "while True: pass"],
134 timeout=0.1)
135
Peter Astrand454f7672005-01-01 09:36:35 +0000136 def test_check_call_zero(self):
137 # check_call() function with zero return code
138 rc = subprocess.check_call([sys.executable, "-c",
139 "import sys; sys.exit(0)"])
140 self.assertEqual(rc, 0)
141
142 def test_check_call_nonzero(self):
143 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000144 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000145 subprocess.check_call([sys.executable, "-c",
146 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000147 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000148
Georg Brandlf9734072008-12-07 15:30:06 +0000149 def test_check_output(self):
150 # check_output() function with zero return code
151 output = subprocess.check_output(
152 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000153 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000154
155 def test_check_output_nonzero(self):
156 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000157 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000158 subprocess.check_output(
159 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000160 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000161
162 def test_check_output_stderr(self):
163 # check_output() function stderr redirected to stdout
164 output = subprocess.check_output(
165 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
166 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000167 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000168
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300169 def test_check_output_stdin_arg(self):
170 # check_output() can be called with stdin set to a file
171 tf = tempfile.TemporaryFile()
172 self.addCleanup(tf.close)
173 tf.write(b'pear')
174 tf.seek(0)
175 output = subprocess.check_output(
176 [sys.executable, "-c",
177 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
178 stdin=tf)
179 self.assertIn(b'PEAR', output)
180
181 def test_check_output_input_arg(self):
182 # check_output() can be called with input set to a string
183 output = subprocess.check_output(
184 [sys.executable, "-c",
185 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
186 input=b'pear')
187 self.assertIn(b'PEAR', output)
188
Georg Brandlf9734072008-12-07 15:30:06 +0000189 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300190 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000191 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000192 output = subprocess.check_output(
193 [sys.executable, "-c", "print('will not be run')"],
194 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000195 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000196 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000197
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300198 def test_check_output_stdin_with_input_arg(self):
199 # check_output() refuses to accept 'stdin' with 'input'
200 tf = tempfile.TemporaryFile()
201 self.addCleanup(tf.close)
202 tf.write(b'pear')
203 tf.seek(0)
204 with self.assertRaises(ValueError) as c:
205 output = subprocess.check_output(
206 [sys.executable, "-c", "print('will not be run')"],
207 stdin=tf, input=b'hare')
208 self.fail("Expected ValueError when stdin and input args supplied.")
209 self.assertIn('stdin', c.exception.args[0])
210 self.assertIn('input', c.exception.args[0])
211
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400212 def test_check_output_timeout(self):
213 # check_output() function with timeout arg
214 with self.assertRaises(subprocess.TimeoutExpired) as c:
215 output = subprocess.check_output(
216 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200217 "import sys, time\n"
218 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400219 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200220 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400221 # Some heavily loaded buildbots (sparc Debian 3.x) require
222 # this much time to start and print.
223 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400224 self.fail("Expected TimeoutExpired.")
225 self.assertEqual(c.exception.output, b'BDFL')
226
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000227 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000228 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000229 newenv = os.environ.copy()
230 newenv["FRUIT"] = "banana"
231 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000232 'import sys, os;'
233 'sys.exit(os.getenv("FRUIT")=="banana")'],
234 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000235 self.assertEqual(rc, 1)
236
Victor Stinner87b9bc32011-06-01 00:57:47 +0200237 def test_invalid_args(self):
238 # Popen() called with invalid arguments should raise TypeError
239 # but Popen.__del__ should not complain (issue #12085)
240 with support.captured_stderr() as s:
241 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
242 argcount = subprocess.Popen.__init__.__code__.co_argcount
243 too_many_args = [0] * (argcount + 1)
244 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
245 self.assertEqual(s.getvalue(), '')
246
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000247 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000248 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000249 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000250 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000251 self.addCleanup(p.stdout.close)
252 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000253 p.wait()
254 self.assertEqual(p.stdin, None)
255
256 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200257 # .stdout is None when not redirected, and the child's stdout will
258 # be inherited from the parent. In order to test this we run a
259 # subprocess in a subprocess:
260 # this_test
261 # \-- subprocess created by this test (parent)
262 # \-- subprocess created by the parent subprocess (child)
263 # The parent doesn't specify stdout, so the child will use the
264 # parent's stdout. This test checks that the message printed by the
265 # child goes to the parent stdout. The parent also checks that the
266 # child's stdout is None. See #11963.
267 code = ('import sys; from subprocess import Popen, PIPE;'
268 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
269 ' stdin=PIPE, stderr=PIPE);'
270 'p.wait(); assert p.stdout is None;')
271 p = subprocess.Popen([sys.executable, "-c", code],
272 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
273 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000274 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200275 out, err = p.communicate()
276 self.assertEqual(p.returncode, 0, err)
277 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000278
279 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000280 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000281 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000282 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000283 self.addCleanup(p.stdout.close)
284 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000285 p.wait()
286 self.assertEqual(p.stderr, None)
287
Chris Jerdonek776cb192012-10-08 15:56:43 -0700288 def _assert_python(self, pre_args, **kwargs):
289 # We include sys.exit() to prevent the test runner from hanging
290 # whenever python is found.
291 args = pre_args + ["import sys; sys.exit(47)"]
292 p = subprocess.Popen(args, **kwargs)
293 p.wait()
294 self.assertEqual(47, p.returncode)
295
296 def test_executable(self):
297 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700298 #
299 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
300 # determine where its standard library is, so we need the directory
301 # of args[0] to be valid for the Popen() call to Python to succeed.
302 # See also issue #16170 and issue #7774.
303 doesnotexist = os.path.join(os.path.dirname(sys.executable),
304 "doesnotexist")
305 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700306
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300307 def test_bytes_executable(self):
308 doesnotexist = os.path.join(os.path.dirname(sys.executable),
309 "doesnotexist")
310 self._assert_python([doesnotexist, "-c"],
311 executable=os.fsencode(sys.executable))
312
313 def test_pathlike_executable(self):
314 doesnotexist = os.path.join(os.path.dirname(sys.executable),
315 "doesnotexist")
316 self._assert_python([doesnotexist, "-c"],
317 executable=FakePath(sys.executable))
318
Chris Jerdonek776cb192012-10-08 15:56:43 -0700319 def test_executable_takes_precedence(self):
320 # Check that the executable argument takes precedence over args[0].
321 #
322 # Verify first that the call succeeds without the executable arg.
323 pre_args = [sys.executable, "-c"]
324 self._assert_python(pre_args)
Victor Stinnerb31206a2018-01-25 19:06:05 +0100325 self.assertRaises(NONEXISTING_ERRORS,
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +0100326 self._assert_python, pre_args,
Victor Stinnerb31206a2018-01-25 19:06:05 +0100327 executable=NONEXISTING_CMD[0])
Chris Jerdonek776cb192012-10-08 15:56:43 -0700328
Victor Stinner937ee9e2018-06-26 02:11:06 +0200329 @unittest.skipIf(mswindows, "executable argument replaces shell")
Chris Jerdonek776cb192012-10-08 15:56:43 -0700330 def test_executable_replaces_shell(self):
331 # Check that the executable argument replaces the default shell
332 # when shell=True.
333 self._assert_python([], executable=sys.executable, shell=True)
334
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300335 @unittest.skipIf(mswindows, "executable argument replaces shell")
336 def test_bytes_executable_replaces_shell(self):
337 self._assert_python([], executable=os.fsencode(sys.executable),
338 shell=True)
339
340 @unittest.skipIf(mswindows, "executable argument replaces shell")
341 def test_pathlike_executable_replaces_shell(self):
342 self._assert_python([], executable=FakePath(sys.executable),
343 shell=True)
344
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700345 # For use in the test_cwd* tests below.
346 def _normalize_cwd(self, cwd):
347 # Normalize an expected cwd (for Tru64 support).
348 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
349 # strings. See bug #1063571.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300350 with support.change_cwd(cwd):
351 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700352
353 # For use in the test_cwd* tests below.
354 def _split_python_path(self):
355 # Return normalized (python_dir, python_base).
356 python_path = os.path.realpath(sys.executable)
357 return os.path.split(python_path)
358
359 # For use in the test_cwd* tests below.
360 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
361 # Invoke Python via Popen, and assert that (1) the call succeeds,
362 # and that (2) the current working directory of the child process
363 # matches *expected_cwd*.
364 p = subprocess.Popen([python_arg, "-c",
365 "import os, sys; "
366 "sys.stdout.write(os.getcwd()); "
367 "sys.exit(47)"],
368 stdout=subprocess.PIPE,
369 **kwargs)
370 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000371 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700372 self.assertEqual(47, p.returncode)
373 normcase = os.path.normcase
374 self.assertEqual(normcase(expected_cwd),
375 normcase(p.stdout.read().decode("utf-8")))
376
377 def test_cwd(self):
378 # Check that cwd changes the cwd for the child process.
379 temp_dir = tempfile.gettempdir()
380 temp_dir = self._normalize_cwd(temp_dir)
381 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
382
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300383 def test_cwd_with_bytes(self):
384 temp_dir = tempfile.gettempdir()
385 temp_dir = self._normalize_cwd(temp_dir)
386 self._assert_cwd(temp_dir, sys.executable, cwd=os.fsencode(temp_dir))
387
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530388 def test_cwd_with_pathlike(self):
389 temp_dir = tempfile.gettempdir()
390 temp_dir = self._normalize_cwd(temp_dir)
Serhiy Storchakab21d1552018-03-02 11:53:51 +0200391 self._assert_cwd(temp_dir, sys.executable, cwd=FakePath(temp_dir))
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530392
Victor Stinner937ee9e2018-06-26 02:11:06 +0200393 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700394 def test_cwd_with_relative_arg(self):
395 # Check that Popen looks for args[0] relative to cwd if args[0]
396 # is relative.
397 python_dir, python_base = self._split_python_path()
398 rel_python = os.path.join(os.curdir, python_base)
399 with support.temp_cwd() as wrong_dir:
400 # Before calling with the correct cwd, confirm that the call fails
401 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700402 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700403 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700404 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700405 [rel_python], cwd=wrong_dir)
406 python_dir = self._normalize_cwd(python_dir)
407 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
408
Victor Stinner937ee9e2018-06-26 02:11:06 +0200409 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700410 def test_cwd_with_relative_executable(self):
411 # Check that Popen looks for executable relative to cwd if executable
412 # is relative (and that executable takes precedence over args[0]).
413 python_dir, python_base = self._split_python_path()
414 rel_python = os.path.join(os.curdir, python_base)
415 doesntexist = "somethingyoudonthave"
416 with support.temp_cwd() as wrong_dir:
417 # Before calling with the correct cwd, confirm that the call fails
418 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700419 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700420 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700421 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700422 [doesntexist], executable=rel_python,
423 cwd=wrong_dir)
424 python_dir = self._normalize_cwd(python_dir)
425 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
426 cwd=python_dir)
427
428 def test_cwd_with_absolute_arg(self):
429 # Check that Popen can find the executable when the cwd is wrong
430 # if args[0] is an absolute path.
431 python_dir, python_base = self._split_python_path()
432 abs_python = os.path.join(python_dir, python_base)
433 rel_python = os.path.join(os.curdir, python_base)
Berker Peksagce643912015-05-06 06:33:17 +0300434 with support.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700435 # Before calling with an absolute path, confirm that using a
436 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700437 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700438 [rel_python], cwd=wrong_dir)
439 wrong_dir = self._normalize_cwd(wrong_dir)
440 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
441
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100442 @unittest.skipIf(sys.base_prefix != sys.prefix,
443 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000444 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700445 python_dir, python_base = self._split_python_path()
446 python_dir = self._normalize_cwd(python_dir)
447 self._assert_cwd(python_dir, "somethingyoudonthave",
448 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000449
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100450 @unittest.skipIf(sys.base_prefix != sys.prefix,
451 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000452 @unittest.skipIf(sysconfig.is_python_build(),
453 "need an installed Python. See #7774")
454 def test_executable_without_cwd(self):
455 # For a normal installation, it should work without 'cwd'
456 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700457 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
458 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000459
460 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000461 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000462 p = subprocess.Popen([sys.executable, "-c",
463 'import sys; sys.exit(sys.stdin.read() == "pear")'],
464 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000465 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000466 p.stdin.close()
467 p.wait()
468 self.assertEqual(p.returncode, 1)
469
470 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000471 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000472 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000473 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000474 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000475 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000476 os.lseek(d, 0, 0)
477 p = subprocess.Popen([sys.executable, "-c",
478 'import sys; sys.exit(sys.stdin.read() == "pear")'],
479 stdin=d)
480 p.wait()
481 self.assertEqual(p.returncode, 1)
482
483 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000484 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000485 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000486 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000487 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000488 tf.seek(0)
489 p = subprocess.Popen([sys.executable, "-c",
490 'import sys; sys.exit(sys.stdin.read() == "pear")'],
491 stdin=tf)
492 p.wait()
493 self.assertEqual(p.returncode, 1)
494
495 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000496 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000497 p = subprocess.Popen([sys.executable, "-c",
498 'import sys; sys.stdout.write("orange")'],
499 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200500 with p:
501 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000502
503 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000504 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000505 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000506 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000507 d = tf.fileno()
508 p = subprocess.Popen([sys.executable, "-c",
509 'import sys; sys.stdout.write("orange")'],
510 stdout=d)
511 p.wait()
512 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000513 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000514
515 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000516 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000517 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000518 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000519 p = subprocess.Popen([sys.executable, "-c",
520 'import sys; sys.stdout.write("orange")'],
521 stdout=tf)
522 p.wait()
523 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000524 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000525
526 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000527 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000528 p = subprocess.Popen([sys.executable, "-c",
529 'import sys; sys.stderr.write("strawberry")'],
530 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200531 with p:
532 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000533
534 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000535 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000536 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000537 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000538 d = tf.fileno()
539 p = subprocess.Popen([sys.executable, "-c",
540 'import sys; sys.stderr.write("strawberry")'],
541 stderr=d)
542 p.wait()
543 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000544 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000545
546 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000547 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000548 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000549 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000550 p = subprocess.Popen([sys.executable, "-c",
551 'import sys; sys.stderr.write("strawberry")'],
552 stderr=tf)
553 p.wait()
554 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000555 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000556
Martin Panterc7635892016-05-13 01:54:44 +0000557 def test_stderr_redirect_with_no_stdout_redirect(self):
558 # test stderr=STDOUT while stdout=None (not set)
559
560 # - grandchild prints to stderr
561 # - child redirects grandchild's stderr to its stdout
562 # - the parent should get grandchild's stderr in child's stdout
563 p = subprocess.Popen([sys.executable, "-c",
564 'import sys, subprocess;'
565 'rc = subprocess.call([sys.executable, "-c",'
566 ' "import sys;"'
567 ' "sys.stderr.write(\'42\')"],'
568 ' stderr=subprocess.STDOUT);'
569 'sys.exit(rc)'],
570 stdout=subprocess.PIPE,
571 stderr=subprocess.PIPE)
572 stdout, stderr = p.communicate()
573 #NOTE: stdout should get stderr from grandchild
574 self.assertStderrEqual(stdout, b'42')
575 self.assertStderrEqual(stderr, b'') # should be empty
576 self.assertEqual(p.returncode, 0)
577
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000578 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000579 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000580 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000581 'import sys;'
582 'sys.stdout.write("apple");'
583 'sys.stdout.flush();'
584 'sys.stderr.write("orange")'],
585 stdout=subprocess.PIPE,
586 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200587 with p:
588 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000589
590 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000591 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000592 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000593 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000594 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000595 'import sys;'
596 'sys.stdout.write("apple");'
597 'sys.stdout.flush();'
598 'sys.stderr.write("orange")'],
599 stdout=tf,
600 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000601 p.wait()
602 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000603 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000604
Thomas Wouters89f507f2006-12-13 04:49:30 +0000605 def test_stdout_filedes_of_stdout(self):
606 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200607 # To avoid printing the text on stdout, we do something similar to
608 # test_stdout_none (see above). The parent subprocess calls the child
609 # subprocess passing stdout=1, and this test uses stdout=PIPE in
610 # order to capture and check the output of the parent. See #11963.
611 code = ('import sys, subprocess; '
612 'rc = subprocess.call([sys.executable, "-c", '
613 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
614 'b\'test with stdout=1\'))"], stdout=1); '
615 'assert rc == 18')
616 p = subprocess.Popen([sys.executable, "-c", code],
617 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
618 self.addCleanup(p.stdout.close)
619 self.addCleanup(p.stderr.close)
620 out, err = p.communicate()
621 self.assertEqual(p.returncode, 0, err)
622 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000623
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200624 def test_stdout_devnull(self):
625 p = subprocess.Popen([sys.executable, "-c",
626 'for i in range(10240):'
627 'print("x" * 1024)'],
628 stdout=subprocess.DEVNULL)
629 p.wait()
630 self.assertEqual(p.stdout, None)
631
632 def test_stderr_devnull(self):
633 p = subprocess.Popen([sys.executable, "-c",
634 'import sys\n'
635 'for i in range(10240):'
636 'sys.stderr.write("x" * 1024)'],
637 stderr=subprocess.DEVNULL)
638 p.wait()
639 self.assertEqual(p.stderr, None)
640
641 def test_stdin_devnull(self):
642 p = subprocess.Popen([sys.executable, "-c",
643 'import sys;'
644 'sys.stdin.read(1)'],
645 stdin=subprocess.DEVNULL)
646 p.wait()
647 self.assertEqual(p.stdin, None)
648
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000649 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000650 newenv = os.environ.copy()
651 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200652 with subprocess.Popen([sys.executable, "-c",
653 'import sys,os;'
654 'sys.stdout.write(os.getenv("FRUIT"))'],
655 stdout=subprocess.PIPE,
656 env=newenv) as p:
657 stdout, stderr = p.communicate()
658 self.assertEqual(stdout, b"orange")
659
Victor Stinner62d51182011-06-23 01:02:25 +0200660 # Windows requires at least the SYSTEMROOT environment variable to start
661 # Python
662 @unittest.skipIf(sys.platform == 'win32',
663 'cannot test an empty env on Windows')
Gregory P. Smithb3512482017-05-30 14:40:37 -0700664 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
665 'The Python shared library cannot be loaded '
666 'with an empty environment.')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200667 def test_empty_env(self):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700668 """Verify that env={} is as empty as possible."""
669
Gregory P. Smith85aba232017-05-30 16:21:47 -0700670 def is_env_var_to_ignore(n):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700671 """Determine if an environment variable is under our control."""
672 # This excludes some __CF_* and VERSIONER_* keys MacOS insists
673 # on adding even when the environment in exec is empty.
674 # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist.
Gregory P. Smith85aba232017-05-30 16:21:47 -0700675 return ('VERSIONER' in n or '__CF' in n or # MacOS
Ned Deily918edc02017-09-04 00:00:21 -0400676 '__PYVENV_LAUNCHER__' in n or # MacOS framework build
Nick Coghlan6ea41862017-06-11 13:16:15 +1000677 n == 'LD_PRELOAD' or n.startswith('SANDBOX') or # Gentoo
678 n == 'LC_CTYPE') # Locale coercion triggered
Gregory P. Smithb3512482017-05-30 14:40:37 -0700679
Victor Stinnerf1512a22011-06-21 17:18:38 +0200680 with subprocess.Popen([sys.executable, "-c",
Gregory P. Smithb3512482017-05-30 14:40:37 -0700681 'import os; print(list(os.environ.keys()))'],
682 stdout=subprocess.PIPE, env={}) as p:
Victor Stinnerf1512a22011-06-21 17:18:38 +0200683 stdout, stderr = p.communicate()
Gregory P. Smithb3512482017-05-30 14:40:37 -0700684 child_env_names = eval(stdout.strip())
685 self.assertIsInstance(child_env_names, list)
686 child_env_names = [k for k in child_env_names
687 if not is_env_var_to_ignore(k)]
688 self.assertEqual(child_env_names, [])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000689
Serhiy Storchakad174d242017-06-23 19:39:27 +0300690 def test_invalid_cmd(self):
691 # null character in the command name
692 cmd = sys.executable + '\0'
693 with self.assertRaises(ValueError):
694 subprocess.Popen([cmd, "-c", "pass"])
695
696 # null character in the command argument
697 with self.assertRaises(ValueError):
698 subprocess.Popen([sys.executable, "-c", "pass#\0"])
699
700 def test_invalid_env(self):
Ville Skyttä49b27342017-08-03 09:00:59 +0300701 # null character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300702 newenv = os.environ.copy()
703 newenv["FRUIT\0VEGETABLE"] = "cabbage"
704 with self.assertRaises(ValueError):
705 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
706
Ville Skyttä49b27342017-08-03 09:00:59 +0300707 # null character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300708 newenv = os.environ.copy()
709 newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
710 with self.assertRaises(ValueError):
711 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
712
Ville Skyttä49b27342017-08-03 09:00:59 +0300713 # equal character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300714 newenv = os.environ.copy()
715 newenv["FRUIT=ORANGE"] = "lemon"
716 with self.assertRaises(ValueError):
717 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
718
Ville Skyttä49b27342017-08-03 09:00:59 +0300719 # equal character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300720 newenv = os.environ.copy()
721 newenv["FRUIT"] = "orange=lemon"
722 with subprocess.Popen([sys.executable, "-c",
723 'import sys, os;'
724 'sys.stdout.write(os.getenv("FRUIT"))'],
725 stdout=subprocess.PIPE,
726 env=newenv) as p:
727 stdout, stderr = p.communicate()
728 self.assertEqual(stdout, b"orange=lemon")
729
Peter Astrandcbac93c2005-03-03 20:24:28 +0000730 def test_communicate_stdin(self):
731 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000732 'import sys;'
733 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000734 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000735 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000736 self.assertEqual(p.returncode, 1)
737
738 def test_communicate_stdout(self):
739 p = subprocess.Popen([sys.executable, "-c",
740 'import sys; sys.stdout.write("pineapple")'],
741 stdout=subprocess.PIPE)
742 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000743 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000744 self.assertEqual(stderr, None)
745
746 def test_communicate_stderr(self):
747 p = subprocess.Popen([sys.executable, "-c",
748 'import sys; sys.stderr.write("pineapple")'],
749 stderr=subprocess.PIPE)
750 (stdout, stderr) = p.communicate()
751 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000752 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000753
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000754 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000755 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000756 'import sys,os;'
757 'sys.stderr.write("pineapple");'
758 'sys.stdout.write(sys.stdin.read())'],
759 stdin=subprocess.PIPE,
760 stdout=subprocess.PIPE,
761 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000762 self.addCleanup(p.stdout.close)
763 self.addCleanup(p.stderr.close)
764 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000765 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000766 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000767 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000768
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400769 def test_communicate_timeout(self):
770 p = subprocess.Popen([sys.executable, "-c",
771 'import sys,os,time;'
772 'sys.stderr.write("pineapple\\n");'
773 'time.sleep(1);'
774 'sys.stderr.write("pear\\n");'
775 'sys.stdout.write(sys.stdin.read())'],
776 universal_newlines=True,
777 stdin=subprocess.PIPE,
778 stdout=subprocess.PIPE,
779 stderr=subprocess.PIPE)
780 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
781 timeout=0.3)
782 # Make sure we can keep waiting for it, and that we get the whole output
783 # after it completes.
784 (stdout, stderr) = p.communicate()
785 self.assertEqual(stdout, "banana")
786 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
787
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700788 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200789 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400790 p = subprocess.Popen([sys.executable, "-c",
791 'import sys,os,time;'
792 'sys.stdout.write("a" * (64 * 1024));'
793 'time.sleep(0.2);'
794 'sys.stdout.write("a" * (64 * 1024));'
795 'time.sleep(0.2);'
796 'sys.stdout.write("a" * (64 * 1024));'
797 'time.sleep(0.2);'
798 'sys.stdout.write("a" * (64 * 1024));'],
799 stdout=subprocess.PIPE)
800 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
801 (stdout, _) = p.communicate()
802 self.assertEqual(len(stdout), 4 * 64 * 1024)
803
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000804 # Test for the fd leak reported in http://bugs.python.org/issue2791.
805 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000806 for stdin_pipe in (False, True):
807 for stdout_pipe in (False, True):
808 for stderr_pipe in (False, True):
809 options = {}
810 if stdin_pipe:
811 options['stdin'] = subprocess.PIPE
812 if stdout_pipe:
813 options['stdout'] = subprocess.PIPE
814 if stderr_pipe:
815 options['stderr'] = subprocess.PIPE
816 if not options:
817 continue
818 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
819 p.communicate()
820 if p.stdin is not None:
821 self.assertTrue(p.stdin.closed)
822 if p.stdout is not None:
823 self.assertTrue(p.stdout.closed)
824 if p.stderr is not None:
825 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000826
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000827 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000828 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000829 p = subprocess.Popen([sys.executable, "-c",
830 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000831 (stdout, stderr) = p.communicate()
832 self.assertEqual(stdout, None)
833 self.assertEqual(stderr, None)
834
835 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000836 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000837 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000838 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000839 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000840 os.close(x)
841 os.close(y)
842 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000843 'import sys,os;'
844 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200845 'sys.stderr.write("x" * %d);'
846 'sys.stdout.write(sys.stdin.read())' %
847 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000848 stdin=subprocess.PIPE,
849 stdout=subprocess.PIPE,
850 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000851 self.addCleanup(p.stdout.close)
852 self.addCleanup(p.stderr.close)
853 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200854 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000855 (stdout, stderr) = p.communicate(string_to_write)
856 self.assertEqual(stdout, string_to_write)
857
858 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000859 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000860 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000861 'import sys,os;'
862 'sys.stdout.write(sys.stdin.read())'],
863 stdin=subprocess.PIPE,
864 stdout=subprocess.PIPE,
865 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000866 self.addCleanup(p.stdout.close)
867 self.addCleanup(p.stderr.close)
868 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000869 p.stdin.write(b"banana")
870 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000871 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000872 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000873
andyclegg7fed7bd2017-10-23 03:01:19 +0100874 def test_universal_newlines_and_text(self):
875 args = [
876 sys.executable, "-c",
877 'import sys,os;' + SETBINARY +
878 'buf = sys.stdout.buffer;'
879 'buf.write(sys.stdin.readline().encode());'
880 'buf.flush();'
881 'buf.write(b"line2\\n");'
882 'buf.flush();'
883 'buf.write(sys.stdin.read().encode());'
884 'buf.flush();'
885 'buf.write(b"line4\\n");'
886 'buf.flush();'
887 'buf.write(b"line5\\r\\n");'
888 'buf.flush();'
889 'buf.write(b"line6\\r");'
890 'buf.flush();'
891 'buf.write(b"\\nline7");'
892 'buf.flush();'
893 'buf.write(b"\\nline8");']
894
895 for extra_kwarg in ('universal_newlines', 'text'):
896 p = subprocess.Popen(args, **{'stdin': subprocess.PIPE,
897 'stdout': subprocess.PIPE,
898 extra_kwarg: True})
899 with p:
900 p.stdin.write("line1\n")
901 p.stdin.flush()
902 self.assertEqual(p.stdout.readline(), "line1\n")
903 p.stdin.write("line3\n")
904 p.stdin.close()
905 self.addCleanup(p.stdout.close)
906 self.assertEqual(p.stdout.readline(),
907 "line2\n")
908 self.assertEqual(p.stdout.read(6),
909 "line3\n")
910 self.assertEqual(p.stdout.read(),
911 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000912
913 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000914 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000915 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000916 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200917 'buf = sys.stdout.buffer;'
918 'buf.write(b"line2\\n");'
919 'buf.flush();'
920 'buf.write(b"line4\\n");'
921 'buf.flush();'
922 'buf.write(b"line5\\r\\n");'
923 'buf.flush();'
924 'buf.write(b"line6\\r");'
925 'buf.flush();'
926 'buf.write(b"\\nline7");'
927 'buf.flush();'
928 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200929 stderr=subprocess.PIPE,
930 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000931 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000932 self.addCleanup(p.stdout.close)
933 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000934 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200935 self.assertEqual(stdout,
936 "line2\nline4\nline5\nline6\nline7\nline8")
937
938 def test_universal_newlines_communicate_stdin(self):
939 # universal newlines through communicate(), with only stdin
940 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300941 'import sys,os;' + SETBINARY + textwrap.dedent('''
942 s = sys.stdin.readline()
943 assert s == "line1\\n", repr(s)
944 s = sys.stdin.read()
945 assert s == "line3\\n", repr(s)
946 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200947 stdin=subprocess.PIPE,
948 universal_newlines=1)
949 (stdout, stderr) = p.communicate("line1\nline3\n")
950 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000951
Andrew Svetlovf3765072012-08-14 18:35:17 +0300952 def test_universal_newlines_communicate_input_none(self):
953 # Test communicate(input=None) with universal newlines.
954 #
955 # We set stdout to PIPE because, as of this writing, a different
956 # code path is tested when the number of pipes is zero or one.
957 p = subprocess.Popen([sys.executable, "-c", "pass"],
958 stdin=subprocess.PIPE,
959 stdout=subprocess.PIPE,
960 universal_newlines=True)
961 p.communicate()
962 self.assertEqual(p.returncode, 0)
963
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300964 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300965 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300966 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300967 'import sys,os;' + SETBINARY + textwrap.dedent('''
968 s = sys.stdin.buffer.readline()
969 sys.stdout.buffer.write(s)
970 sys.stdout.buffer.write(b"line2\\r")
971 sys.stderr.buffer.write(b"eline2\\n")
972 s = sys.stdin.buffer.read()
973 sys.stdout.buffer.write(s)
974 sys.stdout.buffer.write(b"line4\\n")
975 sys.stdout.buffer.write(b"line5\\r\\n")
976 sys.stderr.buffer.write(b"eline6\\r")
977 sys.stderr.buffer.write(b"eline7\\r\\nz")
978 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300979 stdin=subprocess.PIPE,
980 stderr=subprocess.PIPE,
981 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300982 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300983 self.addCleanup(p.stdout.close)
984 self.addCleanup(p.stderr.close)
985 (stdout, stderr) = p.communicate("line1\nline3\n")
986 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300987 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300988 # Python debug build push something like "[42442 refs]\n"
989 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300990 # Don't use assertStderrEqual because it strips CR and LF from output.
991 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300992
Andrew Svetlov82860712012-08-19 22:13:41 +0300993 def test_universal_newlines_communicate_encodings(self):
994 # Check that universal newlines mode works for various encodings,
995 # in particular for encodings in the UTF-16 and UTF-32 families.
996 # See issue #15595.
997 #
998 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
999 # without, and UTF-16 and UTF-32.
1000 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +03001001 code = ("import sys; "
1002 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
1003 encoding)
1004 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -07001005 # We set stdin to be non-None because, as of this writing,
1006 # a different code path is used when the number of pipes is
1007 # zero or one.
1008 popen = subprocess.Popen(args,
1009 stdin=subprocess.PIPE,
1010 stdout=subprocess.PIPE,
1011 encoding=encoding)
1012 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +03001013 self.assertEqual(stdout, '1\n2\n3\n4')
1014
Steve Dower050acae2016-09-06 20:16:17 -07001015 def test_communicate_errors(self):
1016 for errors, expected in [
1017 ('ignore', ''),
1018 ('replace', '\ufffd\ufffd'),
1019 ('surrogateescape', '\udc80\udc80'),
1020 ('backslashreplace', '\\x80\\x80'),
1021 ]:
1022 code = ("import sys; "
1023 r"sys.stdout.buffer.write(b'[\x80\x80]')")
1024 args = [sys.executable, '-c', code]
1025 # We set stdin to be non-None because, as of this writing,
1026 # a different code path is used when the number of pipes is
1027 # zero or one.
1028 popen = subprocess.Popen(args,
1029 stdin=subprocess.PIPE,
1030 stdout=subprocess.PIPE,
1031 encoding='utf-8',
1032 errors=errors)
1033 stdout, stderr = popen.communicate(input='')
1034 self.assertEqual(stdout, '[{}]'.format(expected))
1035
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001036 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +00001037 # Make sure we leak no resources
Victor Stinner937ee9e2018-06-26 02:11:06 +02001038 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +00001039 max_handles = 1026 # too much for most UNIX systems
1040 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +00001041 max_handles = 2050 # too much for (at least some) Windows setups
1042 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001043 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +00001044 try:
1045 for i in range(max_handles):
1046 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001047 tmpfile = os.path.join(tmpdir, support.TESTFN)
1048 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +00001049 except OSError as e:
1050 if e.errno != errno.EMFILE:
1051 raise
1052 break
1053 else:
1054 self.skipTest("failed to reach the file descriptor limit "
1055 "(tried %d)" % max_handles)
1056 # Close a couple of them (should be enough for a subprocess)
1057 for i in range(10):
1058 os.close(handles.pop())
1059 # Loop creating some subprocesses. If one of them leaks some fds,
1060 # the next loop iteration will fail by reaching the max fd limit.
1061 for i in range(15):
1062 p = subprocess.Popen([sys.executable, "-c",
1063 "import sys;"
1064 "sys.stdout.write(sys.stdin.read())"],
1065 stdin=subprocess.PIPE,
1066 stdout=subprocess.PIPE,
1067 stderr=subprocess.PIPE)
1068 data = p.communicate(b"lime")[0]
1069 self.assertEqual(data, b"lime")
1070 finally:
1071 for h in handles:
1072 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001073 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001074
1075 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001076 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
1077 '"a b c" d e')
1078 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
1079 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +00001080 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
1081 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001082 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
1083 'a\\\\\\b "de fg" h')
1084 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
1085 'a\\\\\\"b c d')
1086 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
1087 '"a\\\\b c" d e')
1088 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
1089 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001090 self.assertEqual(subprocess.list2cmdline(['ab', '']),
1091 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001092
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001093 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001094 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +02001095 "import os; os.read(0, 1)"],
1096 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001097 self.addCleanup(p.stdin.close)
1098 self.assertIsNone(p.poll())
1099 os.write(p.stdin.fileno(), b'A')
1100 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001101 # Subsequent invocations should just return the returncode
1102 self.assertEqual(p.poll(), 0)
1103
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001104 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001105 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001106 self.assertEqual(p.wait(), 0)
1107 # Subsequent invocations should just return the returncode
1108 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001109
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001110 def test_wait_timeout(self):
1111 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001112 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001113 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001114 p.wait(timeout=0.0001)
1115 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -04001116 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
1117 # time to start.
1118 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001119
Peter Astrand738131d2004-11-30 21:04:45 +00001120 def test_invalid_bufsize(self):
1121 # an invalid type of the bufsize argument should raise
1122 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001123 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +00001124 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001125
Guido van Rossum46a05a72007-06-07 21:56:45 +00001126 def test_bufsize_is_none(self):
1127 # bufsize=None should be the same as bufsize=0.
1128 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
1129 self.assertEqual(p.wait(), 0)
1130 # Again with keyword arg
1131 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
1132 self.assertEqual(p.wait(), 0)
1133
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001134 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1135 # subprocess may deadlock with bufsize=1, see issue #21332
1136 with subprocess.Popen([sys.executable, "-c", "import sys;"
1137 "sys.stdout.write(sys.stdin.readline());"
1138 "sys.stdout.flush()"],
1139 stdin=subprocess.PIPE,
1140 stdout=subprocess.PIPE,
1141 stderr=subprocess.DEVNULL,
1142 bufsize=1,
1143 universal_newlines=universal_newlines) as p:
1144 p.stdin.write(line) # expect that it flushes the line in text mode
1145 os.close(p.stdin.fileno()) # close it without flushing the buffer
1146 read_line = p.stdout.readline()
Segev Finer4d385172017-08-18 16:18:13 +03001147 with support.SuppressCrashReport():
1148 try:
1149 p.stdin.close()
1150 except OSError:
1151 pass
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001152 p.stdin = None
1153 self.assertEqual(p.returncode, 0)
1154 self.assertEqual(read_line, expected)
1155
1156 def test_bufsize_equal_one_text_mode(self):
1157 # line is flushed in text mode with bufsize=1.
1158 # we should get the full line in return
1159 line = "line\n"
1160 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1161
1162 def test_bufsize_equal_one_binary_mode(self):
1163 # line is not flushed in binary mode with bufsize=1.
1164 # we should get empty response
1165 line = b'line' + os.linesep.encode() # assume ascii-based locale
Alexey Izbysheva2670562018-10-20 03:22:31 +03001166 with self.assertWarnsRegex(RuntimeWarning, 'line buffering'):
1167 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001168
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001169 def test_leaking_fds_on_error(self):
1170 # see bug #5179: Popen leaks file descriptors to PIPEs if
1171 # the child fails to execute; this will eventually exhaust
1172 # the maximum number of open fds. 1024 seems a very common
1173 # value for that limit, but Windows has 2048, so we loop
1174 # 1024 times (each call leaked two fds).
1175 for i in range(1024):
Victor Stinnerb31206a2018-01-25 19:06:05 +01001176 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02001177 subprocess.Popen(NONEXISTING_CMD,
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001178 stdout=subprocess.PIPE,
1179 stderr=subprocess.PIPE)
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001180
Victor Stinner9a83f652017-08-21 23:51:31 +02001181 def test_nonexisting_with_pipes(self):
1182 # bpo-30121: Popen with pipes must close properly pipes on error.
1183 # Previously, os.close() was called with a Windows handle which is not
1184 # a valid file descriptor.
1185 #
1186 # Run the test in a subprocess to control how the CRT reports errors
1187 # and to get stderr content.
1188 try:
1189 import msvcrt
1190 msvcrt.CrtSetReportMode
1191 except (AttributeError, ImportError):
1192 self.skipTest("need msvcrt.CrtSetReportMode")
1193
1194 code = textwrap.dedent(f"""
1195 import msvcrt
1196 import subprocess
1197
1198 cmd = {NONEXISTING_CMD!r}
1199
1200 for report_type in [msvcrt.CRT_WARN,
1201 msvcrt.CRT_ERROR,
1202 msvcrt.CRT_ASSERT]:
1203 msvcrt.CrtSetReportMode(report_type, msvcrt.CRTDBG_MODE_FILE)
1204 msvcrt.CrtSetReportFile(report_type, msvcrt.CRTDBG_FILE_STDERR)
1205
1206 try:
Zachary Ware55376462018-02-19 14:02:38 -06001207 subprocess.Popen(cmd,
Victor Stinner9a83f652017-08-21 23:51:31 +02001208 stdout=subprocess.PIPE,
1209 stderr=subprocess.PIPE)
1210 except OSError:
1211 pass
1212 """)
1213 cmd = [sys.executable, "-c", code]
1214 proc = subprocess.Popen(cmd,
1215 stderr=subprocess.PIPE,
1216 universal_newlines=True)
1217 with proc:
1218 stderr = proc.communicate()[1]
1219 self.assertEqual(stderr, "")
1220 self.assertEqual(proc.returncode, 0)
1221
Antoine Pitroua8392712013-08-30 23:38:13 +02001222 def test_double_close_on_error(self):
1223 # Issue #18851
1224 fds = []
1225 def open_fds():
1226 for i in range(20):
1227 fds.extend(os.pipe())
1228 time.sleep(0.001)
1229 t = threading.Thread(target=open_fds)
1230 t.start()
1231 try:
1232 with self.assertRaises(EnvironmentError):
Victor Stinner9a83f652017-08-21 23:51:31 +02001233 subprocess.Popen(NONEXISTING_CMD,
Antoine Pitroua8392712013-08-30 23:38:13 +02001234 stdin=subprocess.PIPE,
1235 stdout=subprocess.PIPE,
1236 stderr=subprocess.PIPE)
1237 finally:
1238 t.join()
1239 exc = None
1240 for fd in fds:
1241 # If a double close occurred, some of those fds will
1242 # already have been closed by mistake, and os.close()
1243 # here will raise.
1244 try:
1245 os.close(fd)
1246 except OSError as e:
1247 exc = e
1248 if exc is not None:
1249 raise exc
1250
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001251 def test_threadsafe_wait(self):
1252 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1253 proc = subprocess.Popen([sys.executable, '-c',
1254 'import time; time.sleep(12)'])
1255 self.assertEqual(proc.returncode, None)
1256 results = []
1257
1258 def kill_proc_timer_thread():
1259 results.append(('thread-start-poll-result', proc.poll()))
1260 # terminate it from the thread and wait for the result.
1261 proc.kill()
1262 proc.wait()
1263 results.append(('thread-after-kill-and-wait', proc.returncode))
1264 # this wait should be a no-op given the above.
1265 proc.wait()
1266 results.append(('thread-after-second-wait', proc.returncode))
1267
1268 # This is a timing sensitive test, the failure mode is
1269 # triggered when both the main thread and this thread are in
1270 # the wait() call at once. The delay here is to allow the
1271 # main thread to most likely be blocked in its wait() call.
1272 t = threading.Timer(0.2, kill_proc_timer_thread)
1273 t.start()
1274
Victor Stinner937ee9e2018-06-26 02:11:06 +02001275 if mswindows:
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001276 expected_errorcode = 1
1277 else:
1278 # Should be -9 because of the proc.kill() from the thread.
1279 expected_errorcode = -9
1280
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001281 # Wait for the process to finish; the thread should kill it
1282 # long before it finishes on its own. Supplying a timeout
1283 # triggers a different code path for better coverage.
1284 proc.wait(timeout=20)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001285 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001286 msg="unexpected result in wait from main thread")
1287
1288 # This should be a no-op with no change in returncode.
1289 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001290 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001291 msg="unexpected result in second main wait.")
1292
1293 t.join()
1294 # Ensure that all of the thread results are as expected.
1295 # When a race condition occurs in wait(), the returncode could
1296 # be set by the wrong thread that doesn't actually have it
1297 # leading to an incorrect value.
1298 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001299 ('thread-after-kill-and-wait', expected_errorcode),
1300 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001301 results)
1302
Victor Stinnerb3693582010-05-21 20:13:12 +00001303 def test_issue8780(self):
1304 # Ensure that stdout is inherited from the parent
1305 # if stdout=PIPE is not used
1306 code = ';'.join((
1307 'import subprocess, sys',
1308 'retcode = subprocess.call('
1309 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1310 'assert retcode == 0'))
1311 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001312 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001313
Tim Goldenaf5ac392010-08-06 13:03:56 +00001314 def test_handles_closed_on_exception(self):
1315 # If CreateProcess exits with an error, ensure the
1316 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001317 ifhandle, ifname = tempfile.mkstemp()
1318 ofhandle, ofname = tempfile.mkstemp()
1319 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001320 try:
1321 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1322 stderr=efhandle)
1323 except OSError:
1324 os.close(ifhandle)
1325 os.remove(ifname)
1326 os.close(ofhandle)
1327 os.remove(ofname)
1328 os.close(efhandle)
1329 os.remove(efname)
1330 self.assertFalse(os.path.exists(ifname))
1331 self.assertFalse(os.path.exists(ofname))
1332 self.assertFalse(os.path.exists(efname))
1333
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001334 def test_communicate_epipe(self):
1335 # Issue 10963: communicate() should hide EPIPE
1336 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1337 stdin=subprocess.PIPE,
1338 stdout=subprocess.PIPE,
1339 stderr=subprocess.PIPE)
1340 self.addCleanup(p.stdout.close)
1341 self.addCleanup(p.stderr.close)
1342 self.addCleanup(p.stdin.close)
1343 p.communicate(b"x" * 2**20)
1344
1345 def test_communicate_epipe_only_stdin(self):
1346 # Issue 10963: communicate() should hide EPIPE
1347 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1348 stdin=subprocess.PIPE)
1349 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001350 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001351 p.communicate(b"x" * 2**20)
1352
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001353 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1354 "Requires signal.SIGUSR1")
1355 @unittest.skipUnless(hasattr(os, 'kill'),
1356 "Requires os.kill")
1357 @unittest.skipUnless(hasattr(os, 'getppid'),
1358 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001359 def test_communicate_eintr(self):
1360 # Issue #12493: communicate() should handle EINTR
1361 def handler(signum, frame):
1362 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001363 old_handler = signal.signal(signal.SIGUSR1, handler)
1364 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001365
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001366 args = [sys.executable, "-c",
1367 'import os, signal;'
1368 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001369 for stream in ('stdout', 'stderr'):
1370 kw = {stream: subprocess.PIPE}
1371 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001372 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001373 process.communicate()
1374
Tim Peterse718f612004-10-12 21:51:32 +00001375
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001376 # This test is Linux-ish specific for simplicity to at least have
1377 # some coverage. It is not a platform specific bug.
1378 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1379 "Linux specific")
1380 def test_failed_child_execute_fd_leak(self):
1381 """Test for the fork() failure fd leak reported in issue16327."""
1382 fd_directory = '/proc/%d/fd' % os.getpid()
1383 fds_before_popen = os.listdir(fd_directory)
1384 with self.assertRaises(PopenTestException):
1385 PopenExecuteChildRaises(
1386 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
1387 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1388
1389 # NOTE: This test doesn't verify that the real _execute_child
1390 # does not close the file descriptors itself on the way out
1391 # during an exception. Code inspection has confirmed that.
1392
1393 fds_after_exception = os.listdir(fd_directory)
1394 self.assertEqual(fds_before_popen, fds_after_exception)
1395
Victor Stinner937ee9e2018-06-26 02:11:06 +02001396 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001397 def test_file_not_found_includes_filename(self):
1398 with self.assertRaises(FileNotFoundError) as c:
1399 subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args'])
1400 self.assertEqual(c.exception.filename, '/opt/nonexistent_binary')
1401
Victor Stinner937ee9e2018-06-26 02:11:06 +02001402 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001403 def test_file_not_found_with_bad_cwd(self):
1404 with self.assertRaises(FileNotFoundError) as c:
1405 subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory')
1406 self.assertEqual(c.exception.filename, '/some/nonexistent/directory')
1407
Gregory P. Smith6e730002015-04-14 16:14:25 -07001408
1409class RunFuncTestCase(BaseTestCase):
1410 def run_python(self, code, **kwargs):
1411 """Run Python code in a subprocess using subprocess.run"""
1412 argv = [sys.executable, "-c", code]
1413 return subprocess.run(argv, **kwargs)
1414
1415 def test_returncode(self):
1416 # call() function with sequence argument
1417 cp = self.run_python("import sys; sys.exit(47)")
1418 self.assertEqual(cp.returncode, 47)
1419 with self.assertRaises(subprocess.CalledProcessError):
1420 cp.check_returncode()
1421
1422 def test_check(self):
1423 with self.assertRaises(subprocess.CalledProcessError) as c:
1424 self.run_python("import sys; sys.exit(47)", check=True)
1425 self.assertEqual(c.exception.returncode, 47)
1426
1427 def test_check_zero(self):
1428 # check_returncode shouldn't raise when returncode is zero
1429 cp = self.run_python("import sys; sys.exit(0)", check=True)
1430 self.assertEqual(cp.returncode, 0)
1431
1432 def test_timeout(self):
1433 # run() function with timeout argument; we want to test that the child
1434 # process gets killed when the timeout expires. If the child isn't
1435 # killed, this call will deadlock since subprocess.run waits for the
1436 # child.
1437 with self.assertRaises(subprocess.TimeoutExpired):
1438 self.run_python("while True: pass", timeout=0.0001)
1439
1440 def test_capture_stdout(self):
1441 # capture stdout with zero return code
1442 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1443 self.assertIn(b'BDFL', cp.stdout)
1444
1445 def test_capture_stderr(self):
1446 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1447 stderr=subprocess.PIPE)
1448 self.assertIn(b'BDFL', cp.stderr)
1449
1450 def test_check_output_stdin_arg(self):
1451 # run() can be called with stdin set to a file
1452 tf = tempfile.TemporaryFile()
1453 self.addCleanup(tf.close)
1454 tf.write(b'pear')
1455 tf.seek(0)
1456 cp = self.run_python(
1457 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1458 stdin=tf, stdout=subprocess.PIPE)
1459 self.assertIn(b'PEAR', cp.stdout)
1460
1461 def test_check_output_input_arg(self):
1462 # check_output() can be called with input set to a string
1463 cp = self.run_python(
1464 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1465 input=b'pear', stdout=subprocess.PIPE)
1466 self.assertIn(b'PEAR', cp.stdout)
1467
1468 def test_check_output_stdin_with_input_arg(self):
1469 # run() refuses to accept 'stdin' with 'input'
1470 tf = tempfile.TemporaryFile()
1471 self.addCleanup(tf.close)
1472 tf.write(b'pear')
1473 tf.seek(0)
1474 with self.assertRaises(ValueError,
1475 msg="Expected ValueError when stdin and input args supplied.") as c:
1476 output = self.run_python("print('will not be run')",
1477 stdin=tf, input=b'hare')
1478 self.assertIn('stdin', c.exception.args[0])
1479 self.assertIn('input', c.exception.args[0])
1480
1481 def test_check_output_timeout(self):
1482 with self.assertRaises(subprocess.TimeoutExpired) as c:
1483 cp = self.run_python((
1484 "import sys, time\n"
1485 "sys.stdout.write('BDFL')\n"
1486 "sys.stdout.flush()\n"
1487 "time.sleep(3600)"),
1488 # Some heavily loaded buildbots (sparc Debian 3.x) require
1489 # this much time to start and print.
1490 timeout=3, stdout=subprocess.PIPE)
1491 self.assertEqual(c.exception.output, b'BDFL')
1492 # output is aliased to stdout
1493 self.assertEqual(c.exception.stdout, b'BDFL')
1494
1495 def test_run_kwargs(self):
1496 newenv = os.environ.copy()
1497 newenv["FRUIT"] = "banana"
1498 cp = self.run_python(('import sys, os;'
1499 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1500 env=newenv)
1501 self.assertEqual(cp.returncode, 33)
1502
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001503 def test_run_with_pathlike_path(self):
1504 # bpo-31961: test run(pathlike_object)
1505 # the name of a command that can be run without
1506 # any argumenets that exit fast
1507 prog = 'tree.com' if mswindows else 'ls'
1508 path = shutil.which(prog)
1509 if path is None:
1510 self.skipTest(f'{prog} required for this test')
1511 path = FakePath(path)
1512 res = subprocess.run(path, stdout=subprocess.DEVNULL)
1513 self.assertEqual(res.returncode, 0)
1514 with self.assertRaises(TypeError):
1515 subprocess.run(path, stdout=subprocess.DEVNULL, shell=True)
1516
1517 def test_run_with_bytes_path_and_arguments(self):
1518 # bpo-31961: test run([bytes_object, b'additional arguments'])
1519 path = os.fsencode(sys.executable)
1520 args = [path, '-c', b'import sys; sys.exit(57)']
1521 res = subprocess.run(args)
1522 self.assertEqual(res.returncode, 57)
1523
1524 def test_run_with_pathlike_path_and_arguments(self):
1525 # bpo-31961: test run([pathlike_object, 'additional arguments'])
1526 path = FakePath(sys.executable)
1527 args = [path, '-c', 'import sys; sys.exit(57)']
1528 res = subprocess.run(args)
1529 self.assertEqual(res.returncode, 57)
1530
Bo Baylesce0f33d2018-01-30 00:40:39 -06001531 def test_capture_output(self):
1532 cp = self.run_python(("import sys;"
1533 "sys.stdout.write('BDFL'); "
1534 "sys.stderr.write('FLUFL')"),
1535 capture_output=True)
1536 self.assertIn(b'BDFL', cp.stdout)
1537 self.assertIn(b'FLUFL', cp.stderr)
1538
1539 def test_stdout_with_capture_output_arg(self):
1540 # run() refuses to accept 'stdout' with 'capture_output'
1541 tf = tempfile.TemporaryFile()
1542 self.addCleanup(tf.close)
1543 with self.assertRaises(ValueError,
1544 msg=("Expected ValueError when stdout and capture_output "
1545 "args supplied.")) as c:
1546 output = self.run_python("print('will not be run')",
1547 capture_output=True, stdout=tf)
1548 self.assertIn('stdout', c.exception.args[0])
1549 self.assertIn('capture_output', c.exception.args[0])
1550
1551 def test_stderr_with_capture_output_arg(self):
1552 # run() refuses to accept 'stderr' with 'capture_output'
1553 tf = tempfile.TemporaryFile()
1554 self.addCleanup(tf.close)
1555 with self.assertRaises(ValueError,
1556 msg=("Expected ValueError when stderr and capture_output "
1557 "args supplied.")) as c:
1558 output = self.run_python("print('will not be run')",
1559 capture_output=True, stderr=tf)
1560 self.assertIn('stderr', c.exception.args[0])
1561 self.assertIn('capture_output', c.exception.args[0])
1562
Gregory P. Smith6e730002015-04-14 16:14:25 -07001563
Victor Stinner937ee9e2018-06-26 02:11:06 +02001564@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001565class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001566
Gregory P. Smith5591b022012-10-10 03:34:47 -07001567 def setUp(self):
1568 super().setUp()
1569 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1570
1571 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001572 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001573 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001574 except OSError as e:
1575 # This avoids hard coding the errno value or the OS perror()
1576 # string and instead capture the exception that we want to see
1577 # below for comparison.
1578 desired_exception = e
1579 else:
Martin Pantereb995702016-07-28 01:11:04 +00001580 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001581 self._nonexistent_dir)
1582 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001583
Gregory P. Smith5591b022012-10-10 03:34:47 -07001584 def test_exception_cwd(self):
1585 """Test error in the child raised in the parent for a bad cwd."""
1586 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001587 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001588 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001589 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001590 except OSError as e:
1591 # Test that the child process chdir failure actually makes
1592 # it up to the parent process as the correct exception.
1593 self.assertEqual(desired_exception.errno, e.errno)
1594 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001595 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001596 else:
1597 self.fail("Expected OSError: %s" % desired_exception)
1598
Gregory P. Smith5591b022012-10-10 03:34:47 -07001599 def test_exception_bad_executable(self):
1600 """Test error in the child raised in the parent for a bad executable."""
1601 desired_exception = self._get_chdir_exception()
1602 try:
1603 p = subprocess.Popen([sys.executable, "-c", ""],
1604 executable=self._nonexistent_dir)
1605 except OSError as e:
1606 # Test that the child process exec failure actually makes
1607 # it up to the parent process as the correct exception.
1608 self.assertEqual(desired_exception.errno, e.errno)
1609 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001610 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001611 else:
1612 self.fail("Expected OSError: %s" % desired_exception)
1613
1614 def test_exception_bad_args_0(self):
1615 """Test error in the child raised in the parent for a bad args[0]."""
1616 desired_exception = self._get_chdir_exception()
1617 try:
1618 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1619 except OSError as e:
1620 # Test that the child process exec failure actually makes
1621 # it up to the parent process as the correct exception.
1622 self.assertEqual(desired_exception.errno, e.errno)
1623 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001624 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001625 else:
1626 self.fail("Expected OSError: %s" % desired_exception)
1627
Ammar Askar3fc499b2017-09-06 02:41:30 -04001628 # We mock the __del__ method for Popen in the next two tests
1629 # because it does cleanup based on the pid returned by fork_exec
1630 # along with issuing a resource warning if it still exists. Since
1631 # we don't actually spawn a process in these tests we can forego
1632 # the destructor. An alternative would be to set _child_created to
1633 # False before the destructor is called but there is no easy way
1634 # to do that
1635 class PopenNoDestructor(subprocess.Popen):
1636 def __del__(self):
1637 pass
1638
1639 @mock.patch("subprocess._posixsubprocess.fork_exec")
1640 def test_exception_errpipe_normal(self, fork_exec):
1641 """Test error passing done through errpipe_write in the good case"""
1642 def proper_error(*args):
1643 errpipe_write = args[13]
1644 # Write the hex for the error code EISDIR: 'is a directory'
1645 err_code = '{:x}'.format(errno.EISDIR).encode()
1646 os.write(errpipe_write, b"OSError:" + err_code + b":")
1647 return 0
1648
1649 fork_exec.side_effect = proper_error
1650
Victor Stinner11045c92017-10-05 06:32:53 -07001651 with mock.patch("subprocess.os.waitpid",
1652 side_effect=ChildProcessError):
1653 with self.assertRaises(IsADirectoryError):
1654 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001655
1656 @mock.patch("subprocess._posixsubprocess.fork_exec")
1657 def test_exception_errpipe_bad_data(self, fork_exec):
1658 """Test error passing done through errpipe_write where its not
1659 in the expected format"""
1660 error_data = b"\xFF\x00\xDE\xAD"
1661 def bad_error(*args):
1662 errpipe_write = args[13]
1663 # Anything can be in the pipe, no assumptions should
1664 # be made about its encoding, so we'll write some
1665 # arbitrary hex bytes to test it out
1666 os.write(errpipe_write, error_data)
1667 return 0
1668
1669 fork_exec.side_effect = bad_error
1670
Victor Stinner11045c92017-10-05 06:32:53 -07001671 with mock.patch("subprocess.os.waitpid",
1672 side_effect=ChildProcessError):
1673 with self.assertRaises(subprocess.SubprocessError) as e:
1674 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001675
1676 self.assertIn(repr(error_data), str(e.exception))
1677
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001678 @unittest.skipIf(not os.path.exists('/proc/self/status'),
1679 "need /proc/self/status")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001680 def test_restore_signals(self):
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001681 # Blindly assume that cat exists on systems with /proc/self/status...
1682 default_proc_status = subprocess.check_output(
1683 ['cat', '/proc/self/status'],
1684 restore_signals=False)
1685 for line in default_proc_status.splitlines():
1686 if line.startswith(b'SigIgn'):
1687 default_sig_ign_mask = line
1688 break
1689 else:
1690 self.skipTest("SigIgn not found in /proc/self/status.")
1691 restored_proc_status = subprocess.check_output(
1692 ['cat', '/proc/self/status'],
1693 restore_signals=True)
1694 for line in restored_proc_status.splitlines():
1695 if line.startswith(b'SigIgn'):
1696 restored_sig_ign_mask = line
1697 break
1698 self.assertNotEqual(default_sig_ign_mask, restored_sig_ign_mask,
1699 msg="restore_signals=True should've unblocked "
1700 "SIGPIPE and friends.")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001701
1702 def test_start_new_session(self):
1703 # For code coverage of calling setsid(). We don't care if we get an
1704 # EPERM error from it depending on the test execution environment, that
1705 # still indicates that it was called.
1706 try:
1707 output = subprocess.check_output(
1708 [sys.executable, "-c",
1709 "import os; print(os.getpgid(os.getpid()))"],
1710 start_new_session=True)
1711 except OSError as e:
1712 if e.errno != errno.EPERM:
1713 raise
1714 else:
1715 parent_pgid = os.getpgid(os.getpid())
1716 child_pgid = int(output)
1717 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001718
1719 def test_run_abort(self):
1720 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001721 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001722 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001723 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001724 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001725 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001726
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001727 def test_CalledProcessError_str_signal(self):
1728 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
1729 error_string = str(err)
1730 # We're relying on the repr() of the signal.Signals intenum to provide
1731 # the word signal, the signal name and the numeric value.
1732 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00001733 # We're not being specific about the signal name as some signals have
1734 # multiple names and which name is revealed can vary.
1735 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001736 self.assertIn(str(signal.SIGABRT), error_string)
1737
1738 def test_CalledProcessError_str_unknown_signal(self):
1739 err = subprocess.CalledProcessError(-9876543, "fake cmd")
1740 error_string = str(err)
1741 self.assertIn("unknown signal 9876543.", error_string)
1742
1743 def test_CalledProcessError_str_non_zero(self):
1744 err = subprocess.CalledProcessError(2, "fake cmd")
1745 error_string = str(err)
1746 self.assertIn("non-zero exit status 2.", error_string)
1747
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001748 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001749 # DISCLAIMER: Setting environment variables is *not* a good use
1750 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001751 p = subprocess.Popen([sys.executable, "-c",
1752 'import sys,os;'
1753 'sys.stdout.write(os.getenv("FRUIT"))'],
1754 stdout=subprocess.PIPE,
1755 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02001756 with p:
1757 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001758
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001759 def test_preexec_exception(self):
1760 def raise_it():
1761 raise ValueError("What if two swallows carried a coconut?")
1762 try:
1763 p = subprocess.Popen([sys.executable, "-c", ""],
1764 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001765 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001766 self.assertTrue(
1767 subprocess._posixsubprocess,
1768 "Expected a ValueError from the preexec_fn")
1769 except ValueError as e:
1770 self.assertIn("coconut", e.args[0])
1771 else:
1772 self.fail("Exception raised by preexec_fn did not make it "
1773 "to the parent process.")
1774
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001775 class _TestExecuteChildPopen(subprocess.Popen):
1776 """Used to test behavior at the end of _execute_child."""
1777 def __init__(self, testcase, *args, **kwargs):
1778 self._testcase = testcase
1779 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001780
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001781 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001782 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001783 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001784 finally:
1785 # Open a bunch of file descriptors and verify that
1786 # none of them are the same as the ones the Popen
1787 # instance is using for stdin/stdout/stderr.
1788 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1789 for _ in range(8)]
1790 try:
1791 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001792 self._testcase.assertNotIn(
1793 fd, (self.stdin.fileno(), self.stdout.fileno(),
1794 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001795 msg="At least one fd was closed early.")
1796 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01001797 for fd in devzero_fds:
1798 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001799
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001800 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1801 def test_preexec_errpipe_does_not_double_close_pipes(self):
1802 """Issue16140: Don't double close pipes on preexec error."""
1803
1804 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08001805 raise subprocess.SubprocessError(
1806 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001807
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08001808 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001809 self._TestExecuteChildPopen(
1810 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001811 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1812 stderr=subprocess.PIPE, preexec_fn=raise_it)
1813
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001814 def test_preexec_gc_module_failure(self):
1815 # This tests the code that disables garbage collection if the child
1816 # process will execute any Python.
1817 def raise_runtime_error():
1818 raise RuntimeError("this shouldn't escape")
1819 enabled = gc.isenabled()
1820 orig_gc_disable = gc.disable
1821 orig_gc_isenabled = gc.isenabled
1822 try:
1823 gc.disable()
1824 self.assertFalse(gc.isenabled())
1825 subprocess.call([sys.executable, '-c', ''],
1826 preexec_fn=lambda: None)
1827 self.assertFalse(gc.isenabled(),
1828 "Popen enabled gc when it shouldn't.")
1829
1830 gc.enable()
1831 self.assertTrue(gc.isenabled())
1832 subprocess.call([sys.executable, '-c', ''],
1833 preexec_fn=lambda: None)
1834 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1835
1836 gc.disable = raise_runtime_error
1837 self.assertRaises(RuntimeError, subprocess.Popen,
1838 [sys.executable, '-c', ''],
1839 preexec_fn=lambda: None)
1840
1841 del gc.isenabled # force an AttributeError
1842 self.assertRaises(AttributeError, subprocess.Popen,
1843 [sys.executable, '-c', ''],
1844 preexec_fn=lambda: None)
1845 finally:
1846 gc.disable = orig_gc_disable
1847 gc.isenabled = orig_gc_isenabled
1848 if not enabled:
1849 gc.disable()
1850
Martin Panterf7fdbda2015-12-05 09:51:52 +00001851 @unittest.skipIf(
1852 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00001853 def test_preexec_fork_failure(self):
1854 # The internal code did not preserve the previous exception when
1855 # re-enabling garbage collection
1856 try:
1857 from resource import getrlimit, setrlimit, RLIMIT_NPROC
1858 except ImportError as err:
1859 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
1860 limits = getrlimit(RLIMIT_NPROC)
1861 [_, hard] = limits
1862 setrlimit(RLIMIT_NPROC, (0, hard))
1863 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00001864 try:
Martin Panterafdd5132015-11-30 02:21:41 +00001865 subprocess.call([sys.executable, '-c', ''],
1866 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00001867 except BlockingIOError:
1868 # Forking should raise EAGAIN, translated to BlockingIOError
1869 pass
1870 else:
1871 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00001872
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001873 def test_args_string(self):
1874 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03001875 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001876 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001877 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001878 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001879 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1880 sys.executable)
1881 os.chmod(fname, 0o700)
1882 p = subprocess.Popen(fname)
1883 p.wait()
1884 os.remove(fname)
1885 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001886
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001887 def test_invalid_args(self):
1888 # invalid arguments should raise ValueError
1889 self.assertRaises(ValueError, subprocess.call,
1890 [sys.executable, "-c",
1891 "import sys; sys.exit(47)"],
1892 startupinfo=47)
1893 self.assertRaises(ValueError, subprocess.call,
1894 [sys.executable, "-c",
1895 "import sys; sys.exit(47)"],
1896 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001897
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001898 def test_shell_sequence(self):
1899 # Run command through the shell (sequence)
1900 newenv = os.environ.copy()
1901 newenv["FRUIT"] = "apple"
1902 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1903 stdout=subprocess.PIPE,
1904 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001905 with p:
1906 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001907
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001908 def test_shell_string(self):
1909 # Run command through the shell (string)
1910 newenv = os.environ.copy()
1911 newenv["FRUIT"] = "apple"
1912 p = subprocess.Popen("echo $FRUIT", shell=1,
1913 stdout=subprocess.PIPE,
1914 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001915 with p:
1916 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001917
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001918 def test_call_string(self):
1919 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03001920 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001921 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001922 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001923 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001924 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1925 sys.executable)
1926 os.chmod(fname, 0o700)
1927 rc = subprocess.call(fname)
1928 os.remove(fname)
1929 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001930
Stefan Krah9542cc62010-07-19 14:20:53 +00001931 def test_specific_shell(self):
1932 # Issue #9265: Incorrect name passed as arg[0].
1933 shells = []
1934 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1935 for name in ['bash', 'ksh']:
1936 sh = os.path.join(prefix, name)
1937 if os.path.isfile(sh):
1938 shells.append(sh)
1939 if not shells: # Will probably work for any shell but csh.
1940 self.skipTest("bash or ksh required for this test")
1941 sh = '/bin/sh'
1942 if os.path.isfile(sh) and not os.path.islink(sh):
1943 # Test will fail if /bin/sh is a symlink to csh.
1944 shells.append(sh)
1945 for sh in shells:
1946 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1947 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02001948 with p:
1949 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00001950
Florent Xicluna4886d242010-03-08 13:27:26 +00001951 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001952 # Do not inherit file handles from the parent.
1953 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07001954 # Also set the SIGINT handler to the default to make sure it's not
1955 # being ignored (some tests rely on that.)
1956 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
1957 try:
1958 p = subprocess.Popen([sys.executable, "-c", """if 1:
1959 import sys, time
1960 sys.stdout.write('x\\n')
1961 sys.stdout.flush()
1962 time.sleep(30)
1963 """],
1964 close_fds=True,
1965 stdin=subprocess.PIPE,
1966 stdout=subprocess.PIPE,
1967 stderr=subprocess.PIPE)
1968 finally:
1969 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001970 # Wait for the interpreter to be completely initialized before
1971 # sending any signal.
1972 p.stdout.read(1)
1973 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001974 return p
1975
Charles-François Natali53221e32013-01-12 16:52:20 +01001976 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1977 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001978 def _kill_dead_process(self, method, *args):
1979 # Do not inherit file handles from the parent.
1980 # It should fix failures on some platforms.
1981 p = subprocess.Popen([sys.executable, "-c", """if 1:
1982 import sys, time
1983 sys.stdout.write('x\\n')
1984 sys.stdout.flush()
1985 """],
1986 close_fds=True,
1987 stdin=subprocess.PIPE,
1988 stdout=subprocess.PIPE,
1989 stderr=subprocess.PIPE)
1990 # Wait for the interpreter to be completely initialized before
1991 # sending any signal.
1992 p.stdout.read(1)
1993 # The process should end after this
1994 time.sleep(1)
1995 # This shouldn't raise even though the child is now dead
1996 getattr(p, method)(*args)
1997 p.communicate()
1998
Florent Xicluna4886d242010-03-08 13:27:26 +00001999 def test_send_signal(self):
2000 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00002001 _, stderr = p.communicate()
2002 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002003 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00002004
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002005 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002006 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00002007 _, stderr = p.communicate()
2008 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002009 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00002010
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002011 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002012 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00002013 _, stderr = p.communicate()
2014 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002015 self.assertEqual(p.wait(), -signal.SIGTERM)
2016
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002017 def test_send_signal_dead(self):
2018 # Sending a signal to a dead process
2019 self._kill_dead_process('send_signal', signal.SIGINT)
2020
2021 def test_kill_dead(self):
2022 # Killing a dead process
2023 self._kill_dead_process('kill')
2024
2025 def test_terminate_dead(self):
2026 # Terminating a dead process
2027 self._kill_dead_process('terminate')
2028
Victor Stinnerdaf45552013-08-28 00:53:59 +02002029 def _save_fds(self, save_fds):
2030 fds = []
2031 for fd in save_fds:
2032 inheritable = os.get_inheritable(fd)
2033 saved = os.dup(fd)
2034 fds.append((fd, saved, inheritable))
2035 return fds
2036
2037 def _restore_fds(self, fds):
2038 for fd, saved, inheritable in fds:
2039 os.dup2(saved, fd, inheritable=inheritable)
2040 os.close(saved)
2041
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002042 def check_close_std_fds(self, fds):
2043 # Issue #9905: test that subprocess pipes still work properly with
2044 # some standard fds closed
2045 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02002046 saved_fds = self._save_fds(fds)
2047 for fd, saved, inheritable in saved_fds:
2048 if fd == 0:
2049 stdin = saved
2050 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002051 try:
2052 for fd in fds:
2053 os.close(fd)
2054 out, err = subprocess.Popen([sys.executable, "-c",
2055 'import sys;'
2056 'sys.stdout.write("apple");'
2057 'sys.stdout.flush();'
2058 'sys.stderr.write("orange")'],
2059 stdin=stdin,
2060 stdout=subprocess.PIPE,
2061 stderr=subprocess.PIPE).communicate()
2062 err = support.strip_python_stderr(err)
2063 self.assertEqual((out, err), (b'apple', b'orange'))
2064 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002065 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002066
2067 def test_close_fd_0(self):
2068 self.check_close_std_fds([0])
2069
2070 def test_close_fd_1(self):
2071 self.check_close_std_fds([1])
2072
2073 def test_close_fd_2(self):
2074 self.check_close_std_fds([2])
2075
2076 def test_close_fds_0_1(self):
2077 self.check_close_std_fds([0, 1])
2078
2079 def test_close_fds_0_2(self):
2080 self.check_close_std_fds([0, 2])
2081
2082 def test_close_fds_1_2(self):
2083 self.check_close_std_fds([1, 2])
2084
2085 def test_close_fds_0_1_2(self):
2086 # Issue #10806: test that subprocess pipes still work properly with
2087 # all standard fds closed.
2088 self.check_close_std_fds([0, 1, 2])
2089
Gregory P. Smith53dd8162013-12-01 16:03:24 -08002090 def test_small_errpipe_write_fd(self):
2091 """Issue #15798: Popen should work when stdio fds are available."""
2092 new_stdin = os.dup(0)
2093 new_stdout = os.dup(1)
2094 try:
2095 os.close(0)
2096 os.close(1)
2097
2098 # Side test: if errpipe_write fails to have its CLOEXEC
2099 # flag set this should cause the parent to think the exec
2100 # failed. Extremely unlikely: everyone supports CLOEXEC.
2101 subprocess.Popen([
2102 sys.executable, "-c",
2103 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
2104 finally:
2105 # Restore original stdin and stdout
2106 os.dup2(new_stdin, 0)
2107 os.dup2(new_stdout, 1)
2108 os.close(new_stdin)
2109 os.close(new_stdout)
2110
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002111 def test_remapping_std_fds(self):
2112 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002113 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002114 try:
2115 temp_fds = [fd for fd, fname in temps]
2116
2117 # unlink the files -- we won't need to reopen them
2118 for fd, fname in temps:
2119 os.unlink(fname)
2120
2121 # write some data to what will become stdin, and rewind
2122 os.write(temp_fds[1], b"STDIN")
2123 os.lseek(temp_fds[1], 0, 0)
2124
2125 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02002126 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002127 try:
2128 # duplicate the file objects over the standard fd's
2129 for fd, temp_fd in enumerate(temp_fds):
2130 os.dup2(temp_fd, fd)
2131
2132 # now use those files in the "wrong" order, so that subprocess
2133 # has to rearrange them in the child
2134 p = subprocess.Popen([sys.executable, "-c",
2135 'import sys; got = sys.stdin.read();'
2136 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2137 stdin=temp_fds[1],
2138 stdout=temp_fds[2],
2139 stderr=temp_fds[0])
2140 p.wait()
2141 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002142 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002143
2144 for fd in temp_fds:
2145 os.lseek(fd, 0, 0)
2146
2147 out = os.read(temp_fds[2], 1024)
2148 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
2149 self.assertEqual(out, b"got STDIN")
2150 self.assertEqual(err, b"err")
2151
2152 finally:
2153 for fd in temp_fds:
2154 os.close(fd)
2155
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002156 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
2157 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002158 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002159 temp_fds = [fd for fd, fname in temps]
2160 try:
2161 # unlink the files -- we won't need to reopen them
2162 for fd, fname in temps:
2163 os.unlink(fname)
2164
2165 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02002166 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002167 try:
2168 # duplicate the temp files over the standard fd's 0, 1, 2
2169 for fd, temp_fd in enumerate(temp_fds):
2170 os.dup2(temp_fd, fd)
2171
2172 # write some data to what will become stdin, and rewind
2173 os.write(stdin_no, b"STDIN")
2174 os.lseek(stdin_no, 0, 0)
2175
2176 # now use those files in the given order, so that subprocess
2177 # has to rearrange them in the child
2178 p = subprocess.Popen([sys.executable, "-c",
2179 'import sys; got = sys.stdin.read();'
2180 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2181 stdin=stdin_no,
2182 stdout=stdout_no,
2183 stderr=stderr_no)
2184 p.wait()
2185
2186 for fd in temp_fds:
2187 os.lseek(fd, 0, 0)
2188
2189 out = os.read(stdout_no, 1024)
2190 err = support.strip_python_stderr(os.read(stderr_no, 1024))
2191 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002192 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002193
2194 self.assertEqual(out, b"got STDIN")
2195 self.assertEqual(err, b"err")
2196
2197 finally:
2198 for fd in temp_fds:
2199 os.close(fd)
2200
2201 # When duping fds, if there arises a situation where one of the fds is
2202 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
2203 # This tests all combinations of this.
2204 def test_swap_fds(self):
2205 self.check_swap_fds(0, 1, 2)
2206 self.check_swap_fds(0, 2, 1)
2207 self.check_swap_fds(1, 0, 2)
2208 self.check_swap_fds(1, 2, 0)
2209 self.check_swap_fds(2, 0, 1)
2210 self.check_swap_fds(2, 1, 0)
2211
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +03002212 def _check_swap_std_fds_with_one_closed(self, from_fds, to_fds):
2213 saved_fds = self._save_fds(range(3))
2214 try:
2215 for from_fd in from_fds:
2216 with tempfile.TemporaryFile() as f:
2217 os.dup2(f.fileno(), from_fd)
2218
2219 fd_to_close = (set(range(3)) - set(from_fds)).pop()
2220 os.close(fd_to_close)
2221
2222 arg_names = ['stdin', 'stdout', 'stderr']
2223 kwargs = {}
2224 for from_fd, to_fd in zip(from_fds, to_fds):
2225 kwargs[arg_names[to_fd]] = from_fd
2226
2227 code = textwrap.dedent(r'''
2228 import os, sys
2229 skipped_fd = int(sys.argv[1])
2230 for fd in range(3):
2231 if fd != skipped_fd:
2232 os.write(fd, str(fd).encode('ascii'))
2233 ''')
2234
2235 skipped_fd = (set(range(3)) - set(to_fds)).pop()
2236
2237 rc = subprocess.call([sys.executable, '-c', code, str(skipped_fd)],
2238 **kwargs)
2239 self.assertEqual(rc, 0)
2240
2241 for from_fd, to_fd in zip(from_fds, to_fds):
2242 os.lseek(from_fd, 0, os.SEEK_SET)
2243 read_bytes = os.read(from_fd, 1024)
2244 read_fds = list(map(int, read_bytes.decode('ascii')))
2245 msg = textwrap.dedent(f"""
2246 When testing {from_fds} to {to_fds} redirection,
2247 parent descriptor {from_fd} got redirected
2248 to descriptor(s) {read_fds} instead of descriptor {to_fd}.
2249 """)
2250 self.assertEqual([to_fd], read_fds, msg)
2251 finally:
2252 self._restore_fds(saved_fds)
2253
2254 # Check that subprocess can remap std fds correctly even
2255 # if one of them is closed (#32844).
2256 def test_swap_std_fds_with_one_closed(self):
2257 for from_fds in itertools.combinations(range(3), 2):
2258 for to_fds in itertools.permutations(range(3), 2):
2259 self._check_swap_std_fds_with_one_closed(from_fds, to_fds)
2260
Victor Stinner13bb71c2010-04-23 21:41:56 +00002261 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00002262 def prepare():
2263 raise ValueError("surrogate:\uDCff")
2264
2265 try:
2266 subprocess.call(
2267 [sys.executable, "-c", "pass"],
2268 preexec_fn=prepare)
2269 except ValueError as err:
2270 # Pure Python implementations keeps the message
2271 self.assertIsNone(subprocess._posixsubprocess)
2272 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002273 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00002274 # _posixsubprocess uses a default message
2275 self.assertIsNotNone(subprocess._posixsubprocess)
2276 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
2277 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002278 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00002279
Victor Stinner13bb71c2010-04-23 21:41:56 +00002280 def test_undecodable_env(self):
2281 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01002282 encoded_value = value.encode("ascii", "surrogateescape")
2283
Victor Stinner13bb71c2010-04-23 21:41:56 +00002284 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002285 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002286 env = os.environ.copy()
2287 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01002288 # Use C locale to get ASCII for the locale encoding to force
Michael Felt89d79b12018-08-26 19:29:36 +02002289 # surrogate-escaping of \xFF in the child process
Victor Stinnerebc78d22010-10-14 10:38:17 +00002290 env['LC_ALL'] = 'C'
Michael Felt89d79b12018-08-26 19:29:36 +02002291 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002292 stdout = subprocess.check_output(
2293 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002294 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002295 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002296 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002297
2298 # test bytes
2299 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002300 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002301 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01002302 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002303 stdout = subprocess.check_output(
2304 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002305 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002306 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002307 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002308
Victor Stinnerb745a742010-05-18 17:17:23 +00002309 def test_bytes_program(self):
2310 abs_program = os.fsencode(sys.executable)
2311 path, program = os.path.split(sys.executable)
2312 program = os.fsencode(program)
2313
2314 # absolute bytes path
2315 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00002316 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002317
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002318 # absolute bytes path as a string
2319 cmd = b"'" + abs_program + b"' -c pass"
2320 exitcode = subprocess.call(cmd, shell=True)
2321 self.assertEqual(exitcode, 0)
2322
Victor Stinnerb745a742010-05-18 17:17:23 +00002323 # bytes program, unicode PATH
2324 env = os.environ.copy()
2325 env["PATH"] = path
2326 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002327 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002328
2329 # bytes program, bytes PATH
2330 envb = os.environb.copy()
2331 envb[b"PATH"] = os.fsencode(path)
2332 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002333 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002334
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002335 def test_pipe_cloexec(self):
2336 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2337 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2338
2339 p1 = subprocess.Popen([sys.executable, sleeper],
2340 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2341 stderr=subprocess.PIPE, close_fds=False)
2342
2343 self.addCleanup(p1.communicate, b'')
2344
2345 p2 = subprocess.Popen([sys.executable, fd_status],
2346 stdout=subprocess.PIPE, close_fds=False)
2347
2348 output, error = p2.communicate()
2349 result_fds = set(map(int, output.split(b',')))
2350 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2351 p1.stderr.fileno()])
2352
2353 self.assertFalse(result_fds & unwanted_fds,
2354 "Expected no fds from %r to be open in child, "
2355 "found %r" %
2356 (unwanted_fds, result_fds & unwanted_fds))
2357
2358 def test_pipe_cloexec_real_tools(self):
2359 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2360 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2361
2362 subdata = b'zxcvbn'
2363 data = subdata * 4 + b'\n'
2364
2365 p1 = subprocess.Popen([sys.executable, qcat],
2366 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2367 close_fds=False)
2368
2369 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2370 stdin=p1.stdout, stdout=subprocess.PIPE,
2371 close_fds=False)
2372
2373 self.addCleanup(p1.wait)
2374 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002375 def kill_p1():
2376 try:
2377 p1.terminate()
2378 except ProcessLookupError:
2379 pass
2380 def kill_p2():
2381 try:
2382 p2.terminate()
2383 except ProcessLookupError:
2384 pass
2385 self.addCleanup(kill_p1)
2386 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002387
2388 p1.stdin.write(data)
2389 p1.stdin.close()
2390
2391 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2392
2393 self.assertTrue(readfiles, "The child hung")
2394 self.assertEqual(p2.stdout.read(), data)
2395
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002396 p1.stdout.close()
2397 p2.stdout.close()
2398
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002399 def test_close_fds(self):
2400 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2401
2402 fds = os.pipe()
2403 self.addCleanup(os.close, fds[0])
2404 self.addCleanup(os.close, fds[1])
2405
2406 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002407 # add a bunch more fds
2408 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002409 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002410 self.addCleanup(os.close, fd)
2411 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002412
Victor Stinnerdaf45552013-08-28 00:53:59 +02002413 for fd in open_fds:
2414 os.set_inheritable(fd, True)
2415
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002416 p = subprocess.Popen([sys.executable, fd_status],
2417 stdout=subprocess.PIPE, close_fds=False)
2418 output, ignored = p.communicate()
2419 remaining_fds = set(map(int, output.split(b',')))
2420
2421 self.assertEqual(remaining_fds & open_fds, open_fds,
2422 "Some fds were closed")
2423
2424 p = subprocess.Popen([sys.executable, fd_status],
2425 stdout=subprocess.PIPE, close_fds=True)
2426 output, ignored = p.communicate()
2427 remaining_fds = set(map(int, output.split(b',')))
2428
2429 self.assertFalse(remaining_fds & open_fds,
2430 "Some fds were left open")
2431 self.assertIn(1, remaining_fds, "Subprocess failed")
2432
Gregory P. Smith8facece2012-01-21 14:01:08 -08002433 # Keep some of the fd's we opened open in the subprocess.
2434 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2435 fds_to_keep = set(open_fds.pop() for _ in range(8))
2436 p = subprocess.Popen([sys.executable, fd_status],
2437 stdout=subprocess.PIPE, close_fds=True,
izbyshev2d8f0632017-12-19 03:26:49 +07002438 pass_fds=fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002439 output, ignored = p.communicate()
2440 remaining_fds = set(map(int, output.split(b',')))
2441
izbyshev2d8f0632017-12-19 03:26:49 +07002442 self.assertFalse((remaining_fds - fds_to_keep) & open_fds,
Gregory P. Smith8facece2012-01-21 14:01:08 -08002443 "Some fds not in pass_fds were left open")
2444 self.assertIn(1, remaining_fds, "Subprocess failed")
2445
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002446
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002447 @unittest.skipIf(sys.platform.startswith("freebsd") and
2448 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2449 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002450 def test_close_fds_when_max_fd_is_lowered(self):
2451 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2452 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2453
Gregory P. Smith634aa682014-06-15 17:51:04 -07002454 # This launches the meat of the test in a child process to
2455 # avoid messing with the larger unittest processes maximum
2456 # number of file descriptors.
2457 # This process launches:
2458 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2459 # a bunch of high open fds above the new lower rlimit.
2460 # Those are reported via stdout before launching a new
2461 # process with close_fds=False to run the actual test:
2462 # +--> The TEST: This one launches a fd_status.py
2463 # subprocess with close_fds=True so we can find out if
2464 # any of the fds above the lowered rlimit are still open.
2465 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2466 '''
2467 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002468 open_fds = set()
2469 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002470 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002471 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002472 open_fds.add(fd)
2473
2474 # Leave a two pairs of low ones available for use by the
2475 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002476 # We also leave 10 more open as some Python buildbots run into
2477 # "too many open files" errors during the test if we do not.
2478 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002479 os.close(fd)
2480 open_fds.remove(fd)
2481
2482 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002483 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002484 os.set_inheritable(fd, True)
2485
2486 max_fd_open = max(open_fds)
2487
Gregory P. Smith634aa682014-06-15 17:51:04 -07002488 # Communicate the open_fds to the parent unittest.TestCase process.
2489 print(','.join(map(str, sorted(open_fds))))
2490 sys.stdout.flush()
2491
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002492 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2493 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002494 # 29 is lower than the highest fds we are leaving open.
2495 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002496 # Launch a new Python interpreter with our low fd rlim_cur that
2497 # inherits open fds above that limit. It then uses subprocess
2498 # with close_fds=True to get a report of open fds in the child.
2499 # An explicit list of fds to check is passed to fd_status.py as
2500 # letting fd_status rely on its default logic would miss the
2501 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002502 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002503 [sys.executable, '-c',
2504 textwrap.dedent("""
2505 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002506 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002507 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002508 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002509 """.format(max_fd=max_fd_open+1))],
2510 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002511 finally:
2512 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002513 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002514
2515 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002516 output_lines = output.splitlines()
2517 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002518 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002519 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2520 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002521
Gregory P. Smith634aa682014-06-15 17:51:04 -07002522 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002523 msg="Some fds were left open.")
2524
2525
Victor Stinner88701e22011-06-01 13:13:04 +02002526 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2527 # descriptor of a pipe closed in the parent process is valid in the
2528 # child process according to fstat(), but the mode of the file
2529 # descriptor is invalid, and read or write raise an error.
2530 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002531 def test_pass_fds(self):
2532 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2533
2534 open_fds = set()
2535
2536 for x in range(5):
2537 fds = os.pipe()
2538 self.addCleanup(os.close, fds[0])
2539 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002540 os.set_inheritable(fds[0], True)
2541 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002542 open_fds.update(fds)
2543
2544 for fd in open_fds:
2545 p = subprocess.Popen([sys.executable, fd_status],
2546 stdout=subprocess.PIPE, close_fds=True,
2547 pass_fds=(fd, ))
2548 output, ignored = p.communicate()
2549
2550 remaining_fds = set(map(int, output.split(b',')))
2551 to_be_closed = open_fds - {fd}
2552
2553 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2554 self.assertFalse(remaining_fds & to_be_closed,
2555 "fd to be closed passed")
2556
2557 # pass_fds overrides close_fds with a warning.
2558 with self.assertWarns(RuntimeWarning) as context:
2559 self.assertFalse(subprocess.call(
2560 [sys.executable, "-c", "import sys; sys.exit(0)"],
2561 close_fds=False, pass_fds=(fd, )))
2562 self.assertIn('overriding close_fds', str(context.warning))
2563
Victor Stinnerdaf45552013-08-28 00:53:59 +02002564 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002565 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002566
2567 inheritable, non_inheritable = os.pipe()
2568 self.addCleanup(os.close, inheritable)
2569 self.addCleanup(os.close, non_inheritable)
2570 os.set_inheritable(inheritable, True)
2571 os.set_inheritable(non_inheritable, False)
2572 pass_fds = (inheritable, non_inheritable)
2573 args = [sys.executable, script]
2574 args += list(map(str, pass_fds))
2575
2576 p = subprocess.Popen(args,
2577 stdout=subprocess.PIPE, close_fds=True,
2578 pass_fds=pass_fds)
2579 output, ignored = p.communicate()
2580 fds = set(map(int, output.split(b',')))
2581
2582 # the inheritable file descriptor must be inherited, so its inheritable
2583 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002584 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002585
2586 # inheritable flag must not be changed in the parent process
2587 self.assertEqual(os.get_inheritable(inheritable), True)
2588 self.assertEqual(os.get_inheritable(non_inheritable), False)
2589
Gregory P. Smithce344102018-09-10 17:46:22 -07002590
2591 # bpo-32270: Ensure that descriptors specified in pass_fds
2592 # are inherited even if they are used in redirections.
2593 # Contributed by @izbyshev.
2594 def test_pass_fds_redirected(self):
2595 """Regression test for https://bugs.python.org/issue32270."""
2596 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2597 pass_fds = []
2598 for _ in range(2):
2599 fd = os.open(os.devnull, os.O_RDWR)
2600 self.addCleanup(os.close, fd)
2601 pass_fds.append(fd)
2602
2603 stdout_r, stdout_w = os.pipe()
2604 self.addCleanup(os.close, stdout_r)
2605 self.addCleanup(os.close, stdout_w)
2606 pass_fds.insert(1, stdout_w)
2607
2608 with subprocess.Popen([sys.executable, fd_status],
2609 stdin=pass_fds[0],
2610 stdout=pass_fds[1],
2611 stderr=pass_fds[2],
2612 close_fds=True,
2613 pass_fds=pass_fds):
2614 output = os.read(stdout_r, 1024)
2615 fds = {int(num) for num in output.split(b',')}
2616
2617 self.assertEqual(fds, {0, 1, 2} | frozenset(pass_fds), f"output={output!a}")
2618
2619
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002620 def test_stdout_stdin_are_single_inout_fd(self):
2621 with io.open(os.devnull, "r+") as inout:
2622 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2623 stdout=inout, stdin=inout)
2624 p.wait()
2625
2626 def test_stdout_stderr_are_single_inout_fd(self):
2627 with io.open(os.devnull, "r+") as inout:
2628 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2629 stdout=inout, stderr=inout)
2630 p.wait()
2631
2632 def test_stderr_stdin_are_single_inout_fd(self):
2633 with io.open(os.devnull, "r+") as inout:
2634 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2635 stderr=inout, stdin=inout)
2636 p.wait()
2637
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002638 def test_wait_when_sigchild_ignored(self):
2639 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2640 sigchild_ignore = support.findfile("sigchild_ignore.py",
2641 subdir="subprocessdata")
2642 p = subprocess.Popen([sys.executable, sigchild_ignore],
2643 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2644 stdout, stderr = p.communicate()
2645 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002646 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002647 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002648
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002649 def test_select_unbuffered(self):
2650 # Issue #11459: bufsize=0 should really set the pipes as
2651 # unbuffered (and therefore let select() work properly).
2652 select = support.import_module("select")
2653 p = subprocess.Popen([sys.executable, "-c",
2654 'import sys;'
2655 'sys.stdout.write("apple")'],
2656 stdout=subprocess.PIPE,
2657 bufsize=0)
2658 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002659 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002660 try:
2661 self.assertEqual(f.read(4), b"appl")
2662 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2663 finally:
2664 p.wait()
2665
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002666 def test_zombie_fast_process_del(self):
2667 # Issue #12650: on Unix, if Popen.__del__() was called before the
2668 # process exited, it wouldn't be added to subprocess._active, and would
2669 # remain a zombie.
2670 # spawn a Popen, and delete its reference before it exits
2671 p = subprocess.Popen([sys.executable, "-c",
2672 'import sys, time;'
2673 'time.sleep(0.2)'],
2674 stdout=subprocess.PIPE,
2675 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002676 self.addCleanup(p.stdout.close)
2677 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002678 ident = id(p)
2679 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002680 with support.check_warnings(('', ResourceWarning)):
2681 p = None
2682
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002683 # check that p is in the active processes list
2684 self.assertIn(ident, [id(o) for o in subprocess._active])
2685
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002686 def test_leak_fast_process_del_killed(self):
2687 # Issue #12650: on Unix, if Popen.__del__() was called before the
2688 # process exited, and the process got killed by a signal, it would never
2689 # be removed from subprocess._active, which triggered a FD and memory
2690 # leak.
2691 # spawn a Popen, delete its reference and kill it
2692 p = subprocess.Popen([sys.executable, "-c",
2693 'import time;'
2694 'time.sleep(3)'],
2695 stdout=subprocess.PIPE,
2696 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002697 self.addCleanup(p.stdout.close)
2698 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002699 ident = id(p)
2700 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002701 with support.check_warnings(('', ResourceWarning)):
2702 p = None
2703
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002704 os.kill(pid, signal.SIGKILL)
2705 # check that p is in the active processes list
2706 self.assertIn(ident, [id(o) for o in subprocess._active])
2707
2708 # let some time for the process to exit, and create a new Popen: this
2709 # should trigger the wait() of p
2710 time.sleep(0.2)
Victor Stinnerb31206a2018-01-25 19:06:05 +01002711 with self.assertRaises(OSError):
Victor Stinner9a83f652017-08-21 23:51:31 +02002712 with subprocess.Popen(NONEXISTING_CMD,
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002713 stdout=subprocess.PIPE,
2714 stderr=subprocess.PIPE) as proc:
2715 pass
2716 # p should have been wait()ed on, and removed from the _active list
2717 self.assertRaises(OSError, os.waitpid, pid, 0)
2718 self.assertNotIn(ident, [id(o) for o in subprocess._active])
2719
Charles-François Natali249cdc32013-08-25 18:24:45 +02002720 def test_close_fds_after_preexec(self):
2721 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2722
2723 # this FD is used as dup2() target by preexec_fn, and should be closed
2724 # in the child process
2725 fd = os.dup(1)
2726 self.addCleanup(os.close, fd)
2727
2728 p = subprocess.Popen([sys.executable, fd_status],
2729 stdout=subprocess.PIPE, close_fds=True,
2730 preexec_fn=lambda: os.dup2(1, fd))
2731 output, ignored = p.communicate()
2732
2733 remaining_fds = set(map(int, output.split(b',')))
2734
2735 self.assertNotIn(fd, remaining_fds)
2736
Victor Stinner8f437aa2014-10-05 17:25:19 +02002737 @support.cpython_only
2738 def test_fork_exec(self):
2739 # Issue #22290: fork_exec() must not crash on memory allocation failure
2740 # or other errors
2741 import _posixsubprocess
2742 gc_enabled = gc.isenabled()
2743 try:
2744 # Use a preexec function and enable the garbage collector
2745 # to force fork_exec() to re-enable the garbage collector
2746 # on error.
2747 func = lambda: None
2748 gc.enable()
2749
Victor Stinner8f437aa2014-10-05 17:25:19 +02002750 for args, exe_list, cwd, env_list in (
2751 (123, [b"exe"], None, [b"env"]),
2752 ([b"arg"], 123, None, [b"env"]),
2753 ([b"arg"], [b"exe"], 123, [b"env"]),
2754 ([b"arg"], [b"exe"], None, 123),
2755 ):
2756 with self.assertRaises(TypeError):
2757 _posixsubprocess.fork_exec(
2758 args, exe_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002759 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02002760 -1, -1, -1, -1,
2761 1, 2, 3, 4,
2762 True, True, func)
2763 finally:
2764 if not gc_enabled:
2765 gc.disable()
2766
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002767 @support.cpython_only
2768 def test_fork_exec_sorted_fd_sanity_check(self):
2769 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
2770 import _posixsubprocess
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002771 class BadInt:
2772 first = True
2773 def __init__(self, value):
2774 self.value = value
2775 def __int__(self):
2776 if self.first:
2777 self.first = False
2778 return self.value
2779 raise ValueError
2780
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002781 gc_enabled = gc.isenabled()
2782 try:
2783 gc.enable()
2784
2785 for fds_to_keep in (
2786 (-1, 2, 3, 4, 5), # Negative number.
2787 ('str', 4), # Not an int.
2788 (18, 23, 42, 2**63), # Out of range.
2789 (5, 4), # Not sorted.
2790 (6, 7, 7, 8), # Duplicate.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002791 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002792 ):
2793 with self.assertRaises(
2794 ValueError,
2795 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
2796 _posixsubprocess.fork_exec(
2797 [b"false"], [b"false"],
2798 True, fds_to_keep, None, [b"env"],
2799 -1, -1, -1, -1,
2800 1, 2, 3, 4,
2801 True, True, None)
2802 self.assertIn('fds_to_keep', str(c.exception))
2803 finally:
2804 if not gc_enabled:
2805 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02002806
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00002807 def test_communicate_BrokenPipeError_stdin_close(self):
2808 # By not setting stdout or stderr or a timeout we force the fast path
2809 # that just calls _stdin_write() internally due to our mock.
2810 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2811 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2812 mock_proc_stdin.close.side_effect = BrokenPipeError
2813 proc.communicate() # Should swallow BrokenPipeError from close.
2814 mock_proc_stdin.close.assert_called_with()
2815
2816 def test_communicate_BrokenPipeError_stdin_write(self):
2817 # By not setting stdout or stderr or a timeout we force the fast path
2818 # that just calls _stdin_write() internally due to our mock.
2819 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2820 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2821 mock_proc_stdin.write.side_effect = BrokenPipeError
2822 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
2823 mock_proc_stdin.write.assert_called_once_with(b'stuff')
2824 mock_proc_stdin.close.assert_called_once_with()
2825
2826 def test_communicate_BrokenPipeError_stdin_flush(self):
2827 # Setting stdin and stdout forces the ._communicate() code path.
2828 # python -h exits faster than python -c pass (but spams stdout).
2829 proc = subprocess.Popen([sys.executable, '-h'],
2830 stdin=subprocess.PIPE,
2831 stdout=subprocess.PIPE)
2832 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
2833 open(os.devnull, 'wb') as dev_null:
2834 mock_proc_stdin.flush.side_effect = BrokenPipeError
2835 # because _communicate registers a selector using proc.stdin...
2836 mock_proc_stdin.fileno.return_value = dev_null.fileno()
2837 # _communicate() should swallow BrokenPipeError from flush.
2838 proc.communicate(b'stuff')
2839 mock_proc_stdin.flush.assert_called_once_with()
2840
2841 def test_communicate_BrokenPipeError_stdin_close_with_timeout(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 mock_proc_stdin.close.side_effect = BrokenPipeError
2849 # _communicate() should swallow BrokenPipeError from close.
2850 proc.communicate(timeout=999)
2851 mock_proc_stdin.close.assert_called_once_with()
2852
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002853 @unittest.skipUnless(_testcapi is not None
2854 and hasattr(_testcapi, 'W_STOPCODE'),
2855 'need _testcapi.W_STOPCODE')
2856 def test_stopped(self):
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002857 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002858 args = [sys.executable, '-c', 'pass']
2859 proc = subprocess.Popen(args)
Victor Stinnercdee3f12017-06-26 17:23:03 +02002860
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002861 # Wait until the real process completes to avoid zombie process
2862 pid = proc.pid
2863 pid, status = os.waitpid(pid, 0)
2864 self.assertEqual(status, 0)
Victor Stinnercdee3f12017-06-26 17:23:03 +02002865
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002866 status = _testcapi.W_STOPCODE(3)
2867 with mock.patch('subprocess.os.waitpid', return_value=(pid, status)):
2868 returncode = proc.wait()
Victor Stinnercdee3f12017-06-26 17:23:03 +02002869
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002870 self.assertEqual(returncode, -3)
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002871
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002872
Victor Stinner937ee9e2018-06-26 02:11:06 +02002873@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00002874class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002875
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002876 def test_startupinfo(self):
2877 # startupinfo argument
2878 # We uses hardcoded constants, because we do not want to
2879 # depend on win32all.
2880 STARTF_USESHOWWINDOW = 1
2881 SW_MAXIMIZE = 3
2882 startupinfo = subprocess.STARTUPINFO()
2883 startupinfo.dwFlags = STARTF_USESHOWWINDOW
2884 startupinfo.wShowWindow = SW_MAXIMIZE
2885 # Since Python is a console process, it won't be affected
2886 # by wShowWindow, but the argument should be silently
2887 # ignored
2888 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002889 startupinfo=startupinfo)
2890
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05302891 def test_startupinfo_keywords(self):
2892 # startupinfo argument
2893 # We use hardcoded constants, because we do not want to
2894 # depend on win32all.
2895 STARTF_USERSHOWWINDOW = 1
2896 SW_MAXIMIZE = 3
2897 startupinfo = subprocess.STARTUPINFO(
2898 dwFlags=STARTF_USERSHOWWINDOW,
2899 wShowWindow=SW_MAXIMIZE
2900 )
2901 # Since Python is a console process, it won't be affected
2902 # by wShowWindow, but the argument should be silently
2903 # ignored
2904 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
2905 startupinfo=startupinfo)
2906
Victor Stinner483422f2018-07-05 22:54:17 +02002907 def test_startupinfo_copy(self):
2908 # bpo-34044: Popen must not modify input STARTUPINFO structure
2909 startupinfo = subprocess.STARTUPINFO()
2910 startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
2911 startupinfo.wShowWindow = subprocess.SW_HIDE
2912
2913 # Call Popen() twice with the same startupinfo object to make sure
2914 # that it's not modified
2915 for _ in range(2):
2916 cmd = [sys.executable, "-c", "pass"]
2917 with open(os.devnull, 'w') as null:
2918 proc = subprocess.Popen(cmd,
2919 stdout=null,
2920 stderr=subprocess.STDOUT,
2921 startupinfo=startupinfo)
2922 with proc:
2923 proc.communicate()
2924 self.assertEqual(proc.returncode, 0)
2925
2926 self.assertEqual(startupinfo.dwFlags,
2927 subprocess.STARTF_USESHOWWINDOW)
2928 self.assertIsNone(startupinfo.hStdInput)
2929 self.assertIsNone(startupinfo.hStdOutput)
2930 self.assertIsNone(startupinfo.hStdError)
2931 self.assertEqual(startupinfo.wShowWindow, subprocess.SW_HIDE)
2932 self.assertEqual(startupinfo.lpAttributeList, {"handle_list": []})
2933
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002934 def test_creationflags(self):
2935 # creationflags argument
2936 CREATE_NEW_CONSOLE = 16
2937 sys.stderr.write(" a DOS box should flash briefly ...\n")
2938 subprocess.call(sys.executable +
2939 ' -c "import time; time.sleep(0.25)"',
2940 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002941
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002942 def test_invalid_args(self):
2943 # invalid arguments should raise ValueError
2944 self.assertRaises(ValueError, subprocess.call,
2945 [sys.executable, "-c",
2946 "import sys; sys.exit(47)"],
2947 preexec_fn=lambda: 1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002948
Oren Milman0b3a87e2017-09-14 22:30:28 +03002949 @support.cpython_only
2950 def test_issue31471(self):
2951 # There shouldn't be an assertion failure in Popen() in case the env
2952 # argument has a bad keys() method.
2953 class BadEnv(dict):
2954 keys = None
2955 with self.assertRaises(TypeError):
2956 subprocess.Popen([sys.executable, "-c", "pass"], env=BadEnv())
2957
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002958 def test_close_fds(self):
2959 # close file descriptors
2960 rc = subprocess.call([sys.executable, "-c",
2961 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002962 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002963 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002964
Segev Finerb2a60832017-12-18 11:28:19 +02002965 def test_close_fds_with_stdio(self):
2966 import msvcrt
2967
2968 fds = os.pipe()
2969 self.addCleanup(os.close, fds[0])
2970 self.addCleanup(os.close, fds[1])
2971
2972 handles = []
2973 for fd in fds:
2974 os.set_inheritable(fd, True)
2975 handles.append(msvcrt.get_osfhandle(fd))
2976
2977 p = subprocess.Popen([sys.executable, "-c",
2978 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
2979 stdout=subprocess.PIPE, close_fds=False)
2980 stdout, stderr = p.communicate()
2981 self.assertEqual(p.returncode, 0)
2982 int(stdout.strip()) # Check that stdout is an integer
2983
2984 p = subprocess.Popen([sys.executable, "-c",
2985 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
2986 stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
2987 stdout, stderr = p.communicate()
2988 self.assertEqual(p.returncode, 1)
2989 self.assertIn(b"OSError", stderr)
2990
2991 # The same as the previous call, but with an empty handle_list
2992 handle_list = []
2993 startupinfo = subprocess.STARTUPINFO()
2994 startupinfo.lpAttributeList = {"handle_list": handle_list}
2995 p = subprocess.Popen([sys.executable, "-c",
2996 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
2997 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
2998 startupinfo=startupinfo, close_fds=True)
2999 stdout, stderr = p.communicate()
3000 self.assertEqual(p.returncode, 1)
3001 self.assertIn(b"OSError", stderr)
3002
3003 # Check for a warning due to using handle_list and close_fds=False
3004 with support.check_warnings((".*overriding close_fds", RuntimeWarning)):
3005 startupinfo = subprocess.STARTUPINFO()
3006 startupinfo.lpAttributeList = {"handle_list": handles[:]}
3007 p = subprocess.Popen([sys.executable, "-c",
3008 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3009 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3010 startupinfo=startupinfo, close_fds=False)
3011 stdout, stderr = p.communicate()
3012 self.assertEqual(p.returncode, 0)
3013
3014 def test_empty_attribute_list(self):
3015 startupinfo = subprocess.STARTUPINFO()
3016 startupinfo.lpAttributeList = {}
3017 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
3018 startupinfo=startupinfo)
3019
3020 def test_empty_handle_list(self):
3021 startupinfo = subprocess.STARTUPINFO()
3022 startupinfo.lpAttributeList = {"handle_list": []}
3023 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
3024 startupinfo=startupinfo)
3025
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003026 def test_shell_sequence(self):
3027 # Run command through the shell (sequence)
3028 newenv = os.environ.copy()
3029 newenv["FRUIT"] = "physalis"
3030 p = subprocess.Popen(["set"], shell=1,
3031 stdout=subprocess.PIPE,
3032 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003033 with p:
3034 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00003035
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003036 def test_shell_string(self):
3037 # Run command through the shell (string)
3038 newenv = os.environ.copy()
3039 newenv["FRUIT"] = "physalis"
3040 p = subprocess.Popen("set", shell=1,
3041 stdout=subprocess.PIPE,
3042 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003043 with p:
3044 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003045
Steve Dower050acae2016-09-06 20:16:17 -07003046 def test_shell_encodings(self):
3047 # Run command through the shell (string)
3048 for enc in ['ansi', 'oem']:
3049 newenv = os.environ.copy()
3050 newenv["FRUIT"] = "physalis"
3051 p = subprocess.Popen("set", shell=1,
3052 stdout=subprocess.PIPE,
3053 env=newenv,
3054 encoding=enc)
3055 with p:
3056 self.assertIn("physalis", p.stdout.read(), enc)
3057
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003058 def test_call_string(self):
3059 # call() function with string argument on Windows
3060 rc = subprocess.call(sys.executable +
3061 ' -c "import sys; sys.exit(47)"')
3062 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003063
Florent Xicluna4886d242010-03-08 13:27:26 +00003064 def _kill_process(self, method, *args):
3065 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00003066 p = subprocess.Popen([sys.executable, "-c", """if 1:
3067 import sys, time
3068 sys.stdout.write('x\\n')
3069 sys.stdout.flush()
3070 time.sleep(30)
3071 """],
3072 stdin=subprocess.PIPE,
3073 stdout=subprocess.PIPE,
3074 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003075 with p:
3076 # Wait for the interpreter to be completely initialized before
3077 # sending any signal.
3078 p.stdout.read(1)
3079 getattr(p, method)(*args)
3080 _, stderr = p.communicate()
3081 self.assertStderrEqual(stderr, b'')
3082 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00003083 self.assertNotEqual(returncode, 0)
3084
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003085 def _kill_dead_process(self, method, *args):
3086 p = subprocess.Popen([sys.executable, "-c", """if 1:
3087 import sys, time
3088 sys.stdout.write('x\\n')
3089 sys.stdout.flush()
3090 sys.exit(42)
3091 """],
3092 stdin=subprocess.PIPE,
3093 stdout=subprocess.PIPE,
3094 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003095 with p:
3096 # Wait for the interpreter to be completely initialized before
3097 # sending any signal.
3098 p.stdout.read(1)
3099 # The process should end after this
3100 time.sleep(1)
3101 # This shouldn't raise even though the child is now dead
3102 getattr(p, method)(*args)
3103 _, stderr = p.communicate()
3104 self.assertStderrEqual(stderr, b'')
3105 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003106 self.assertEqual(rc, 42)
3107
Florent Xicluna4886d242010-03-08 13:27:26 +00003108 def test_send_signal(self):
3109 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00003110
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003111 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003112 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00003113
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003114 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003115 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00003116
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003117 def test_send_signal_dead(self):
3118 self._kill_dead_process('send_signal', signal.SIGTERM)
3119
3120 def test_kill_dead(self):
3121 self._kill_dead_process('kill')
3122
3123 def test_terminate_dead(self):
3124 self._kill_dead_process('terminate')
3125
Martin Panter23172bd2016-04-16 11:28:10 +00003126class MiscTests(unittest.TestCase):
Gregory P. Smithf4d644f2018-01-29 21:27:39 -08003127
3128 class RecordingPopen(subprocess.Popen):
3129 """A Popen that saves a reference to each instance for testing."""
3130 instances_created = []
3131
3132 def __init__(self, *args, **kwargs):
3133 super().__init__(*args, **kwargs)
3134 self.instances_created.append(self)
3135
3136 @mock.patch.object(subprocess.Popen, "_communicate")
3137 def _test_keyboardinterrupt_no_kill(self, popener, mock__communicate,
3138 **kwargs):
3139 """Fake a SIGINT happening during Popen._communicate() and ._wait().
3140
3141 This avoids the need to actually try and get test environments to send
3142 and receive signals reliably across platforms. The net effect of a ^C
3143 happening during a blocking subprocess execution which we want to clean
3144 up from is a KeyboardInterrupt coming out of communicate() or wait().
3145 """
3146
3147 mock__communicate.side_effect = KeyboardInterrupt
3148 try:
3149 with mock.patch.object(subprocess.Popen, "_wait") as mock__wait:
3150 # We patch out _wait() as no signal was involved so the
3151 # child process isn't actually going to exit rapidly.
3152 mock__wait.side_effect = KeyboardInterrupt
3153 with mock.patch.object(subprocess, "Popen",
3154 self.RecordingPopen):
3155 with self.assertRaises(KeyboardInterrupt):
3156 popener([sys.executable, "-c",
3157 "import time\ntime.sleep(9)\nimport sys\n"
3158 "sys.stderr.write('\\n!runaway child!\\n')"],
3159 stdout=subprocess.DEVNULL, **kwargs)
3160 for call in mock__wait.call_args_list[1:]:
3161 self.assertNotEqual(
3162 call, mock.call(timeout=None),
3163 "no open-ended wait() after the first allowed: "
3164 f"{mock__wait.call_args_list}")
3165 sigint_calls = []
3166 for call in mock__wait.call_args_list:
3167 if call == mock.call(timeout=0.25): # from Popen.__init__
3168 sigint_calls.append(call)
3169 self.assertLessEqual(mock__wait.call_count, 2,
3170 msg=mock__wait.call_args_list)
3171 self.assertEqual(len(sigint_calls), 1,
3172 msg=mock__wait.call_args_list)
3173 finally:
3174 # cleanup the forgotten (due to our mocks) child process
3175 process = self.RecordingPopen.instances_created.pop()
3176 process.kill()
3177 process.wait()
3178 self.assertEqual([], self.RecordingPopen.instances_created)
3179
3180 def test_call_keyboardinterrupt_no_kill(self):
3181 self._test_keyboardinterrupt_no_kill(subprocess.call, timeout=6.282)
3182
3183 def test_run_keyboardinterrupt_no_kill(self):
3184 self._test_keyboardinterrupt_no_kill(subprocess.run, timeout=6.282)
3185
3186 def test_context_manager_keyboardinterrupt_no_kill(self):
3187 def popen_via_context_manager(*args, **kwargs):
3188 with subprocess.Popen(*args, **kwargs) as unused_process:
3189 raise KeyboardInterrupt # Test how __exit__ handles ^C.
3190 self._test_keyboardinterrupt_no_kill(popen_via_context_manager)
3191
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003192 def test_getoutput(self):
3193 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
3194 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
3195 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00003196
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003197 # we use mkdtemp in the next line to create an empty directory
3198 # under our exclusive control; from that, we can invent a pathname
3199 # that we _know_ won't exist. This is guaranteed to fail.
3200 dir = None
3201 try:
3202 dir = tempfile.mkdtemp()
3203 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00003204 status, output = subprocess.getstatusoutput(
Victor Stinner937ee9e2018-06-26 02:11:06 +02003205 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003206 self.assertNotEqual(status, 0)
3207 finally:
3208 if dir is not None:
3209 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00003210
Gregory P. Smithace55862015-04-07 15:57:54 -07003211 def test__all__(self):
3212 """Ensure that __all__ is populated properly."""
Martin Panter528619b2016-04-16 23:42:37 +00003213 intentionally_excluded = {"list2cmdline", "Handle"}
Gregory P. Smithace55862015-04-07 15:57:54 -07003214 exported = set(subprocess.__all__)
3215 possible_exports = set()
3216 import types
3217 for name, value in subprocess.__dict__.items():
3218 if name.startswith('_'):
3219 continue
3220 if isinstance(value, (types.ModuleType,)):
3221 continue
3222 possible_exports.add(name)
3223 self.assertEqual(exported, possible_exports - intentionally_excluded)
3224
3225
Martin Panter23172bd2016-04-16 11:28:10 +00003226@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
3227 "Test needs selectors.PollSelector")
3228class ProcessTestCaseNoPoll(ProcessTestCase):
3229 def setUp(self):
3230 self.orig_selector = subprocess._PopenSelector
3231 subprocess._PopenSelector = selectors.SelectSelector
3232 ProcessTestCase.setUp(self)
3233
3234 def tearDown(self):
3235 subprocess._PopenSelector = self.orig_selector
3236 ProcessTestCase.tearDown(self)
3237
Gregory P. Smithd06fa472009-07-04 02:46:54 +00003238
Victor Stinner937ee9e2018-06-26 02:11:06 +02003239@unittest.skipUnless(mswindows, "Windows-specific tests")
Tim Golden126c2962010-08-11 14:20:40 +00003240class CommandsWithSpaces (BaseTestCase):
3241
3242 def setUp(self):
3243 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03003244 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00003245 self.fname = fname.lower ()
3246 os.write(f, b"import sys;"
3247 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
3248 )
3249 os.close(f)
3250
3251 def tearDown(self):
3252 os.remove(self.fname)
3253 super().tearDown()
3254
3255 def with_spaces(self, *args, **kwargs):
3256 kwargs['stdout'] = subprocess.PIPE
3257 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02003258 with p:
3259 self.assertEqual(
3260 p.stdout.read ().decode("mbcs"),
3261 "2 [%r, 'ab cd']" % self.fname
3262 )
Tim Golden126c2962010-08-11 14:20:40 +00003263
3264 def test_shell_string_with_spaces(self):
3265 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003266 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3267 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003268
3269 def test_shell_sequence_with_spaces(self):
3270 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003271 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003272
3273 def test_noshell_string_with_spaces(self):
3274 # call() function with string argument with spaces on Windows
3275 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3276 "ab cd"))
3277
3278 def test_noshell_sequence_with_spaces(self):
3279 # call() function with sequence argument with spaces on Windows
3280 self.with_spaces([sys.executable, self.fname, "ab cd"])
3281
Brian Curtin79cdb662010-12-03 02:46:02 +00003282
Georg Brandla86b2622012-02-20 21:34:57 +01003283class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00003284
3285 def test_pipe(self):
3286 with subprocess.Popen([sys.executable, "-c",
3287 "import sys;"
3288 "sys.stdout.write('stdout');"
3289 "sys.stderr.write('stderr');"],
3290 stdout=subprocess.PIPE,
3291 stderr=subprocess.PIPE) as proc:
3292 self.assertEqual(proc.stdout.read(), b"stdout")
3293 self.assertStderrEqual(proc.stderr.read(), b"stderr")
3294
3295 self.assertTrue(proc.stdout.closed)
3296 self.assertTrue(proc.stderr.closed)
3297
3298 def test_returncode(self):
3299 with subprocess.Popen([sys.executable, "-c",
3300 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07003301 pass
3302 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00003303 self.assertEqual(proc.returncode, 100)
3304
3305 def test_communicate_stdin(self):
3306 with subprocess.Popen([sys.executable, "-c",
3307 "import sys;"
3308 "sys.exit(sys.stdin.read() == 'context')"],
3309 stdin=subprocess.PIPE) as proc:
3310 proc.communicate(b"context")
3311 self.assertEqual(proc.returncode, 1)
3312
3313 def test_invalid_args(self):
Victor Stinnerb31206a2018-01-25 19:06:05 +01003314 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02003315 with subprocess.Popen(NONEXISTING_CMD,
Brian Curtin79cdb662010-12-03 02:46:02 +00003316 stdout=subprocess.PIPE,
3317 stderr=subprocess.PIPE) as proc:
3318 pass
3319
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003320 def test_broken_pipe_cleanup(self):
3321 """Broken pipe error should not prevent wait() (Issue 21619)"""
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003322 proc = subprocess.Popen([sys.executable, '-c', 'pass'],
Victor Stinner20f4bd42015-03-05 02:38:41 +01003323 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003324 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003325 proc = proc.__enter__()
3326 # Prepare to send enough data to overflow any OS pipe buffering and
3327 # guarantee a broken pipe error. Data is held in BufferedWriter
3328 # buffer until closed.
3329 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003330 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003331 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02003332 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003333 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003334 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003335
Brian Curtin79cdb662010-12-03 02:46:02 +00003336
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003337if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04003338 unittest.main()