blob: 97d21904b9cecf3aa9000b285243e570b2925458 [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(
Victor Stinner58840432019-06-14 19:31:43 +02001708 [sys.executable, "-c", "import os; print(os.getsid(0))"],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001709 start_new_session=True)
1710 except OSError as e:
1711 if e.errno != errno.EPERM:
1712 raise
1713 else:
Victor Stinner58840432019-06-14 19:31:43 +02001714 parent_sid = os.getsid(0)
1715 child_sid = int(output)
1716 self.assertNotEqual(parent_sid, child_sid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001717
1718 def test_run_abort(self):
1719 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001720 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001721 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001722 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001723 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001724 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001725
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001726 def test_CalledProcessError_str_signal(self):
1727 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
1728 error_string = str(err)
1729 # We're relying on the repr() of the signal.Signals intenum to provide
1730 # the word signal, the signal name and the numeric value.
1731 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00001732 # We're not being specific about the signal name as some signals have
1733 # multiple names and which name is revealed can vary.
1734 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001735 self.assertIn(str(signal.SIGABRT), error_string)
1736
1737 def test_CalledProcessError_str_unknown_signal(self):
1738 err = subprocess.CalledProcessError(-9876543, "fake cmd")
1739 error_string = str(err)
1740 self.assertIn("unknown signal 9876543.", error_string)
1741
1742 def test_CalledProcessError_str_non_zero(self):
1743 err = subprocess.CalledProcessError(2, "fake cmd")
1744 error_string = str(err)
1745 self.assertIn("non-zero exit status 2.", error_string)
1746
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001747 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001748 # DISCLAIMER: Setting environment variables is *not* a good use
1749 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001750 p = subprocess.Popen([sys.executable, "-c",
1751 'import sys,os;'
1752 'sys.stdout.write(os.getenv("FRUIT"))'],
1753 stdout=subprocess.PIPE,
1754 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02001755 with p:
1756 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001757
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001758 def test_preexec_exception(self):
1759 def raise_it():
1760 raise ValueError("What if two swallows carried a coconut?")
1761 try:
1762 p = subprocess.Popen([sys.executable, "-c", ""],
1763 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001764 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001765 self.assertTrue(
1766 subprocess._posixsubprocess,
1767 "Expected a ValueError from the preexec_fn")
1768 except ValueError as e:
1769 self.assertIn("coconut", e.args[0])
1770 else:
1771 self.fail("Exception raised by preexec_fn did not make it "
1772 "to the parent process.")
1773
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001774 class _TestExecuteChildPopen(subprocess.Popen):
1775 """Used to test behavior at the end of _execute_child."""
1776 def __init__(self, testcase, *args, **kwargs):
1777 self._testcase = testcase
1778 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001779
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001780 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001781 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001782 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001783 finally:
1784 # Open a bunch of file descriptors and verify that
1785 # none of them are the same as the ones the Popen
1786 # instance is using for stdin/stdout/stderr.
1787 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1788 for _ in range(8)]
1789 try:
1790 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001791 self._testcase.assertNotIn(
1792 fd, (self.stdin.fileno(), self.stdout.fileno(),
1793 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001794 msg="At least one fd was closed early.")
1795 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01001796 for fd in devzero_fds:
1797 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001798
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001799 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1800 def test_preexec_errpipe_does_not_double_close_pipes(self):
1801 """Issue16140: Don't double close pipes on preexec error."""
1802
1803 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08001804 raise subprocess.SubprocessError(
1805 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001806
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08001807 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001808 self._TestExecuteChildPopen(
1809 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001810 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1811 stderr=subprocess.PIPE, preexec_fn=raise_it)
1812
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001813 def test_preexec_gc_module_failure(self):
1814 # This tests the code that disables garbage collection if the child
1815 # process will execute any Python.
1816 def raise_runtime_error():
1817 raise RuntimeError("this shouldn't escape")
1818 enabled = gc.isenabled()
1819 orig_gc_disable = gc.disable
1820 orig_gc_isenabled = gc.isenabled
1821 try:
1822 gc.disable()
1823 self.assertFalse(gc.isenabled())
1824 subprocess.call([sys.executable, '-c', ''],
1825 preexec_fn=lambda: None)
1826 self.assertFalse(gc.isenabled(),
1827 "Popen enabled gc when it shouldn't.")
1828
1829 gc.enable()
1830 self.assertTrue(gc.isenabled())
1831 subprocess.call([sys.executable, '-c', ''],
1832 preexec_fn=lambda: None)
1833 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1834
1835 gc.disable = raise_runtime_error
1836 self.assertRaises(RuntimeError, subprocess.Popen,
1837 [sys.executable, '-c', ''],
1838 preexec_fn=lambda: None)
1839
1840 del gc.isenabled # force an AttributeError
1841 self.assertRaises(AttributeError, subprocess.Popen,
1842 [sys.executable, '-c', ''],
1843 preexec_fn=lambda: None)
1844 finally:
1845 gc.disable = orig_gc_disable
1846 gc.isenabled = orig_gc_isenabled
1847 if not enabled:
1848 gc.disable()
1849
Martin Panterf7fdbda2015-12-05 09:51:52 +00001850 @unittest.skipIf(
1851 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00001852 def test_preexec_fork_failure(self):
1853 # The internal code did not preserve the previous exception when
1854 # re-enabling garbage collection
1855 try:
1856 from resource import getrlimit, setrlimit, RLIMIT_NPROC
1857 except ImportError as err:
1858 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
1859 limits = getrlimit(RLIMIT_NPROC)
1860 [_, hard] = limits
1861 setrlimit(RLIMIT_NPROC, (0, hard))
1862 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00001863 try:
Martin Panterafdd5132015-11-30 02:21:41 +00001864 subprocess.call([sys.executable, '-c', ''],
1865 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00001866 except BlockingIOError:
1867 # Forking should raise EAGAIN, translated to BlockingIOError
1868 pass
1869 else:
1870 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00001871
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001872 def test_args_string(self):
1873 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03001874 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001875 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001876 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001877 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001878 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1879 sys.executable)
1880 os.chmod(fname, 0o700)
1881 p = subprocess.Popen(fname)
1882 p.wait()
1883 os.remove(fname)
1884 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001885
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001886 def test_invalid_args(self):
1887 # invalid arguments should raise ValueError
1888 self.assertRaises(ValueError, subprocess.call,
1889 [sys.executable, "-c",
1890 "import sys; sys.exit(47)"],
1891 startupinfo=47)
1892 self.assertRaises(ValueError, subprocess.call,
1893 [sys.executable, "-c",
1894 "import sys; sys.exit(47)"],
1895 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001896
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001897 def test_shell_sequence(self):
1898 # Run command through the shell (sequence)
1899 newenv = os.environ.copy()
1900 newenv["FRUIT"] = "apple"
1901 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1902 stdout=subprocess.PIPE,
1903 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001904 with p:
1905 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001906
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001907 def test_shell_string(self):
1908 # Run command through the shell (string)
1909 newenv = os.environ.copy()
1910 newenv["FRUIT"] = "apple"
1911 p = subprocess.Popen("echo $FRUIT", shell=1,
1912 stdout=subprocess.PIPE,
1913 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001914 with p:
1915 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001916
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001917 def test_call_string(self):
1918 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03001919 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001920 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001921 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001922 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001923 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1924 sys.executable)
1925 os.chmod(fname, 0o700)
1926 rc = subprocess.call(fname)
1927 os.remove(fname)
1928 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001929
Stefan Krah9542cc62010-07-19 14:20:53 +00001930 def test_specific_shell(self):
1931 # Issue #9265: Incorrect name passed as arg[0].
1932 shells = []
1933 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1934 for name in ['bash', 'ksh']:
1935 sh = os.path.join(prefix, name)
1936 if os.path.isfile(sh):
1937 shells.append(sh)
1938 if not shells: # Will probably work for any shell but csh.
1939 self.skipTest("bash or ksh required for this test")
1940 sh = '/bin/sh'
1941 if os.path.isfile(sh) and not os.path.islink(sh):
1942 # Test will fail if /bin/sh is a symlink to csh.
1943 shells.append(sh)
1944 for sh in shells:
1945 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1946 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02001947 with p:
1948 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00001949
Florent Xicluna4886d242010-03-08 13:27:26 +00001950 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001951 # Do not inherit file handles from the parent.
1952 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07001953 # Also set the SIGINT handler to the default to make sure it's not
1954 # being ignored (some tests rely on that.)
1955 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
1956 try:
1957 p = subprocess.Popen([sys.executable, "-c", """if 1:
1958 import sys, time
1959 sys.stdout.write('x\\n')
1960 sys.stdout.flush()
1961 time.sleep(30)
1962 """],
1963 close_fds=True,
1964 stdin=subprocess.PIPE,
1965 stdout=subprocess.PIPE,
1966 stderr=subprocess.PIPE)
1967 finally:
1968 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001969 # Wait for the interpreter to be completely initialized before
1970 # sending any signal.
1971 p.stdout.read(1)
1972 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001973 return p
1974
Charles-François Natali53221e32013-01-12 16:52:20 +01001975 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1976 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001977 def _kill_dead_process(self, method, *args):
1978 # Do not inherit file handles from the parent.
1979 # It should fix failures on some platforms.
1980 p = subprocess.Popen([sys.executable, "-c", """if 1:
1981 import sys, time
1982 sys.stdout.write('x\\n')
1983 sys.stdout.flush()
1984 """],
1985 close_fds=True,
1986 stdin=subprocess.PIPE,
1987 stdout=subprocess.PIPE,
1988 stderr=subprocess.PIPE)
1989 # Wait for the interpreter to be completely initialized before
1990 # sending any signal.
1991 p.stdout.read(1)
1992 # The process should end after this
1993 time.sleep(1)
1994 # This shouldn't raise even though the child is now dead
1995 getattr(p, method)(*args)
1996 p.communicate()
1997
Florent Xicluna4886d242010-03-08 13:27:26 +00001998 def test_send_signal(self):
1999 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00002000 _, stderr = p.communicate()
2001 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002002 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00002003
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002004 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002005 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00002006 _, stderr = p.communicate()
2007 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002008 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00002009
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002010 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002011 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00002012 _, stderr = p.communicate()
2013 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002014 self.assertEqual(p.wait(), -signal.SIGTERM)
2015
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002016 def test_send_signal_dead(self):
2017 # Sending a signal to a dead process
2018 self._kill_dead_process('send_signal', signal.SIGINT)
2019
2020 def test_kill_dead(self):
2021 # Killing a dead process
2022 self._kill_dead_process('kill')
2023
2024 def test_terminate_dead(self):
2025 # Terminating a dead process
2026 self._kill_dead_process('terminate')
2027
Victor Stinnerdaf45552013-08-28 00:53:59 +02002028 def _save_fds(self, save_fds):
2029 fds = []
2030 for fd in save_fds:
2031 inheritable = os.get_inheritable(fd)
2032 saved = os.dup(fd)
2033 fds.append((fd, saved, inheritable))
2034 return fds
2035
2036 def _restore_fds(self, fds):
2037 for fd, saved, inheritable in fds:
2038 os.dup2(saved, fd, inheritable=inheritable)
2039 os.close(saved)
2040
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002041 def check_close_std_fds(self, fds):
2042 # Issue #9905: test that subprocess pipes still work properly with
2043 # some standard fds closed
2044 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02002045 saved_fds = self._save_fds(fds)
2046 for fd, saved, inheritable in saved_fds:
2047 if fd == 0:
2048 stdin = saved
2049 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002050 try:
2051 for fd in fds:
2052 os.close(fd)
2053 out, err = subprocess.Popen([sys.executable, "-c",
2054 'import sys;'
2055 'sys.stdout.write("apple");'
2056 'sys.stdout.flush();'
2057 'sys.stderr.write("orange")'],
2058 stdin=stdin,
2059 stdout=subprocess.PIPE,
2060 stderr=subprocess.PIPE).communicate()
2061 err = support.strip_python_stderr(err)
2062 self.assertEqual((out, err), (b'apple', b'orange'))
2063 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002064 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002065
2066 def test_close_fd_0(self):
2067 self.check_close_std_fds([0])
2068
2069 def test_close_fd_1(self):
2070 self.check_close_std_fds([1])
2071
2072 def test_close_fd_2(self):
2073 self.check_close_std_fds([2])
2074
2075 def test_close_fds_0_1(self):
2076 self.check_close_std_fds([0, 1])
2077
2078 def test_close_fds_0_2(self):
2079 self.check_close_std_fds([0, 2])
2080
2081 def test_close_fds_1_2(self):
2082 self.check_close_std_fds([1, 2])
2083
2084 def test_close_fds_0_1_2(self):
2085 # Issue #10806: test that subprocess pipes still work properly with
2086 # all standard fds closed.
2087 self.check_close_std_fds([0, 1, 2])
2088
Gregory P. Smith53dd8162013-12-01 16:03:24 -08002089 def test_small_errpipe_write_fd(self):
2090 """Issue #15798: Popen should work when stdio fds are available."""
2091 new_stdin = os.dup(0)
2092 new_stdout = os.dup(1)
2093 try:
2094 os.close(0)
2095 os.close(1)
2096
2097 # Side test: if errpipe_write fails to have its CLOEXEC
2098 # flag set this should cause the parent to think the exec
2099 # failed. Extremely unlikely: everyone supports CLOEXEC.
2100 subprocess.Popen([
2101 sys.executable, "-c",
2102 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
2103 finally:
2104 # Restore original stdin and stdout
2105 os.dup2(new_stdin, 0)
2106 os.dup2(new_stdout, 1)
2107 os.close(new_stdin)
2108 os.close(new_stdout)
2109
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002110 def test_remapping_std_fds(self):
2111 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002112 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002113 try:
2114 temp_fds = [fd for fd, fname in temps]
2115
2116 # unlink the files -- we won't need to reopen them
2117 for fd, fname in temps:
2118 os.unlink(fname)
2119
2120 # write some data to what will become stdin, and rewind
2121 os.write(temp_fds[1], b"STDIN")
2122 os.lseek(temp_fds[1], 0, 0)
2123
2124 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02002125 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002126 try:
2127 # duplicate the file objects over the standard fd's
2128 for fd, temp_fd in enumerate(temp_fds):
2129 os.dup2(temp_fd, fd)
2130
2131 # now use those files in the "wrong" order, so that subprocess
2132 # has to rearrange them in the child
2133 p = subprocess.Popen([sys.executable, "-c",
2134 'import sys; got = sys.stdin.read();'
2135 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2136 stdin=temp_fds[1],
2137 stdout=temp_fds[2],
2138 stderr=temp_fds[0])
2139 p.wait()
2140 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002141 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002142
2143 for fd in temp_fds:
2144 os.lseek(fd, 0, 0)
2145
2146 out = os.read(temp_fds[2], 1024)
2147 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
2148 self.assertEqual(out, b"got STDIN")
2149 self.assertEqual(err, b"err")
2150
2151 finally:
2152 for fd in temp_fds:
2153 os.close(fd)
2154
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002155 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
2156 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002157 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002158 temp_fds = [fd for fd, fname in temps]
2159 try:
2160 # unlink the files -- we won't need to reopen them
2161 for fd, fname in temps:
2162 os.unlink(fname)
2163
2164 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02002165 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002166 try:
2167 # duplicate the temp files over the standard fd's 0, 1, 2
2168 for fd, temp_fd in enumerate(temp_fds):
2169 os.dup2(temp_fd, fd)
2170
2171 # write some data to what will become stdin, and rewind
2172 os.write(stdin_no, b"STDIN")
2173 os.lseek(stdin_no, 0, 0)
2174
2175 # now use those files in the given order, so that subprocess
2176 # has to rearrange them in the child
2177 p = subprocess.Popen([sys.executable, "-c",
2178 'import sys; got = sys.stdin.read();'
2179 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2180 stdin=stdin_no,
2181 stdout=stdout_no,
2182 stderr=stderr_no)
2183 p.wait()
2184
2185 for fd in temp_fds:
2186 os.lseek(fd, 0, 0)
2187
2188 out = os.read(stdout_no, 1024)
2189 err = support.strip_python_stderr(os.read(stderr_no, 1024))
2190 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002191 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002192
2193 self.assertEqual(out, b"got STDIN")
2194 self.assertEqual(err, b"err")
2195
2196 finally:
2197 for fd in temp_fds:
2198 os.close(fd)
2199
2200 # When duping fds, if there arises a situation where one of the fds is
2201 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
2202 # This tests all combinations of this.
2203 def test_swap_fds(self):
2204 self.check_swap_fds(0, 1, 2)
2205 self.check_swap_fds(0, 2, 1)
2206 self.check_swap_fds(1, 0, 2)
2207 self.check_swap_fds(1, 2, 0)
2208 self.check_swap_fds(2, 0, 1)
2209 self.check_swap_fds(2, 1, 0)
2210
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +03002211 def _check_swap_std_fds_with_one_closed(self, from_fds, to_fds):
2212 saved_fds = self._save_fds(range(3))
2213 try:
2214 for from_fd in from_fds:
2215 with tempfile.TemporaryFile() as f:
2216 os.dup2(f.fileno(), from_fd)
2217
2218 fd_to_close = (set(range(3)) - set(from_fds)).pop()
2219 os.close(fd_to_close)
2220
2221 arg_names = ['stdin', 'stdout', 'stderr']
2222 kwargs = {}
2223 for from_fd, to_fd in zip(from_fds, to_fds):
2224 kwargs[arg_names[to_fd]] = from_fd
2225
2226 code = textwrap.dedent(r'''
2227 import os, sys
2228 skipped_fd = int(sys.argv[1])
2229 for fd in range(3):
2230 if fd != skipped_fd:
2231 os.write(fd, str(fd).encode('ascii'))
2232 ''')
2233
2234 skipped_fd = (set(range(3)) - set(to_fds)).pop()
2235
2236 rc = subprocess.call([sys.executable, '-c', code, str(skipped_fd)],
2237 **kwargs)
2238 self.assertEqual(rc, 0)
2239
2240 for from_fd, to_fd in zip(from_fds, to_fds):
2241 os.lseek(from_fd, 0, os.SEEK_SET)
2242 read_bytes = os.read(from_fd, 1024)
2243 read_fds = list(map(int, read_bytes.decode('ascii')))
2244 msg = textwrap.dedent(f"""
2245 When testing {from_fds} to {to_fds} redirection,
2246 parent descriptor {from_fd} got redirected
2247 to descriptor(s) {read_fds} instead of descriptor {to_fd}.
2248 """)
2249 self.assertEqual([to_fd], read_fds, msg)
2250 finally:
2251 self._restore_fds(saved_fds)
2252
2253 # Check that subprocess can remap std fds correctly even
2254 # if one of them is closed (#32844).
2255 def test_swap_std_fds_with_one_closed(self):
2256 for from_fds in itertools.combinations(range(3), 2):
2257 for to_fds in itertools.permutations(range(3), 2):
2258 self._check_swap_std_fds_with_one_closed(from_fds, to_fds)
2259
Victor Stinner13bb71c2010-04-23 21:41:56 +00002260 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00002261 def prepare():
2262 raise ValueError("surrogate:\uDCff")
2263
2264 try:
2265 subprocess.call(
2266 [sys.executable, "-c", "pass"],
2267 preexec_fn=prepare)
2268 except ValueError as err:
2269 # Pure Python implementations keeps the message
2270 self.assertIsNone(subprocess._posixsubprocess)
2271 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002272 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00002273 # _posixsubprocess uses a default message
2274 self.assertIsNotNone(subprocess._posixsubprocess)
2275 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
2276 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002277 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00002278
Victor Stinner13bb71c2010-04-23 21:41:56 +00002279 def test_undecodable_env(self):
2280 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01002281 encoded_value = value.encode("ascii", "surrogateescape")
2282
Victor Stinner13bb71c2010-04-23 21:41:56 +00002283 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002284 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002285 env = os.environ.copy()
2286 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01002287 # Use C locale to get ASCII for the locale encoding to force
Michael Felt89d79b12018-08-26 19:29:36 +02002288 # surrogate-escaping of \xFF in the child process
Victor Stinnerebc78d22010-10-14 10:38:17 +00002289 env['LC_ALL'] = 'C'
Michael Felt89d79b12018-08-26 19:29:36 +02002290 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002291 stdout = subprocess.check_output(
2292 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002293 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002294 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002295 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002296
2297 # test bytes
2298 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002299 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002300 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01002301 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002302 stdout = subprocess.check_output(
2303 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002304 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002305 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002306 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002307
Victor Stinnerb745a742010-05-18 17:17:23 +00002308 def test_bytes_program(self):
2309 abs_program = os.fsencode(sys.executable)
2310 path, program = os.path.split(sys.executable)
2311 program = os.fsencode(program)
2312
2313 # absolute bytes path
2314 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00002315 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002316
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002317 # absolute bytes path as a string
2318 cmd = b"'" + abs_program + b"' -c pass"
2319 exitcode = subprocess.call(cmd, shell=True)
2320 self.assertEqual(exitcode, 0)
2321
Victor Stinnerb745a742010-05-18 17:17:23 +00002322 # bytes program, unicode PATH
2323 env = os.environ.copy()
2324 env["PATH"] = path
2325 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002326 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002327
2328 # bytes program, bytes PATH
2329 envb = os.environb.copy()
2330 envb[b"PATH"] = os.fsencode(path)
2331 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002332 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002333
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002334 def test_pipe_cloexec(self):
2335 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2336 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2337
2338 p1 = subprocess.Popen([sys.executable, sleeper],
2339 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2340 stderr=subprocess.PIPE, close_fds=False)
2341
2342 self.addCleanup(p1.communicate, b'')
2343
2344 p2 = subprocess.Popen([sys.executable, fd_status],
2345 stdout=subprocess.PIPE, close_fds=False)
2346
2347 output, error = p2.communicate()
2348 result_fds = set(map(int, output.split(b',')))
2349 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2350 p1.stderr.fileno()])
2351
2352 self.assertFalse(result_fds & unwanted_fds,
2353 "Expected no fds from %r to be open in child, "
2354 "found %r" %
2355 (unwanted_fds, result_fds & unwanted_fds))
2356
2357 def test_pipe_cloexec_real_tools(self):
2358 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2359 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2360
2361 subdata = b'zxcvbn'
2362 data = subdata * 4 + b'\n'
2363
2364 p1 = subprocess.Popen([sys.executable, qcat],
2365 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2366 close_fds=False)
2367
2368 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2369 stdin=p1.stdout, stdout=subprocess.PIPE,
2370 close_fds=False)
2371
2372 self.addCleanup(p1.wait)
2373 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002374 def kill_p1():
2375 try:
2376 p1.terminate()
2377 except ProcessLookupError:
2378 pass
2379 def kill_p2():
2380 try:
2381 p2.terminate()
2382 except ProcessLookupError:
2383 pass
2384 self.addCleanup(kill_p1)
2385 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002386
2387 p1.stdin.write(data)
2388 p1.stdin.close()
2389
2390 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2391
2392 self.assertTrue(readfiles, "The child hung")
2393 self.assertEqual(p2.stdout.read(), data)
2394
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002395 p1.stdout.close()
2396 p2.stdout.close()
2397
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002398 def test_close_fds(self):
2399 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2400
2401 fds = os.pipe()
2402 self.addCleanup(os.close, fds[0])
2403 self.addCleanup(os.close, fds[1])
2404
2405 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002406 # add a bunch more fds
2407 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002408 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002409 self.addCleanup(os.close, fd)
2410 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002411
Victor Stinnerdaf45552013-08-28 00:53:59 +02002412 for fd in open_fds:
2413 os.set_inheritable(fd, True)
2414
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002415 p = subprocess.Popen([sys.executable, fd_status],
2416 stdout=subprocess.PIPE, close_fds=False)
2417 output, ignored = p.communicate()
2418 remaining_fds = set(map(int, output.split(b',')))
2419
2420 self.assertEqual(remaining_fds & open_fds, open_fds,
2421 "Some fds were closed")
2422
2423 p = subprocess.Popen([sys.executable, fd_status],
2424 stdout=subprocess.PIPE, close_fds=True)
2425 output, ignored = p.communicate()
2426 remaining_fds = set(map(int, output.split(b',')))
2427
2428 self.assertFalse(remaining_fds & open_fds,
2429 "Some fds were left open")
2430 self.assertIn(1, remaining_fds, "Subprocess failed")
2431
Gregory P. Smith8facece2012-01-21 14:01:08 -08002432 # Keep some of the fd's we opened open in the subprocess.
2433 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2434 fds_to_keep = set(open_fds.pop() for _ in range(8))
2435 p = subprocess.Popen([sys.executable, fd_status],
2436 stdout=subprocess.PIPE, close_fds=True,
izbyshev2d8f0632017-12-19 03:26:49 +07002437 pass_fds=fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002438 output, ignored = p.communicate()
2439 remaining_fds = set(map(int, output.split(b',')))
2440
izbyshev2d8f0632017-12-19 03:26:49 +07002441 self.assertFalse((remaining_fds - fds_to_keep) & open_fds,
Gregory P. Smith8facece2012-01-21 14:01:08 -08002442 "Some fds not in pass_fds were left open")
2443 self.assertIn(1, remaining_fds, "Subprocess failed")
2444
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002445
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002446 @unittest.skipIf(sys.platform.startswith("freebsd") and
2447 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2448 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002449 def test_close_fds_when_max_fd_is_lowered(self):
2450 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2451 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2452
Gregory P. Smith634aa682014-06-15 17:51:04 -07002453 # This launches the meat of the test in a child process to
2454 # avoid messing with the larger unittest processes maximum
2455 # number of file descriptors.
2456 # This process launches:
2457 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2458 # a bunch of high open fds above the new lower rlimit.
2459 # Those are reported via stdout before launching a new
2460 # process with close_fds=False to run the actual test:
2461 # +--> The TEST: This one launches a fd_status.py
2462 # subprocess with close_fds=True so we can find out if
2463 # any of the fds above the lowered rlimit are still open.
2464 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2465 '''
2466 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002467 open_fds = set()
2468 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002469 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002470 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002471 open_fds.add(fd)
2472
2473 # Leave a two pairs of low ones available for use by the
2474 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002475 # We also leave 10 more open as some Python buildbots run into
2476 # "too many open files" errors during the test if we do not.
2477 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002478 os.close(fd)
2479 open_fds.remove(fd)
2480
2481 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002482 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002483 os.set_inheritable(fd, True)
2484
2485 max_fd_open = max(open_fds)
2486
Gregory P. Smith634aa682014-06-15 17:51:04 -07002487 # Communicate the open_fds to the parent unittest.TestCase process.
2488 print(','.join(map(str, sorted(open_fds))))
2489 sys.stdout.flush()
2490
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002491 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2492 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002493 # 29 is lower than the highest fds we are leaving open.
2494 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002495 # Launch a new Python interpreter with our low fd rlim_cur that
2496 # inherits open fds above that limit. It then uses subprocess
2497 # with close_fds=True to get a report of open fds in the child.
2498 # An explicit list of fds to check is passed to fd_status.py as
2499 # letting fd_status rely on its default logic would miss the
2500 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002501 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002502 [sys.executable, '-c',
2503 textwrap.dedent("""
2504 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002505 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002506 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002507 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002508 """.format(max_fd=max_fd_open+1))],
2509 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002510 finally:
2511 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002512 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002513
2514 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002515 output_lines = output.splitlines()
2516 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002517 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002518 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2519 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002520
Gregory P. Smith634aa682014-06-15 17:51:04 -07002521 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002522 msg="Some fds were left open.")
2523
2524
Victor Stinner88701e22011-06-01 13:13:04 +02002525 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2526 # descriptor of a pipe closed in the parent process is valid in the
2527 # child process according to fstat(), but the mode of the file
2528 # descriptor is invalid, and read or write raise an error.
2529 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002530 def test_pass_fds(self):
2531 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2532
2533 open_fds = set()
2534
2535 for x in range(5):
2536 fds = os.pipe()
2537 self.addCleanup(os.close, fds[0])
2538 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002539 os.set_inheritable(fds[0], True)
2540 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002541 open_fds.update(fds)
2542
2543 for fd in open_fds:
2544 p = subprocess.Popen([sys.executable, fd_status],
2545 stdout=subprocess.PIPE, close_fds=True,
2546 pass_fds=(fd, ))
2547 output, ignored = p.communicate()
2548
2549 remaining_fds = set(map(int, output.split(b',')))
2550 to_be_closed = open_fds - {fd}
2551
2552 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2553 self.assertFalse(remaining_fds & to_be_closed,
2554 "fd to be closed passed")
2555
2556 # pass_fds overrides close_fds with a warning.
2557 with self.assertWarns(RuntimeWarning) as context:
2558 self.assertFalse(subprocess.call(
2559 [sys.executable, "-c", "import sys; sys.exit(0)"],
2560 close_fds=False, pass_fds=(fd, )))
2561 self.assertIn('overriding close_fds', str(context.warning))
2562
Victor Stinnerdaf45552013-08-28 00:53:59 +02002563 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002564 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002565
2566 inheritable, non_inheritable = os.pipe()
2567 self.addCleanup(os.close, inheritable)
2568 self.addCleanup(os.close, non_inheritable)
2569 os.set_inheritable(inheritable, True)
2570 os.set_inheritable(non_inheritable, False)
2571 pass_fds = (inheritable, non_inheritable)
2572 args = [sys.executable, script]
2573 args += list(map(str, pass_fds))
2574
2575 p = subprocess.Popen(args,
2576 stdout=subprocess.PIPE, close_fds=True,
2577 pass_fds=pass_fds)
2578 output, ignored = p.communicate()
2579 fds = set(map(int, output.split(b',')))
2580
2581 # the inheritable file descriptor must be inherited, so its inheritable
2582 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002583 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002584
2585 # inheritable flag must not be changed in the parent process
2586 self.assertEqual(os.get_inheritable(inheritable), True)
2587 self.assertEqual(os.get_inheritable(non_inheritable), False)
2588
Gregory P. Smithce344102018-09-10 17:46:22 -07002589
2590 # bpo-32270: Ensure that descriptors specified in pass_fds
2591 # are inherited even if they are used in redirections.
2592 # Contributed by @izbyshev.
2593 def test_pass_fds_redirected(self):
2594 """Regression test for https://bugs.python.org/issue32270."""
2595 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2596 pass_fds = []
2597 for _ in range(2):
2598 fd = os.open(os.devnull, os.O_RDWR)
2599 self.addCleanup(os.close, fd)
2600 pass_fds.append(fd)
2601
2602 stdout_r, stdout_w = os.pipe()
2603 self.addCleanup(os.close, stdout_r)
2604 self.addCleanup(os.close, stdout_w)
2605 pass_fds.insert(1, stdout_w)
2606
2607 with subprocess.Popen([sys.executable, fd_status],
2608 stdin=pass_fds[0],
2609 stdout=pass_fds[1],
2610 stderr=pass_fds[2],
2611 close_fds=True,
2612 pass_fds=pass_fds):
2613 output = os.read(stdout_r, 1024)
2614 fds = {int(num) for num in output.split(b',')}
2615
2616 self.assertEqual(fds, {0, 1, 2} | frozenset(pass_fds), f"output={output!a}")
2617
2618
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002619 def test_stdout_stdin_are_single_inout_fd(self):
2620 with io.open(os.devnull, "r+") as inout:
2621 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2622 stdout=inout, stdin=inout)
2623 p.wait()
2624
2625 def test_stdout_stderr_are_single_inout_fd(self):
2626 with io.open(os.devnull, "r+") as inout:
2627 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2628 stdout=inout, stderr=inout)
2629 p.wait()
2630
2631 def test_stderr_stdin_are_single_inout_fd(self):
2632 with io.open(os.devnull, "r+") as inout:
2633 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2634 stderr=inout, stdin=inout)
2635 p.wait()
2636
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002637 def test_wait_when_sigchild_ignored(self):
2638 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2639 sigchild_ignore = support.findfile("sigchild_ignore.py",
2640 subdir="subprocessdata")
2641 p = subprocess.Popen([sys.executable, sigchild_ignore],
2642 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2643 stdout, stderr = p.communicate()
2644 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002645 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002646 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002647
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002648 def test_select_unbuffered(self):
2649 # Issue #11459: bufsize=0 should really set the pipes as
2650 # unbuffered (and therefore let select() work properly).
2651 select = support.import_module("select")
2652 p = subprocess.Popen([sys.executable, "-c",
2653 'import sys;'
2654 'sys.stdout.write("apple")'],
2655 stdout=subprocess.PIPE,
2656 bufsize=0)
2657 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002658 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002659 try:
2660 self.assertEqual(f.read(4), b"appl")
2661 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2662 finally:
2663 p.wait()
2664
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002665 def test_zombie_fast_process_del(self):
2666 # Issue #12650: on Unix, if Popen.__del__() was called before the
2667 # process exited, it wouldn't be added to subprocess._active, and would
2668 # remain a zombie.
2669 # spawn a Popen, and delete its reference before it exits
2670 p = subprocess.Popen([sys.executable, "-c",
2671 'import sys, time;'
2672 'time.sleep(0.2)'],
2673 stdout=subprocess.PIPE,
2674 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002675 self.addCleanup(p.stdout.close)
2676 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002677 ident = id(p)
2678 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002679 with support.check_warnings(('', ResourceWarning)):
2680 p = None
2681
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002682 # check that p is in the active processes list
2683 self.assertIn(ident, [id(o) for o in subprocess._active])
2684
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002685 def test_leak_fast_process_del_killed(self):
2686 # Issue #12650: on Unix, if Popen.__del__() was called before the
2687 # process exited, and the process got killed by a signal, it would never
2688 # be removed from subprocess._active, which triggered a FD and memory
2689 # leak.
2690 # spawn a Popen, delete its reference and kill it
2691 p = subprocess.Popen([sys.executable, "-c",
2692 'import time;'
2693 'time.sleep(3)'],
2694 stdout=subprocess.PIPE,
2695 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002696 self.addCleanup(p.stdout.close)
2697 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002698 ident = id(p)
2699 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002700 with support.check_warnings(('', ResourceWarning)):
2701 p = None
2702
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002703 os.kill(pid, signal.SIGKILL)
2704 # check that p is in the active processes list
2705 self.assertIn(ident, [id(o) for o in subprocess._active])
2706
2707 # let some time for the process to exit, and create a new Popen: this
2708 # should trigger the wait() of p
2709 time.sleep(0.2)
Victor Stinnerb31206a2018-01-25 19:06:05 +01002710 with self.assertRaises(OSError):
Victor Stinner9a83f652017-08-21 23:51:31 +02002711 with subprocess.Popen(NONEXISTING_CMD,
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002712 stdout=subprocess.PIPE,
2713 stderr=subprocess.PIPE) as proc:
2714 pass
2715 # p should have been wait()ed on, and removed from the _active list
2716 self.assertRaises(OSError, os.waitpid, pid, 0)
2717 self.assertNotIn(ident, [id(o) for o in subprocess._active])
2718
Charles-François Natali249cdc32013-08-25 18:24:45 +02002719 def test_close_fds_after_preexec(self):
2720 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2721
2722 # this FD is used as dup2() target by preexec_fn, and should be closed
2723 # in the child process
2724 fd = os.dup(1)
2725 self.addCleanup(os.close, fd)
2726
2727 p = subprocess.Popen([sys.executable, fd_status],
2728 stdout=subprocess.PIPE, close_fds=True,
2729 preexec_fn=lambda: os.dup2(1, fd))
2730 output, ignored = p.communicate()
2731
2732 remaining_fds = set(map(int, output.split(b',')))
2733
2734 self.assertNotIn(fd, remaining_fds)
2735
Victor Stinner8f437aa2014-10-05 17:25:19 +02002736 @support.cpython_only
2737 def test_fork_exec(self):
2738 # Issue #22290: fork_exec() must not crash on memory allocation failure
2739 # or other errors
2740 import _posixsubprocess
2741 gc_enabled = gc.isenabled()
2742 try:
2743 # Use a preexec function and enable the garbage collector
2744 # to force fork_exec() to re-enable the garbage collector
2745 # on error.
2746 func = lambda: None
2747 gc.enable()
2748
Victor Stinner8f437aa2014-10-05 17:25:19 +02002749 for args, exe_list, cwd, env_list in (
2750 (123, [b"exe"], None, [b"env"]),
2751 ([b"arg"], 123, None, [b"env"]),
2752 ([b"arg"], [b"exe"], 123, [b"env"]),
2753 ([b"arg"], [b"exe"], None, 123),
2754 ):
2755 with self.assertRaises(TypeError):
2756 _posixsubprocess.fork_exec(
2757 args, exe_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002758 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02002759 -1, -1, -1, -1,
2760 1, 2, 3, 4,
2761 True, True, func)
2762 finally:
2763 if not gc_enabled:
2764 gc.disable()
2765
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002766 @support.cpython_only
2767 def test_fork_exec_sorted_fd_sanity_check(self):
2768 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
2769 import _posixsubprocess
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002770 class BadInt:
2771 first = True
2772 def __init__(self, value):
2773 self.value = value
2774 def __int__(self):
2775 if self.first:
2776 self.first = False
2777 return self.value
2778 raise ValueError
2779
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002780 gc_enabled = gc.isenabled()
2781 try:
2782 gc.enable()
2783
2784 for fds_to_keep in (
2785 (-1, 2, 3, 4, 5), # Negative number.
2786 ('str', 4), # Not an int.
2787 (18, 23, 42, 2**63), # Out of range.
2788 (5, 4), # Not sorted.
2789 (6, 7, 7, 8), # Duplicate.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002790 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002791 ):
2792 with self.assertRaises(
2793 ValueError,
2794 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
2795 _posixsubprocess.fork_exec(
2796 [b"false"], [b"false"],
2797 True, fds_to_keep, None, [b"env"],
2798 -1, -1, -1, -1,
2799 1, 2, 3, 4,
2800 True, True, None)
2801 self.assertIn('fds_to_keep', str(c.exception))
2802 finally:
2803 if not gc_enabled:
2804 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02002805
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00002806 def test_communicate_BrokenPipeError_stdin_close(self):
2807 # By not setting stdout or stderr or a timeout we force the fast path
2808 # that just calls _stdin_write() internally due to our mock.
2809 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2810 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2811 mock_proc_stdin.close.side_effect = BrokenPipeError
2812 proc.communicate() # Should swallow BrokenPipeError from close.
2813 mock_proc_stdin.close.assert_called_with()
2814
2815 def test_communicate_BrokenPipeError_stdin_write(self):
2816 # By not setting stdout or stderr or a timeout we force the fast path
2817 # that just calls _stdin_write() internally due to our mock.
2818 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2819 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2820 mock_proc_stdin.write.side_effect = BrokenPipeError
2821 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
2822 mock_proc_stdin.write.assert_called_once_with(b'stuff')
2823 mock_proc_stdin.close.assert_called_once_with()
2824
2825 def test_communicate_BrokenPipeError_stdin_flush(self):
2826 # Setting stdin and stdout forces the ._communicate() code path.
2827 # python -h exits faster than python -c pass (but spams stdout).
2828 proc = subprocess.Popen([sys.executable, '-h'],
2829 stdin=subprocess.PIPE,
2830 stdout=subprocess.PIPE)
2831 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
2832 open(os.devnull, 'wb') as dev_null:
2833 mock_proc_stdin.flush.side_effect = BrokenPipeError
2834 # because _communicate registers a selector using proc.stdin...
2835 mock_proc_stdin.fileno.return_value = dev_null.fileno()
2836 # _communicate() should swallow BrokenPipeError from flush.
2837 proc.communicate(b'stuff')
2838 mock_proc_stdin.flush.assert_called_once_with()
2839
2840 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
2841 # Setting stdin and stdout forces the ._communicate() code path.
2842 # python -h exits faster than python -c pass (but spams stdout).
2843 proc = subprocess.Popen([sys.executable, '-h'],
2844 stdin=subprocess.PIPE,
2845 stdout=subprocess.PIPE)
2846 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2847 mock_proc_stdin.close.side_effect = BrokenPipeError
2848 # _communicate() should swallow BrokenPipeError from close.
2849 proc.communicate(timeout=999)
2850 mock_proc_stdin.close.assert_called_once_with()
2851
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002852 @unittest.skipUnless(_testcapi is not None
2853 and hasattr(_testcapi, 'W_STOPCODE'),
2854 'need _testcapi.W_STOPCODE')
2855 def test_stopped(self):
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002856 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002857 args = [sys.executable, '-c', 'pass']
2858 proc = subprocess.Popen(args)
Victor Stinnercdee3f12017-06-26 17:23:03 +02002859
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002860 # Wait until the real process completes to avoid zombie process
2861 pid = proc.pid
2862 pid, status = os.waitpid(pid, 0)
2863 self.assertEqual(status, 0)
Victor Stinnercdee3f12017-06-26 17:23:03 +02002864
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002865 status = _testcapi.W_STOPCODE(3)
2866 with mock.patch('subprocess.os.waitpid', return_value=(pid, status)):
2867 returncode = proc.wait()
Victor Stinnercdee3f12017-06-26 17:23:03 +02002868
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002869 self.assertEqual(returncode, -3)
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002870
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002871
Victor Stinner937ee9e2018-06-26 02:11:06 +02002872@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00002873class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002874
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002875 def test_startupinfo(self):
2876 # startupinfo argument
2877 # We uses hardcoded constants, because we do not want to
2878 # depend on win32all.
2879 STARTF_USESHOWWINDOW = 1
2880 SW_MAXIMIZE = 3
2881 startupinfo = subprocess.STARTUPINFO()
2882 startupinfo.dwFlags = STARTF_USESHOWWINDOW
2883 startupinfo.wShowWindow = SW_MAXIMIZE
2884 # Since Python is a console process, it won't be affected
2885 # by wShowWindow, but the argument should be silently
2886 # ignored
2887 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002888 startupinfo=startupinfo)
2889
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05302890 def test_startupinfo_keywords(self):
2891 # startupinfo argument
2892 # We use hardcoded constants, because we do not want to
2893 # depend on win32all.
2894 STARTF_USERSHOWWINDOW = 1
2895 SW_MAXIMIZE = 3
2896 startupinfo = subprocess.STARTUPINFO(
2897 dwFlags=STARTF_USERSHOWWINDOW,
2898 wShowWindow=SW_MAXIMIZE
2899 )
2900 # Since Python is a console process, it won't be affected
2901 # by wShowWindow, but the argument should be silently
2902 # ignored
2903 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
2904 startupinfo=startupinfo)
2905
Victor Stinner483422f2018-07-05 22:54:17 +02002906 def test_startupinfo_copy(self):
2907 # bpo-34044: Popen must not modify input STARTUPINFO structure
2908 startupinfo = subprocess.STARTUPINFO()
2909 startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
2910 startupinfo.wShowWindow = subprocess.SW_HIDE
2911
2912 # Call Popen() twice with the same startupinfo object to make sure
2913 # that it's not modified
2914 for _ in range(2):
2915 cmd = [sys.executable, "-c", "pass"]
2916 with open(os.devnull, 'w') as null:
2917 proc = subprocess.Popen(cmd,
2918 stdout=null,
2919 stderr=subprocess.STDOUT,
2920 startupinfo=startupinfo)
2921 with proc:
2922 proc.communicate()
2923 self.assertEqual(proc.returncode, 0)
2924
2925 self.assertEqual(startupinfo.dwFlags,
2926 subprocess.STARTF_USESHOWWINDOW)
2927 self.assertIsNone(startupinfo.hStdInput)
2928 self.assertIsNone(startupinfo.hStdOutput)
2929 self.assertIsNone(startupinfo.hStdError)
2930 self.assertEqual(startupinfo.wShowWindow, subprocess.SW_HIDE)
2931 self.assertEqual(startupinfo.lpAttributeList, {"handle_list": []})
2932
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002933 def test_creationflags(self):
2934 # creationflags argument
2935 CREATE_NEW_CONSOLE = 16
2936 sys.stderr.write(" a DOS box should flash briefly ...\n")
2937 subprocess.call(sys.executable +
2938 ' -c "import time; time.sleep(0.25)"',
2939 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002940
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002941 def test_invalid_args(self):
2942 # invalid arguments should raise ValueError
2943 self.assertRaises(ValueError, subprocess.call,
2944 [sys.executable, "-c",
2945 "import sys; sys.exit(47)"],
2946 preexec_fn=lambda: 1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002947
Oren Milman0b3a87e2017-09-14 22:30:28 +03002948 @support.cpython_only
2949 def test_issue31471(self):
2950 # There shouldn't be an assertion failure in Popen() in case the env
2951 # argument has a bad keys() method.
2952 class BadEnv(dict):
2953 keys = None
2954 with self.assertRaises(TypeError):
2955 subprocess.Popen([sys.executable, "-c", "pass"], env=BadEnv())
2956
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002957 def test_close_fds(self):
2958 # close file descriptors
2959 rc = subprocess.call([sys.executable, "-c",
2960 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002961 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002962 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002963
Segev Finerb2a60832017-12-18 11:28:19 +02002964 def test_close_fds_with_stdio(self):
2965 import msvcrt
2966
2967 fds = os.pipe()
2968 self.addCleanup(os.close, fds[0])
2969 self.addCleanup(os.close, fds[1])
2970
2971 handles = []
2972 for fd in fds:
2973 os.set_inheritable(fd, True)
2974 handles.append(msvcrt.get_osfhandle(fd))
2975
2976 p = subprocess.Popen([sys.executable, "-c",
2977 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
2978 stdout=subprocess.PIPE, close_fds=False)
2979 stdout, stderr = p.communicate()
2980 self.assertEqual(p.returncode, 0)
2981 int(stdout.strip()) # Check that stdout is an integer
2982
2983 p = subprocess.Popen([sys.executable, "-c",
2984 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
2985 stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
2986 stdout, stderr = p.communicate()
2987 self.assertEqual(p.returncode, 1)
2988 self.assertIn(b"OSError", stderr)
2989
2990 # The same as the previous call, but with an empty handle_list
2991 handle_list = []
2992 startupinfo = subprocess.STARTUPINFO()
2993 startupinfo.lpAttributeList = {"handle_list": handle_list}
2994 p = subprocess.Popen([sys.executable, "-c",
2995 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
2996 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
2997 startupinfo=startupinfo, close_fds=True)
2998 stdout, stderr = p.communicate()
2999 self.assertEqual(p.returncode, 1)
3000 self.assertIn(b"OSError", stderr)
3001
3002 # Check for a warning due to using handle_list and close_fds=False
3003 with support.check_warnings((".*overriding close_fds", RuntimeWarning)):
3004 startupinfo = subprocess.STARTUPINFO()
3005 startupinfo.lpAttributeList = {"handle_list": handles[:]}
3006 p = subprocess.Popen([sys.executable, "-c",
3007 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3008 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3009 startupinfo=startupinfo, close_fds=False)
3010 stdout, stderr = p.communicate()
3011 self.assertEqual(p.returncode, 0)
3012
3013 def test_empty_attribute_list(self):
3014 startupinfo = subprocess.STARTUPINFO()
3015 startupinfo.lpAttributeList = {}
3016 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
3017 startupinfo=startupinfo)
3018
3019 def test_empty_handle_list(self):
3020 startupinfo = subprocess.STARTUPINFO()
3021 startupinfo.lpAttributeList = {"handle_list": []}
3022 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
3023 startupinfo=startupinfo)
3024
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003025 def test_shell_sequence(self):
3026 # Run command through the shell (sequence)
3027 newenv = os.environ.copy()
3028 newenv["FRUIT"] = "physalis"
3029 p = subprocess.Popen(["set"], shell=1,
3030 stdout=subprocess.PIPE,
3031 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003032 with p:
3033 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00003034
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003035 def test_shell_string(self):
3036 # Run command through the shell (string)
3037 newenv = os.environ.copy()
3038 newenv["FRUIT"] = "physalis"
3039 p = subprocess.Popen("set", shell=1,
3040 stdout=subprocess.PIPE,
3041 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003042 with p:
3043 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003044
Steve Dower050acae2016-09-06 20:16:17 -07003045 def test_shell_encodings(self):
3046 # Run command through the shell (string)
3047 for enc in ['ansi', 'oem']:
3048 newenv = os.environ.copy()
3049 newenv["FRUIT"] = "physalis"
3050 p = subprocess.Popen("set", shell=1,
3051 stdout=subprocess.PIPE,
3052 env=newenv,
3053 encoding=enc)
3054 with p:
3055 self.assertIn("physalis", p.stdout.read(), enc)
3056
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003057 def test_call_string(self):
3058 # call() function with string argument on Windows
3059 rc = subprocess.call(sys.executable +
3060 ' -c "import sys; sys.exit(47)"')
3061 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003062
Florent Xicluna4886d242010-03-08 13:27:26 +00003063 def _kill_process(self, method, *args):
3064 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00003065 p = subprocess.Popen([sys.executable, "-c", """if 1:
3066 import sys, time
3067 sys.stdout.write('x\\n')
3068 sys.stdout.flush()
3069 time.sleep(30)
3070 """],
3071 stdin=subprocess.PIPE,
3072 stdout=subprocess.PIPE,
3073 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003074 with p:
3075 # Wait for the interpreter to be completely initialized before
3076 # sending any signal.
3077 p.stdout.read(1)
3078 getattr(p, method)(*args)
3079 _, stderr = p.communicate()
3080 self.assertStderrEqual(stderr, b'')
3081 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00003082 self.assertNotEqual(returncode, 0)
3083
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003084 def _kill_dead_process(self, method, *args):
3085 p = subprocess.Popen([sys.executable, "-c", """if 1:
3086 import sys, time
3087 sys.stdout.write('x\\n')
3088 sys.stdout.flush()
3089 sys.exit(42)
3090 """],
3091 stdin=subprocess.PIPE,
3092 stdout=subprocess.PIPE,
3093 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003094 with p:
3095 # Wait for the interpreter to be completely initialized before
3096 # sending any signal.
3097 p.stdout.read(1)
3098 # The process should end after this
3099 time.sleep(1)
3100 # This shouldn't raise even though the child is now dead
3101 getattr(p, method)(*args)
3102 _, stderr = p.communicate()
3103 self.assertStderrEqual(stderr, b'')
3104 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003105 self.assertEqual(rc, 42)
3106
Florent Xicluna4886d242010-03-08 13:27:26 +00003107 def test_send_signal(self):
3108 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00003109
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003110 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003111 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00003112
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003113 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003114 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00003115
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003116 def test_send_signal_dead(self):
3117 self._kill_dead_process('send_signal', signal.SIGTERM)
3118
3119 def test_kill_dead(self):
3120 self._kill_dead_process('kill')
3121
3122 def test_terminate_dead(self):
3123 self._kill_dead_process('terminate')
3124
Martin Panter23172bd2016-04-16 11:28:10 +00003125class MiscTests(unittest.TestCase):
Gregory P. Smithf4d644f2018-01-29 21:27:39 -08003126
3127 class RecordingPopen(subprocess.Popen):
3128 """A Popen that saves a reference to each instance for testing."""
3129 instances_created = []
3130
3131 def __init__(self, *args, **kwargs):
3132 super().__init__(*args, **kwargs)
3133 self.instances_created.append(self)
3134
3135 @mock.patch.object(subprocess.Popen, "_communicate")
3136 def _test_keyboardinterrupt_no_kill(self, popener, mock__communicate,
3137 **kwargs):
3138 """Fake a SIGINT happening during Popen._communicate() and ._wait().
3139
3140 This avoids the need to actually try and get test environments to send
3141 and receive signals reliably across platforms. The net effect of a ^C
3142 happening during a blocking subprocess execution which we want to clean
3143 up from is a KeyboardInterrupt coming out of communicate() or wait().
3144 """
3145
3146 mock__communicate.side_effect = KeyboardInterrupt
3147 try:
3148 with mock.patch.object(subprocess.Popen, "_wait") as mock__wait:
3149 # We patch out _wait() as no signal was involved so the
3150 # child process isn't actually going to exit rapidly.
3151 mock__wait.side_effect = KeyboardInterrupt
3152 with mock.patch.object(subprocess, "Popen",
3153 self.RecordingPopen):
3154 with self.assertRaises(KeyboardInterrupt):
3155 popener([sys.executable, "-c",
3156 "import time\ntime.sleep(9)\nimport sys\n"
3157 "sys.stderr.write('\\n!runaway child!\\n')"],
3158 stdout=subprocess.DEVNULL, **kwargs)
3159 for call in mock__wait.call_args_list[1:]:
3160 self.assertNotEqual(
3161 call, mock.call(timeout=None),
3162 "no open-ended wait() after the first allowed: "
3163 f"{mock__wait.call_args_list}")
3164 sigint_calls = []
3165 for call in mock__wait.call_args_list:
3166 if call == mock.call(timeout=0.25): # from Popen.__init__
3167 sigint_calls.append(call)
3168 self.assertLessEqual(mock__wait.call_count, 2,
3169 msg=mock__wait.call_args_list)
3170 self.assertEqual(len(sigint_calls), 1,
3171 msg=mock__wait.call_args_list)
3172 finally:
3173 # cleanup the forgotten (due to our mocks) child process
3174 process = self.RecordingPopen.instances_created.pop()
3175 process.kill()
3176 process.wait()
3177 self.assertEqual([], self.RecordingPopen.instances_created)
3178
3179 def test_call_keyboardinterrupt_no_kill(self):
3180 self._test_keyboardinterrupt_no_kill(subprocess.call, timeout=6.282)
3181
3182 def test_run_keyboardinterrupt_no_kill(self):
3183 self._test_keyboardinterrupt_no_kill(subprocess.run, timeout=6.282)
3184
3185 def test_context_manager_keyboardinterrupt_no_kill(self):
3186 def popen_via_context_manager(*args, **kwargs):
3187 with subprocess.Popen(*args, **kwargs) as unused_process:
3188 raise KeyboardInterrupt # Test how __exit__ handles ^C.
3189 self._test_keyboardinterrupt_no_kill(popen_via_context_manager)
3190
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003191 def test_getoutput(self):
3192 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
3193 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
3194 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00003195
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003196 # we use mkdtemp in the next line to create an empty directory
3197 # under our exclusive control; from that, we can invent a pathname
3198 # that we _know_ won't exist. This is guaranteed to fail.
3199 dir = None
3200 try:
3201 dir = tempfile.mkdtemp()
3202 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00003203 status, output = subprocess.getstatusoutput(
Victor Stinner937ee9e2018-06-26 02:11:06 +02003204 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003205 self.assertNotEqual(status, 0)
3206 finally:
3207 if dir is not None:
3208 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00003209
Gregory P. Smithace55862015-04-07 15:57:54 -07003210 def test__all__(self):
3211 """Ensure that __all__ is populated properly."""
Martin Panter528619b2016-04-16 23:42:37 +00003212 intentionally_excluded = {"list2cmdline", "Handle"}
Gregory P. Smithace55862015-04-07 15:57:54 -07003213 exported = set(subprocess.__all__)
3214 possible_exports = set()
3215 import types
3216 for name, value in subprocess.__dict__.items():
3217 if name.startswith('_'):
3218 continue
3219 if isinstance(value, (types.ModuleType,)):
3220 continue
3221 possible_exports.add(name)
3222 self.assertEqual(exported, possible_exports - intentionally_excluded)
3223
3224
Martin Panter23172bd2016-04-16 11:28:10 +00003225@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
3226 "Test needs selectors.PollSelector")
3227class ProcessTestCaseNoPoll(ProcessTestCase):
3228 def setUp(self):
3229 self.orig_selector = subprocess._PopenSelector
3230 subprocess._PopenSelector = selectors.SelectSelector
3231 ProcessTestCase.setUp(self)
3232
3233 def tearDown(self):
3234 subprocess._PopenSelector = self.orig_selector
3235 ProcessTestCase.tearDown(self)
3236
Gregory P. Smithd06fa472009-07-04 02:46:54 +00003237
Victor Stinner937ee9e2018-06-26 02:11:06 +02003238@unittest.skipUnless(mswindows, "Windows-specific tests")
Tim Golden126c2962010-08-11 14:20:40 +00003239class CommandsWithSpaces (BaseTestCase):
3240
3241 def setUp(self):
3242 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03003243 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00003244 self.fname = fname.lower ()
3245 os.write(f, b"import sys;"
3246 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
3247 )
3248 os.close(f)
3249
3250 def tearDown(self):
3251 os.remove(self.fname)
3252 super().tearDown()
3253
3254 def with_spaces(self, *args, **kwargs):
3255 kwargs['stdout'] = subprocess.PIPE
3256 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02003257 with p:
3258 self.assertEqual(
3259 p.stdout.read ().decode("mbcs"),
3260 "2 [%r, 'ab cd']" % self.fname
3261 )
Tim Golden126c2962010-08-11 14:20:40 +00003262
3263 def test_shell_string_with_spaces(self):
3264 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003265 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3266 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003267
3268 def test_shell_sequence_with_spaces(self):
3269 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003270 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003271
3272 def test_noshell_string_with_spaces(self):
3273 # call() function with string argument with spaces on Windows
3274 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3275 "ab cd"))
3276
3277 def test_noshell_sequence_with_spaces(self):
3278 # call() function with sequence argument with spaces on Windows
3279 self.with_spaces([sys.executable, self.fname, "ab cd"])
3280
Brian Curtin79cdb662010-12-03 02:46:02 +00003281
Georg Brandla86b2622012-02-20 21:34:57 +01003282class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00003283
3284 def test_pipe(self):
3285 with subprocess.Popen([sys.executable, "-c",
3286 "import sys;"
3287 "sys.stdout.write('stdout');"
3288 "sys.stderr.write('stderr');"],
3289 stdout=subprocess.PIPE,
3290 stderr=subprocess.PIPE) as proc:
3291 self.assertEqual(proc.stdout.read(), b"stdout")
3292 self.assertStderrEqual(proc.stderr.read(), b"stderr")
3293
3294 self.assertTrue(proc.stdout.closed)
3295 self.assertTrue(proc.stderr.closed)
3296
3297 def test_returncode(self):
3298 with subprocess.Popen([sys.executable, "-c",
3299 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07003300 pass
3301 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00003302 self.assertEqual(proc.returncode, 100)
3303
3304 def test_communicate_stdin(self):
3305 with subprocess.Popen([sys.executable, "-c",
3306 "import sys;"
3307 "sys.exit(sys.stdin.read() == 'context')"],
3308 stdin=subprocess.PIPE) as proc:
3309 proc.communicate(b"context")
3310 self.assertEqual(proc.returncode, 1)
3311
3312 def test_invalid_args(self):
Victor Stinnerb31206a2018-01-25 19:06:05 +01003313 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02003314 with subprocess.Popen(NONEXISTING_CMD,
Brian Curtin79cdb662010-12-03 02:46:02 +00003315 stdout=subprocess.PIPE,
3316 stderr=subprocess.PIPE) as proc:
3317 pass
3318
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003319 def test_broken_pipe_cleanup(self):
3320 """Broken pipe error should not prevent wait() (Issue 21619)"""
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003321 proc = subprocess.Popen([sys.executable, '-c', 'pass'],
Victor Stinner20f4bd42015-03-05 02:38:41 +01003322 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003323 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003324 proc = proc.__enter__()
3325 # Prepare to send enough data to overflow any OS pipe buffering and
3326 # guarantee a broken pipe error. Data is held in BufferedWriter
3327 # buffer until closed.
3328 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003329 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003330 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02003331 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003332 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003333 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003334
Brian Curtin79cdb662010-12-03 02:46:02 +00003335
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003336if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04003337 unittest.main()