blob: 9bfc21123cc01697fb4b497d256d2af49b3fbb94 [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +00002from unittest import mock
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003from test import support
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00004import subprocess
5import sys
6import signal
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04007import io
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +03008import itertools
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00009import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +000010import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000011import tempfile
12import time
Charles-François Natali3a4586a2013-11-08 19:56:59 +010013import selectors
Ezio Melotti184bdfb2010-02-18 09:37:05 +000014import sysconfig
Gregory P. Smith51ee2702010-12-13 07:59:39 +000015import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040016import shutil
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020017import threading
Benjamin Petersonb870aa12011-12-10 12:44:25 -050018import gc
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030019import textwrap
Serhiy Storchakab21d1552018-03-02 11:53:51 +020020from test.support import FakePath
Benjamin Peterson964561b2011-12-10 12:31:42 -050021
22try:
Victor Stinner7b7c6dc2017-08-10 12:37:39 +020023 import _testcapi
24except ImportError:
25 _testcapi = None
26
Victor Stinner466e18e2019-07-01 19:01:52 +020027
Steve Dower22d06982016-09-06 19:38:15 -070028if support.PGO:
29 raise unittest.SkipTest("test is not helpful for PGO")
30
Victor Stinner937ee9e2018-06-26 02:11:06 +020031mswindows = (sys.platform == "win32")
32
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000033#
34# Depends on the following external programs: Python
35#
36
Victor Stinner937ee9e2018-06-26 02:11:06 +020037if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000038 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
39 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000040else:
41 SETBINARY = ''
42
Victor Stinner9a83f652017-08-21 23:51:31 +020043NONEXISTING_CMD = ('nonexisting_i_hope',)
Victor Stinnerb31206a2018-01-25 19:06:05 +010044# Ignore errors that indicate the command was not found
45NONEXISTING_ERRORS = (FileNotFoundError, NotADirectoryError, PermissionError)
Victor Stinner9a83f652017-08-21 23:51:31 +020046
Florent Xiclunab1e94e82010-02-27 22:12:37 +000047
Florent Xiclunac049d872010-03-27 22:47:23 +000048class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000049 def setUp(self):
50 # Try to minimize the number of children we have so this test
51 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000052 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000053
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000054 def tearDown(self):
55 for inst in subprocess._active:
56 inst.wait()
57 subprocess._cleanup()
58 self.assertFalse(subprocess._active, "subprocess._active not empty")
Victor Stinnercc42c122017-07-28 18:00:22 +020059 self.doCleanups()
60 support.reap_children()
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000061
Florent Xiclunab1e94e82010-02-27 22:12:37 +000062 def assertStderrEqual(self, stderr, expected, msg=None):
63 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
64 # shutdown time. That frustrates tests trying to check stderr produced
65 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000066 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040067 # strip_python_stderr also strips whitespace, so we do too.
68 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000069 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000070
Florent Xiclunac049d872010-03-27 22:47:23 +000071
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080072class PopenTestException(Exception):
73 pass
74
75
76class PopenExecuteChildRaises(subprocess.Popen):
77 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
78 _execute_child fails.
79 """
80 def _execute_child(self, *args, **kwargs):
81 raise PopenTestException("Forced Exception for Test")
82
83
Florent Xiclunac049d872010-03-27 22:47:23 +000084class ProcessTestCase(BaseTestCase):
85
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070086 def test_io_buffered_by_default(self):
87 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
88 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
89 stderr=subprocess.PIPE)
90 try:
91 self.assertIsInstance(p.stdin, io.BufferedIOBase)
92 self.assertIsInstance(p.stdout, io.BufferedIOBase)
93 self.assertIsInstance(p.stderr, io.BufferedIOBase)
94 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -070095 p.stdin.close()
96 p.stdout.close()
97 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070098 p.wait()
99
100 def test_io_unbuffered_works(self):
101 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
102 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
103 stderr=subprocess.PIPE, bufsize=0)
104 try:
105 self.assertIsInstance(p.stdin, io.RawIOBase)
106 self.assertIsInstance(p.stdout, io.RawIOBase)
107 self.assertIsInstance(p.stderr, io.RawIOBase)
108 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700109 p.stdin.close()
110 p.stdout.close()
111 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700112 p.wait()
113
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000114 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000115 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000116 rc = subprocess.call([sys.executable, "-c",
117 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000118 self.assertEqual(rc, 47)
119
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400120 def test_call_timeout(self):
121 # call() function with timeout argument; we want to test that the child
122 # process gets killed when the timeout expires. If the child isn't
123 # killed, this call will deadlock since subprocess.call waits for the
124 # child.
125 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
126 [sys.executable, "-c", "while True: pass"],
127 timeout=0.1)
128
Peter Astrand454f7672005-01-01 09:36:35 +0000129 def test_check_call_zero(self):
130 # check_call() function with zero return code
131 rc = subprocess.check_call([sys.executable, "-c",
132 "import sys; sys.exit(0)"])
133 self.assertEqual(rc, 0)
134
135 def test_check_call_nonzero(self):
136 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000137 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000138 subprocess.check_call([sys.executable, "-c",
139 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000140 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000141
Georg Brandlf9734072008-12-07 15:30:06 +0000142 def test_check_output(self):
143 # check_output() function with zero return code
144 output = subprocess.check_output(
145 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000146 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000147
148 def test_check_output_nonzero(self):
149 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000150 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000151 subprocess.check_output(
152 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000153 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000154
155 def test_check_output_stderr(self):
156 # check_output() function stderr redirected to stdout
157 output = subprocess.check_output(
158 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
159 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000160 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000161
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300162 def test_check_output_stdin_arg(self):
163 # check_output() can be called with stdin set to a file
164 tf = tempfile.TemporaryFile()
165 self.addCleanup(tf.close)
166 tf.write(b'pear')
167 tf.seek(0)
168 output = subprocess.check_output(
169 [sys.executable, "-c",
170 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
171 stdin=tf)
172 self.assertIn(b'PEAR', output)
173
174 def test_check_output_input_arg(self):
175 # check_output() can be called with input set to a string
176 output = subprocess.check_output(
177 [sys.executable, "-c",
178 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
179 input=b'pear')
180 self.assertIn(b'PEAR', output)
181
Georg Brandlf9734072008-12-07 15:30:06 +0000182 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300183 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000184 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000185 output = subprocess.check_output(
186 [sys.executable, "-c", "print('will not be run')"],
187 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000188 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000189 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000190
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300191 def test_check_output_stdin_with_input_arg(self):
192 # check_output() refuses to accept 'stdin' with 'input'
193 tf = tempfile.TemporaryFile()
194 self.addCleanup(tf.close)
195 tf.write(b'pear')
196 tf.seek(0)
197 with self.assertRaises(ValueError) as c:
198 output = subprocess.check_output(
199 [sys.executable, "-c", "print('will not be run')"],
200 stdin=tf, input=b'hare')
201 self.fail("Expected ValueError when stdin and input args supplied.")
202 self.assertIn('stdin', c.exception.args[0])
203 self.assertIn('input', c.exception.args[0])
204
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400205 def test_check_output_timeout(self):
206 # check_output() function with timeout arg
207 with self.assertRaises(subprocess.TimeoutExpired) as c:
208 output = subprocess.check_output(
209 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200210 "import sys, time\n"
211 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400212 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200213 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400214 # Some heavily loaded buildbots (sparc Debian 3.x) require
215 # this much time to start and print.
216 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400217 self.fail("Expected TimeoutExpired.")
218 self.assertEqual(c.exception.output, b'BDFL')
219
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000220 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000221 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000222 newenv = os.environ.copy()
223 newenv["FRUIT"] = "banana"
224 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000225 'import sys, os;'
226 'sys.exit(os.getenv("FRUIT")=="banana")'],
227 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000228 self.assertEqual(rc, 1)
229
Victor Stinner87b9bc32011-06-01 00:57:47 +0200230 def test_invalid_args(self):
231 # Popen() called with invalid arguments should raise TypeError
232 # but Popen.__del__ should not complain (issue #12085)
233 with support.captured_stderr() as s:
234 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
235 argcount = subprocess.Popen.__init__.__code__.co_argcount
236 too_many_args = [0] * (argcount + 1)
237 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
238 self.assertEqual(s.getvalue(), '')
239
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000240 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000241 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000242 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000243 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000244 self.addCleanup(p.stdout.close)
245 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000246 p.wait()
247 self.assertEqual(p.stdin, None)
248
249 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200250 # .stdout is None when not redirected, and the child's stdout will
251 # be inherited from the parent. In order to test this we run a
252 # subprocess in a subprocess:
253 # this_test
254 # \-- subprocess created by this test (parent)
255 # \-- subprocess created by the parent subprocess (child)
256 # The parent doesn't specify stdout, so the child will use the
257 # parent's stdout. This test checks that the message printed by the
258 # child goes to the parent stdout. The parent also checks that the
259 # child's stdout is None. See #11963.
260 code = ('import sys; from subprocess import Popen, PIPE;'
261 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
262 ' stdin=PIPE, stderr=PIPE);'
263 'p.wait(); assert p.stdout is None;')
264 p = subprocess.Popen([sys.executable, "-c", code],
265 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
266 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000267 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200268 out, err = p.communicate()
269 self.assertEqual(p.returncode, 0, err)
270 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000271
272 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000273 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000274 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000275 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000276 self.addCleanup(p.stdout.close)
277 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000278 p.wait()
279 self.assertEqual(p.stderr, None)
280
Chris Jerdonek776cb192012-10-08 15:56:43 -0700281 def _assert_python(self, pre_args, **kwargs):
282 # We include sys.exit() to prevent the test runner from hanging
283 # whenever python is found.
284 args = pre_args + ["import sys; sys.exit(47)"]
285 p = subprocess.Popen(args, **kwargs)
286 p.wait()
287 self.assertEqual(47, p.returncode)
288
289 def test_executable(self):
290 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700291 #
292 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
293 # determine where its standard library is, so we need the directory
294 # of args[0] to be valid for the Popen() call to Python to succeed.
295 # See also issue #16170 and issue #7774.
296 doesnotexist = os.path.join(os.path.dirname(sys.executable),
297 "doesnotexist")
298 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700299
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300300 def test_bytes_executable(self):
301 doesnotexist = os.path.join(os.path.dirname(sys.executable),
302 "doesnotexist")
303 self._assert_python([doesnotexist, "-c"],
304 executable=os.fsencode(sys.executable))
305
306 def test_pathlike_executable(self):
307 doesnotexist = os.path.join(os.path.dirname(sys.executable),
308 "doesnotexist")
309 self._assert_python([doesnotexist, "-c"],
310 executable=FakePath(sys.executable))
311
Chris Jerdonek776cb192012-10-08 15:56:43 -0700312 def test_executable_takes_precedence(self):
313 # Check that the executable argument takes precedence over args[0].
314 #
315 # Verify first that the call succeeds without the executable arg.
316 pre_args = [sys.executable, "-c"]
317 self._assert_python(pre_args)
Victor Stinnerb31206a2018-01-25 19:06:05 +0100318 self.assertRaises(NONEXISTING_ERRORS,
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +0100319 self._assert_python, pre_args,
Victor Stinnerb31206a2018-01-25 19:06:05 +0100320 executable=NONEXISTING_CMD[0])
Chris Jerdonek776cb192012-10-08 15:56:43 -0700321
Victor Stinner937ee9e2018-06-26 02:11:06 +0200322 @unittest.skipIf(mswindows, "executable argument replaces shell")
Chris Jerdonek776cb192012-10-08 15:56:43 -0700323 def test_executable_replaces_shell(self):
324 # Check that the executable argument replaces the default shell
325 # when shell=True.
326 self._assert_python([], executable=sys.executable, shell=True)
327
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300328 @unittest.skipIf(mswindows, "executable argument replaces shell")
329 def test_bytes_executable_replaces_shell(self):
330 self._assert_python([], executable=os.fsencode(sys.executable),
331 shell=True)
332
333 @unittest.skipIf(mswindows, "executable argument replaces shell")
334 def test_pathlike_executable_replaces_shell(self):
335 self._assert_python([], executable=FakePath(sys.executable),
336 shell=True)
337
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700338 # For use in the test_cwd* tests below.
339 def _normalize_cwd(self, cwd):
340 # Normalize an expected cwd (for Tru64 support).
341 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
342 # strings. See bug #1063571.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300343 with support.change_cwd(cwd):
344 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700345
346 # For use in the test_cwd* tests below.
347 def _split_python_path(self):
348 # Return normalized (python_dir, python_base).
349 python_path = os.path.realpath(sys.executable)
350 return os.path.split(python_path)
351
352 # For use in the test_cwd* tests below.
353 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
354 # Invoke Python via Popen, and assert that (1) the call succeeds,
355 # and that (2) the current working directory of the child process
356 # matches *expected_cwd*.
357 p = subprocess.Popen([python_arg, "-c",
358 "import os, sys; "
359 "sys.stdout.write(os.getcwd()); "
360 "sys.exit(47)"],
361 stdout=subprocess.PIPE,
362 **kwargs)
363 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000364 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700365 self.assertEqual(47, p.returncode)
366 normcase = os.path.normcase
367 self.assertEqual(normcase(expected_cwd),
368 normcase(p.stdout.read().decode("utf-8")))
369
370 def test_cwd(self):
371 # Check that cwd changes the cwd for the child process.
372 temp_dir = tempfile.gettempdir()
373 temp_dir = self._normalize_cwd(temp_dir)
374 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
375
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300376 def test_cwd_with_bytes(self):
377 temp_dir = tempfile.gettempdir()
378 temp_dir = self._normalize_cwd(temp_dir)
379 self._assert_cwd(temp_dir, sys.executable, cwd=os.fsencode(temp_dir))
380
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530381 def test_cwd_with_pathlike(self):
382 temp_dir = tempfile.gettempdir()
383 temp_dir = self._normalize_cwd(temp_dir)
Serhiy Storchakab21d1552018-03-02 11:53:51 +0200384 self._assert_cwd(temp_dir, sys.executable, cwd=FakePath(temp_dir))
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530385
Victor Stinner937ee9e2018-06-26 02:11:06 +0200386 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700387 def test_cwd_with_relative_arg(self):
388 # Check that Popen looks for args[0] relative to cwd if args[0]
389 # is relative.
390 python_dir, python_base = self._split_python_path()
391 rel_python = os.path.join(os.curdir, python_base)
392 with support.temp_cwd() as wrong_dir:
393 # Before calling with the correct cwd, confirm that the call fails
394 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700395 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700396 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700397 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700398 [rel_python], cwd=wrong_dir)
399 python_dir = self._normalize_cwd(python_dir)
400 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
401
Victor Stinner937ee9e2018-06-26 02:11:06 +0200402 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700403 def test_cwd_with_relative_executable(self):
404 # Check that Popen looks for executable relative to cwd if executable
405 # is relative (and that executable takes precedence over args[0]).
406 python_dir, python_base = self._split_python_path()
407 rel_python = os.path.join(os.curdir, python_base)
408 doesntexist = "somethingyoudonthave"
409 with support.temp_cwd() as wrong_dir:
410 # Before calling with the correct cwd, confirm that the call fails
411 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700412 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700413 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700414 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700415 [doesntexist], executable=rel_python,
416 cwd=wrong_dir)
417 python_dir = self._normalize_cwd(python_dir)
418 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
419 cwd=python_dir)
420
421 def test_cwd_with_absolute_arg(self):
422 # Check that Popen can find the executable when the cwd is wrong
423 # if args[0] is an absolute path.
424 python_dir, python_base = self._split_python_path()
425 abs_python = os.path.join(python_dir, python_base)
426 rel_python = os.path.join(os.curdir, python_base)
Berker Peksagce643912015-05-06 06:33:17 +0300427 with support.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700428 # Before calling with an absolute path, confirm that using a
429 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700430 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700431 [rel_python], cwd=wrong_dir)
432 wrong_dir = self._normalize_cwd(wrong_dir)
433 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
434
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100435 @unittest.skipIf(sys.base_prefix != sys.prefix,
436 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000437 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700438 python_dir, python_base = self._split_python_path()
439 python_dir = self._normalize_cwd(python_dir)
440 self._assert_cwd(python_dir, "somethingyoudonthave",
441 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000442
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100443 @unittest.skipIf(sys.base_prefix != sys.prefix,
444 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000445 @unittest.skipIf(sysconfig.is_python_build(),
446 "need an installed Python. See #7774")
447 def test_executable_without_cwd(self):
448 # For a normal installation, it should work without 'cwd'
449 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700450 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
451 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000452
453 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000454 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000455 p = subprocess.Popen([sys.executable, "-c",
456 'import sys; sys.exit(sys.stdin.read() == "pear")'],
457 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000458 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000459 p.stdin.close()
460 p.wait()
461 self.assertEqual(p.returncode, 1)
462
463 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000464 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000465 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000466 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000467 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000468 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000469 os.lseek(d, 0, 0)
470 p = subprocess.Popen([sys.executable, "-c",
471 'import sys; sys.exit(sys.stdin.read() == "pear")'],
472 stdin=d)
473 p.wait()
474 self.assertEqual(p.returncode, 1)
475
476 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000477 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000478 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000479 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000480 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000481 tf.seek(0)
482 p = subprocess.Popen([sys.executable, "-c",
483 'import sys; sys.exit(sys.stdin.read() == "pear")'],
484 stdin=tf)
485 p.wait()
486 self.assertEqual(p.returncode, 1)
487
488 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000489 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000490 p = subprocess.Popen([sys.executable, "-c",
491 'import sys; sys.stdout.write("orange")'],
492 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200493 with p:
494 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000495
496 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000497 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000498 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000499 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000500 d = tf.fileno()
501 p = subprocess.Popen([sys.executable, "-c",
502 'import sys; sys.stdout.write("orange")'],
503 stdout=d)
504 p.wait()
505 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000506 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000507
508 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000509 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000510 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000511 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000512 p = subprocess.Popen([sys.executable, "-c",
513 'import sys; sys.stdout.write("orange")'],
514 stdout=tf)
515 p.wait()
516 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000517 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000518
519 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000520 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000521 p = subprocess.Popen([sys.executable, "-c",
522 'import sys; sys.stderr.write("strawberry")'],
523 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200524 with p:
525 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000526
527 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000528 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000529 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000530 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000531 d = tf.fileno()
532 p = subprocess.Popen([sys.executable, "-c",
533 'import sys; sys.stderr.write("strawberry")'],
534 stderr=d)
535 p.wait()
536 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000537 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000538
539 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000540 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000541 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000542 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000543 p = subprocess.Popen([sys.executable, "-c",
544 'import sys; sys.stderr.write("strawberry")'],
545 stderr=tf)
546 p.wait()
547 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000548 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000549
Martin Panterc7635892016-05-13 01:54:44 +0000550 def test_stderr_redirect_with_no_stdout_redirect(self):
551 # test stderr=STDOUT while stdout=None (not set)
552
553 # - grandchild prints to stderr
554 # - child redirects grandchild's stderr to its stdout
555 # - the parent should get grandchild's stderr in child's stdout
556 p = subprocess.Popen([sys.executable, "-c",
557 'import sys, subprocess;'
558 'rc = subprocess.call([sys.executable, "-c",'
559 ' "import sys;"'
560 ' "sys.stderr.write(\'42\')"],'
561 ' stderr=subprocess.STDOUT);'
562 'sys.exit(rc)'],
563 stdout=subprocess.PIPE,
564 stderr=subprocess.PIPE)
565 stdout, stderr = p.communicate()
566 #NOTE: stdout should get stderr from grandchild
567 self.assertStderrEqual(stdout, b'42')
568 self.assertStderrEqual(stderr, b'') # should be empty
569 self.assertEqual(p.returncode, 0)
570
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000571 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000572 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000573 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000574 'import sys;'
575 'sys.stdout.write("apple");'
576 'sys.stdout.flush();'
577 'sys.stderr.write("orange")'],
578 stdout=subprocess.PIPE,
579 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200580 with p:
581 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000582
583 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000584 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000585 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000586 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000587 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000588 'import sys;'
589 'sys.stdout.write("apple");'
590 'sys.stdout.flush();'
591 'sys.stderr.write("orange")'],
592 stdout=tf,
593 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000594 p.wait()
595 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000596 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000597
Thomas Wouters89f507f2006-12-13 04:49:30 +0000598 def test_stdout_filedes_of_stdout(self):
599 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200600 # To avoid printing the text on stdout, we do something similar to
601 # test_stdout_none (see above). The parent subprocess calls the child
602 # subprocess passing stdout=1, and this test uses stdout=PIPE in
603 # order to capture and check the output of the parent. See #11963.
604 code = ('import sys, subprocess; '
605 'rc = subprocess.call([sys.executable, "-c", '
606 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
607 'b\'test with stdout=1\'))"], stdout=1); '
608 'assert rc == 18')
609 p = subprocess.Popen([sys.executable, "-c", code],
610 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
611 self.addCleanup(p.stdout.close)
612 self.addCleanup(p.stderr.close)
613 out, err = p.communicate()
614 self.assertEqual(p.returncode, 0, err)
615 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000616
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200617 def test_stdout_devnull(self):
618 p = subprocess.Popen([sys.executable, "-c",
619 'for i in range(10240):'
620 'print("x" * 1024)'],
621 stdout=subprocess.DEVNULL)
622 p.wait()
623 self.assertEqual(p.stdout, None)
624
625 def test_stderr_devnull(self):
626 p = subprocess.Popen([sys.executable, "-c",
627 'import sys\n'
628 'for i in range(10240):'
629 'sys.stderr.write("x" * 1024)'],
630 stderr=subprocess.DEVNULL)
631 p.wait()
632 self.assertEqual(p.stderr, None)
633
634 def test_stdin_devnull(self):
635 p = subprocess.Popen([sys.executable, "-c",
636 'import sys;'
637 'sys.stdin.read(1)'],
638 stdin=subprocess.DEVNULL)
639 p.wait()
640 self.assertEqual(p.stdin, None)
641
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000642 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000643 newenv = os.environ.copy()
644 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200645 with subprocess.Popen([sys.executable, "-c",
646 'import sys,os;'
647 'sys.stdout.write(os.getenv("FRUIT"))'],
648 stdout=subprocess.PIPE,
649 env=newenv) as p:
650 stdout, stderr = p.communicate()
651 self.assertEqual(stdout, b"orange")
652
Victor Stinner62d51182011-06-23 01:02:25 +0200653 # Windows requires at least the SYSTEMROOT environment variable to start
654 # Python
655 @unittest.skipIf(sys.platform == 'win32',
656 'cannot test an empty env on Windows')
Gregory P. Smithb3512482017-05-30 14:40:37 -0700657 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
658 'The Python shared library cannot be loaded '
659 'with an empty environment.')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200660 def test_empty_env(self):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700661 """Verify that env={} is as empty as possible."""
662
Gregory P. Smith85aba232017-05-30 16:21:47 -0700663 def is_env_var_to_ignore(n):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700664 """Determine if an environment variable is under our control."""
665 # This excludes some __CF_* and VERSIONER_* keys MacOS insists
666 # on adding even when the environment in exec is empty.
667 # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist.
Gregory P. Smith85aba232017-05-30 16:21:47 -0700668 return ('VERSIONER' in n or '__CF' in n or # MacOS
Ned Deily918edc02017-09-04 00:00:21 -0400669 '__PYVENV_LAUNCHER__' in n or # MacOS framework build
Nick Coghlan6ea41862017-06-11 13:16:15 +1000670 n == 'LD_PRELOAD' or n.startswith('SANDBOX') or # Gentoo
671 n == 'LC_CTYPE') # Locale coercion triggered
Gregory P. Smithb3512482017-05-30 14:40:37 -0700672
Victor Stinnerf1512a22011-06-21 17:18:38 +0200673 with subprocess.Popen([sys.executable, "-c",
Gregory P. Smithb3512482017-05-30 14:40:37 -0700674 'import os; print(list(os.environ.keys()))'],
675 stdout=subprocess.PIPE, env={}) as p:
Victor Stinnerf1512a22011-06-21 17:18:38 +0200676 stdout, stderr = p.communicate()
Gregory P. Smithb3512482017-05-30 14:40:37 -0700677 child_env_names = eval(stdout.strip())
678 self.assertIsInstance(child_env_names, list)
679 child_env_names = [k for k in child_env_names
680 if not is_env_var_to_ignore(k)]
681 self.assertEqual(child_env_names, [])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000682
Serhiy Storchakad174d242017-06-23 19:39:27 +0300683 def test_invalid_cmd(self):
684 # null character in the command name
685 cmd = sys.executable + '\0'
686 with self.assertRaises(ValueError):
687 subprocess.Popen([cmd, "-c", "pass"])
688
689 # null character in the command argument
690 with self.assertRaises(ValueError):
691 subprocess.Popen([sys.executable, "-c", "pass#\0"])
692
693 def test_invalid_env(self):
Ville Skyttä49b27342017-08-03 09:00:59 +0300694 # null character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300695 newenv = os.environ.copy()
696 newenv["FRUIT\0VEGETABLE"] = "cabbage"
697 with self.assertRaises(ValueError):
698 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
699
Ville Skyttä49b27342017-08-03 09:00:59 +0300700 # null character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300701 newenv = os.environ.copy()
702 newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
703 with self.assertRaises(ValueError):
704 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
705
Ville Skyttä49b27342017-08-03 09:00:59 +0300706 # equal character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300707 newenv = os.environ.copy()
708 newenv["FRUIT=ORANGE"] = "lemon"
709 with self.assertRaises(ValueError):
710 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
711
Ville Skyttä49b27342017-08-03 09:00:59 +0300712 # equal character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300713 newenv = os.environ.copy()
714 newenv["FRUIT"] = "orange=lemon"
715 with subprocess.Popen([sys.executable, "-c",
716 'import sys, os;'
717 'sys.stdout.write(os.getenv("FRUIT"))'],
718 stdout=subprocess.PIPE,
719 env=newenv) as p:
720 stdout, stderr = p.communicate()
721 self.assertEqual(stdout, b"orange=lemon")
722
Peter Astrandcbac93c2005-03-03 20:24:28 +0000723 def test_communicate_stdin(self):
724 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000725 'import sys;'
726 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000727 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000728 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000729 self.assertEqual(p.returncode, 1)
730
731 def test_communicate_stdout(self):
732 p = subprocess.Popen([sys.executable, "-c",
733 'import sys; sys.stdout.write("pineapple")'],
734 stdout=subprocess.PIPE)
735 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000736 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000737 self.assertEqual(stderr, None)
738
739 def test_communicate_stderr(self):
740 p = subprocess.Popen([sys.executable, "-c",
741 'import sys; sys.stderr.write("pineapple")'],
742 stderr=subprocess.PIPE)
743 (stdout, stderr) = p.communicate()
744 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000745 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000746
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000747 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000748 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000749 'import sys,os;'
750 'sys.stderr.write("pineapple");'
751 'sys.stdout.write(sys.stdin.read())'],
752 stdin=subprocess.PIPE,
753 stdout=subprocess.PIPE,
754 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000755 self.addCleanup(p.stdout.close)
756 self.addCleanup(p.stderr.close)
757 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000758 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000759 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000760 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000761
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400762 def test_communicate_timeout(self):
763 p = subprocess.Popen([sys.executable, "-c",
764 'import sys,os,time;'
765 'sys.stderr.write("pineapple\\n");'
766 'time.sleep(1);'
767 'sys.stderr.write("pear\\n");'
768 'sys.stdout.write(sys.stdin.read())'],
769 universal_newlines=True,
770 stdin=subprocess.PIPE,
771 stdout=subprocess.PIPE,
772 stderr=subprocess.PIPE)
773 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
774 timeout=0.3)
775 # Make sure we can keep waiting for it, and that we get the whole output
776 # after it completes.
777 (stdout, stderr) = p.communicate()
778 self.assertEqual(stdout, "banana")
779 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
780
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700781 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200782 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400783 p = subprocess.Popen([sys.executable, "-c",
784 'import sys,os,time;'
785 'sys.stdout.write("a" * (64 * 1024));'
786 'time.sleep(0.2);'
787 'sys.stdout.write("a" * (64 * 1024));'
788 'time.sleep(0.2);'
789 'sys.stdout.write("a" * (64 * 1024));'
790 'time.sleep(0.2);'
791 'sys.stdout.write("a" * (64 * 1024));'],
792 stdout=subprocess.PIPE)
793 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
794 (stdout, _) = p.communicate()
795 self.assertEqual(len(stdout), 4 * 64 * 1024)
796
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000797 # Test for the fd leak reported in http://bugs.python.org/issue2791.
798 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000799 for stdin_pipe in (False, True):
800 for stdout_pipe in (False, True):
801 for stderr_pipe in (False, True):
802 options = {}
803 if stdin_pipe:
804 options['stdin'] = subprocess.PIPE
805 if stdout_pipe:
806 options['stdout'] = subprocess.PIPE
807 if stderr_pipe:
808 options['stderr'] = subprocess.PIPE
809 if not options:
810 continue
811 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
812 p.communicate()
813 if p.stdin is not None:
814 self.assertTrue(p.stdin.closed)
815 if p.stdout is not None:
816 self.assertTrue(p.stdout.closed)
817 if p.stderr is not None:
818 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000819
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000820 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000821 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000822 p = subprocess.Popen([sys.executable, "-c",
823 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000824 (stdout, stderr) = p.communicate()
825 self.assertEqual(stdout, None)
826 self.assertEqual(stderr, None)
827
828 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000829 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000830 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000831 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000832 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000833 os.close(x)
834 os.close(y)
835 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000836 'import sys,os;'
837 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200838 'sys.stderr.write("x" * %d);'
839 'sys.stdout.write(sys.stdin.read())' %
840 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000841 stdin=subprocess.PIPE,
842 stdout=subprocess.PIPE,
843 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000844 self.addCleanup(p.stdout.close)
845 self.addCleanup(p.stderr.close)
846 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200847 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000848 (stdout, stderr) = p.communicate(string_to_write)
849 self.assertEqual(stdout, string_to_write)
850
851 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000852 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000853 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000854 'import sys,os;'
855 'sys.stdout.write(sys.stdin.read())'],
856 stdin=subprocess.PIPE,
857 stdout=subprocess.PIPE,
858 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000859 self.addCleanup(p.stdout.close)
860 self.addCleanup(p.stderr.close)
861 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000862 p.stdin.write(b"banana")
863 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000864 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000865 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000866
andyclegg7fed7bd2017-10-23 03:01:19 +0100867 def test_universal_newlines_and_text(self):
868 args = [
869 sys.executable, "-c",
870 'import sys,os;' + SETBINARY +
871 'buf = sys.stdout.buffer;'
872 'buf.write(sys.stdin.readline().encode());'
873 'buf.flush();'
874 'buf.write(b"line2\\n");'
875 'buf.flush();'
876 'buf.write(sys.stdin.read().encode());'
877 'buf.flush();'
878 'buf.write(b"line4\\n");'
879 'buf.flush();'
880 'buf.write(b"line5\\r\\n");'
881 'buf.flush();'
882 'buf.write(b"line6\\r");'
883 'buf.flush();'
884 'buf.write(b"\\nline7");'
885 'buf.flush();'
886 'buf.write(b"\\nline8");']
887
888 for extra_kwarg in ('universal_newlines', 'text'):
889 p = subprocess.Popen(args, **{'stdin': subprocess.PIPE,
890 'stdout': subprocess.PIPE,
891 extra_kwarg: True})
892 with p:
893 p.stdin.write("line1\n")
894 p.stdin.flush()
895 self.assertEqual(p.stdout.readline(), "line1\n")
896 p.stdin.write("line3\n")
897 p.stdin.close()
898 self.addCleanup(p.stdout.close)
899 self.assertEqual(p.stdout.readline(),
900 "line2\n")
901 self.assertEqual(p.stdout.read(6),
902 "line3\n")
903 self.assertEqual(p.stdout.read(),
904 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000905
906 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000907 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000908 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000909 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200910 'buf = sys.stdout.buffer;'
911 'buf.write(b"line2\\n");'
912 'buf.flush();'
913 'buf.write(b"line4\\n");'
914 'buf.flush();'
915 'buf.write(b"line5\\r\\n");'
916 'buf.flush();'
917 'buf.write(b"line6\\r");'
918 'buf.flush();'
919 'buf.write(b"\\nline7");'
920 'buf.flush();'
921 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200922 stderr=subprocess.PIPE,
923 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000924 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000925 self.addCleanup(p.stdout.close)
926 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000927 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200928 self.assertEqual(stdout,
929 "line2\nline4\nline5\nline6\nline7\nline8")
930
931 def test_universal_newlines_communicate_stdin(self):
932 # universal newlines through communicate(), with only stdin
933 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300934 'import sys,os;' + SETBINARY + textwrap.dedent('''
935 s = sys.stdin.readline()
936 assert s == "line1\\n", repr(s)
937 s = sys.stdin.read()
938 assert s == "line3\\n", repr(s)
939 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200940 stdin=subprocess.PIPE,
941 universal_newlines=1)
942 (stdout, stderr) = p.communicate("line1\nline3\n")
943 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000944
Andrew Svetlovf3765072012-08-14 18:35:17 +0300945 def test_universal_newlines_communicate_input_none(self):
946 # Test communicate(input=None) with universal newlines.
947 #
948 # We set stdout to PIPE because, as of this writing, a different
949 # code path is tested when the number of pipes is zero or one.
950 p = subprocess.Popen([sys.executable, "-c", "pass"],
951 stdin=subprocess.PIPE,
952 stdout=subprocess.PIPE,
953 universal_newlines=True)
954 p.communicate()
955 self.assertEqual(p.returncode, 0)
956
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300957 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300958 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300959 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300960 'import sys,os;' + SETBINARY + textwrap.dedent('''
961 s = sys.stdin.buffer.readline()
962 sys.stdout.buffer.write(s)
963 sys.stdout.buffer.write(b"line2\\r")
964 sys.stderr.buffer.write(b"eline2\\n")
965 s = sys.stdin.buffer.read()
966 sys.stdout.buffer.write(s)
967 sys.stdout.buffer.write(b"line4\\n")
968 sys.stdout.buffer.write(b"line5\\r\\n")
969 sys.stderr.buffer.write(b"eline6\\r")
970 sys.stderr.buffer.write(b"eline7\\r\\nz")
971 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300972 stdin=subprocess.PIPE,
973 stderr=subprocess.PIPE,
974 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300975 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300976 self.addCleanup(p.stdout.close)
977 self.addCleanup(p.stderr.close)
978 (stdout, stderr) = p.communicate("line1\nline3\n")
979 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300980 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300981 # Python debug build push something like "[42442 refs]\n"
982 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300983 # Don't use assertStderrEqual because it strips CR and LF from output.
984 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300985
Andrew Svetlov82860712012-08-19 22:13:41 +0300986 def test_universal_newlines_communicate_encodings(self):
987 # Check that universal newlines mode works for various encodings,
988 # in particular for encodings in the UTF-16 and UTF-32 families.
989 # See issue #15595.
990 #
991 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
992 # without, and UTF-16 and UTF-32.
993 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +0300994 code = ("import sys; "
995 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
996 encoding)
997 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -0700998 # We set stdin to be non-None because, as of this writing,
999 # a different code path is used when the number of pipes is
1000 # zero or one.
1001 popen = subprocess.Popen(args,
1002 stdin=subprocess.PIPE,
1003 stdout=subprocess.PIPE,
1004 encoding=encoding)
1005 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +03001006 self.assertEqual(stdout, '1\n2\n3\n4')
1007
Steve Dower050acae2016-09-06 20:16:17 -07001008 def test_communicate_errors(self):
1009 for errors, expected in [
1010 ('ignore', ''),
1011 ('replace', '\ufffd\ufffd'),
1012 ('surrogateescape', '\udc80\udc80'),
1013 ('backslashreplace', '\\x80\\x80'),
1014 ]:
1015 code = ("import sys; "
1016 r"sys.stdout.buffer.write(b'[\x80\x80]')")
1017 args = [sys.executable, '-c', code]
1018 # We set stdin to be non-None because, as of this writing,
1019 # a different code path is used when the number of pipes is
1020 # zero or one.
1021 popen = subprocess.Popen(args,
1022 stdin=subprocess.PIPE,
1023 stdout=subprocess.PIPE,
1024 encoding='utf-8',
1025 errors=errors)
1026 stdout, stderr = popen.communicate(input='')
1027 self.assertEqual(stdout, '[{}]'.format(expected))
1028
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001029 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +00001030 # Make sure we leak no resources
Victor Stinner937ee9e2018-06-26 02:11:06 +02001031 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +00001032 max_handles = 1026 # too much for most UNIX systems
1033 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +00001034 max_handles = 2050 # too much for (at least some) Windows setups
1035 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001036 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +00001037 try:
1038 for i in range(max_handles):
1039 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001040 tmpfile = os.path.join(tmpdir, support.TESTFN)
1041 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +00001042 except OSError as e:
1043 if e.errno != errno.EMFILE:
1044 raise
1045 break
1046 else:
1047 self.skipTest("failed to reach the file descriptor limit "
1048 "(tried %d)" % max_handles)
1049 # Close a couple of them (should be enough for a subprocess)
1050 for i in range(10):
1051 os.close(handles.pop())
1052 # Loop creating some subprocesses. If one of them leaks some fds,
1053 # the next loop iteration will fail by reaching the max fd limit.
1054 for i in range(15):
1055 p = subprocess.Popen([sys.executable, "-c",
1056 "import sys;"
1057 "sys.stdout.write(sys.stdin.read())"],
1058 stdin=subprocess.PIPE,
1059 stdout=subprocess.PIPE,
1060 stderr=subprocess.PIPE)
1061 data = p.communicate(b"lime")[0]
1062 self.assertEqual(data, b"lime")
1063 finally:
1064 for h in handles:
1065 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001066 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001067
1068 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001069 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
1070 '"a b c" d e')
1071 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
1072 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +00001073 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
1074 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001075 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
1076 'a\\\\\\b "de fg" h')
1077 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
1078 'a\\\\\\"b c d')
1079 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
1080 '"a\\\\b c" d e')
1081 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
1082 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001083 self.assertEqual(subprocess.list2cmdline(['ab', '']),
1084 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001085
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001086 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001087 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +02001088 "import os; os.read(0, 1)"],
1089 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001090 self.addCleanup(p.stdin.close)
1091 self.assertIsNone(p.poll())
1092 os.write(p.stdin.fileno(), b'A')
1093 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001094 # Subsequent invocations should just return the returncode
1095 self.assertEqual(p.poll(), 0)
1096
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001097 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001098 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001099 self.assertEqual(p.wait(), 0)
1100 # Subsequent invocations should just return the returncode
1101 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001102
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001103 def test_wait_timeout(self):
1104 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001105 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001106 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001107 p.wait(timeout=0.0001)
1108 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -04001109 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
1110 # time to start.
1111 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001112
Peter Astrand738131d2004-11-30 21:04:45 +00001113 def test_invalid_bufsize(self):
1114 # an invalid type of the bufsize argument should raise
1115 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001116 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +00001117 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001118
Guido van Rossum46a05a72007-06-07 21:56:45 +00001119 def test_bufsize_is_none(self):
1120 # bufsize=None should be the same as bufsize=0.
1121 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
1122 self.assertEqual(p.wait(), 0)
1123 # Again with keyword arg
1124 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
1125 self.assertEqual(p.wait(), 0)
1126
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001127 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1128 # subprocess may deadlock with bufsize=1, see issue #21332
1129 with subprocess.Popen([sys.executable, "-c", "import sys;"
1130 "sys.stdout.write(sys.stdin.readline());"
1131 "sys.stdout.flush()"],
1132 stdin=subprocess.PIPE,
1133 stdout=subprocess.PIPE,
1134 stderr=subprocess.DEVNULL,
1135 bufsize=1,
1136 universal_newlines=universal_newlines) as p:
1137 p.stdin.write(line) # expect that it flushes the line in text mode
1138 os.close(p.stdin.fileno()) # close it without flushing the buffer
1139 read_line = p.stdout.readline()
Segev Finer4d385172017-08-18 16:18:13 +03001140 with support.SuppressCrashReport():
1141 try:
1142 p.stdin.close()
1143 except OSError:
1144 pass
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001145 p.stdin = None
1146 self.assertEqual(p.returncode, 0)
1147 self.assertEqual(read_line, expected)
1148
1149 def test_bufsize_equal_one_text_mode(self):
1150 # line is flushed in text mode with bufsize=1.
1151 # we should get the full line in return
1152 line = "line\n"
1153 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1154
1155 def test_bufsize_equal_one_binary_mode(self):
1156 # line is not flushed in binary mode with bufsize=1.
1157 # we should get empty response
1158 line = b'line' + os.linesep.encode() # assume ascii-based locale
Alexey Izbysheva2670562018-10-20 03:22:31 +03001159 with self.assertWarnsRegex(RuntimeWarning, 'line buffering'):
1160 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001161
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001162 def test_leaking_fds_on_error(self):
1163 # see bug #5179: Popen leaks file descriptors to PIPEs if
1164 # the child fails to execute; this will eventually exhaust
1165 # the maximum number of open fds. 1024 seems a very common
1166 # value for that limit, but Windows has 2048, so we loop
1167 # 1024 times (each call leaked two fds).
1168 for i in range(1024):
Victor Stinnerb31206a2018-01-25 19:06:05 +01001169 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02001170 subprocess.Popen(NONEXISTING_CMD,
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001171 stdout=subprocess.PIPE,
1172 stderr=subprocess.PIPE)
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001173
Victor Stinner9a83f652017-08-21 23:51:31 +02001174 def test_nonexisting_with_pipes(self):
1175 # bpo-30121: Popen with pipes must close properly pipes on error.
1176 # Previously, os.close() was called with a Windows handle which is not
1177 # a valid file descriptor.
1178 #
1179 # Run the test in a subprocess to control how the CRT reports errors
1180 # and to get stderr content.
1181 try:
1182 import msvcrt
1183 msvcrt.CrtSetReportMode
1184 except (AttributeError, ImportError):
1185 self.skipTest("need msvcrt.CrtSetReportMode")
1186
1187 code = textwrap.dedent(f"""
1188 import msvcrt
1189 import subprocess
1190
1191 cmd = {NONEXISTING_CMD!r}
1192
1193 for report_type in [msvcrt.CRT_WARN,
1194 msvcrt.CRT_ERROR,
1195 msvcrt.CRT_ASSERT]:
1196 msvcrt.CrtSetReportMode(report_type, msvcrt.CRTDBG_MODE_FILE)
1197 msvcrt.CrtSetReportFile(report_type, msvcrt.CRTDBG_FILE_STDERR)
1198
1199 try:
Zachary Ware55376462018-02-19 14:02:38 -06001200 subprocess.Popen(cmd,
Victor Stinner9a83f652017-08-21 23:51:31 +02001201 stdout=subprocess.PIPE,
1202 stderr=subprocess.PIPE)
1203 except OSError:
1204 pass
1205 """)
1206 cmd = [sys.executable, "-c", code]
1207 proc = subprocess.Popen(cmd,
1208 stderr=subprocess.PIPE,
1209 universal_newlines=True)
1210 with proc:
1211 stderr = proc.communicate()[1]
1212 self.assertEqual(stderr, "")
1213 self.assertEqual(proc.returncode, 0)
1214
Antoine Pitroua8392712013-08-30 23:38:13 +02001215 def test_double_close_on_error(self):
1216 # Issue #18851
1217 fds = []
1218 def open_fds():
1219 for i in range(20):
1220 fds.extend(os.pipe())
1221 time.sleep(0.001)
1222 t = threading.Thread(target=open_fds)
1223 t.start()
1224 try:
1225 with self.assertRaises(EnvironmentError):
Victor Stinner9a83f652017-08-21 23:51:31 +02001226 subprocess.Popen(NONEXISTING_CMD,
Antoine Pitroua8392712013-08-30 23:38:13 +02001227 stdin=subprocess.PIPE,
1228 stdout=subprocess.PIPE,
1229 stderr=subprocess.PIPE)
1230 finally:
1231 t.join()
1232 exc = None
1233 for fd in fds:
1234 # If a double close occurred, some of those fds will
1235 # already have been closed by mistake, and os.close()
1236 # here will raise.
1237 try:
1238 os.close(fd)
1239 except OSError as e:
1240 exc = e
1241 if exc is not None:
1242 raise exc
1243
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001244 def test_threadsafe_wait(self):
1245 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1246 proc = subprocess.Popen([sys.executable, '-c',
1247 'import time; time.sleep(12)'])
1248 self.assertEqual(proc.returncode, None)
1249 results = []
1250
1251 def kill_proc_timer_thread():
1252 results.append(('thread-start-poll-result', proc.poll()))
1253 # terminate it from the thread and wait for the result.
1254 proc.kill()
1255 proc.wait()
1256 results.append(('thread-after-kill-and-wait', proc.returncode))
1257 # this wait should be a no-op given the above.
1258 proc.wait()
1259 results.append(('thread-after-second-wait', proc.returncode))
1260
1261 # This is a timing sensitive test, the failure mode is
1262 # triggered when both the main thread and this thread are in
1263 # the wait() call at once. The delay here is to allow the
1264 # main thread to most likely be blocked in its wait() call.
1265 t = threading.Timer(0.2, kill_proc_timer_thread)
1266 t.start()
1267
Victor Stinner937ee9e2018-06-26 02:11:06 +02001268 if mswindows:
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001269 expected_errorcode = 1
1270 else:
1271 # Should be -9 because of the proc.kill() from the thread.
1272 expected_errorcode = -9
1273
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001274 # Wait for the process to finish; the thread should kill it
1275 # long before it finishes on its own. Supplying a timeout
1276 # triggers a different code path for better coverage.
1277 proc.wait(timeout=20)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001278 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001279 msg="unexpected result in wait from main thread")
1280
1281 # This should be a no-op with no change in returncode.
1282 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001283 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001284 msg="unexpected result in second main wait.")
1285
1286 t.join()
1287 # Ensure that all of the thread results are as expected.
1288 # When a race condition occurs in wait(), the returncode could
1289 # be set by the wrong thread that doesn't actually have it
1290 # leading to an incorrect value.
1291 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001292 ('thread-after-kill-and-wait', expected_errorcode),
1293 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001294 results)
1295
Victor Stinnerb3693582010-05-21 20:13:12 +00001296 def test_issue8780(self):
1297 # Ensure that stdout is inherited from the parent
1298 # if stdout=PIPE is not used
1299 code = ';'.join((
1300 'import subprocess, sys',
1301 'retcode = subprocess.call('
1302 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1303 'assert retcode == 0'))
1304 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001305 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001306
Tim Goldenaf5ac392010-08-06 13:03:56 +00001307 def test_handles_closed_on_exception(self):
1308 # If CreateProcess exits with an error, ensure the
1309 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001310 ifhandle, ifname = tempfile.mkstemp()
1311 ofhandle, ofname = tempfile.mkstemp()
1312 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001313 try:
1314 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1315 stderr=efhandle)
1316 except OSError:
1317 os.close(ifhandle)
1318 os.remove(ifname)
1319 os.close(ofhandle)
1320 os.remove(ofname)
1321 os.close(efhandle)
1322 os.remove(efname)
1323 self.assertFalse(os.path.exists(ifname))
1324 self.assertFalse(os.path.exists(ofname))
1325 self.assertFalse(os.path.exists(efname))
1326
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001327 def test_communicate_epipe(self):
1328 # Issue 10963: communicate() should hide EPIPE
1329 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1330 stdin=subprocess.PIPE,
1331 stdout=subprocess.PIPE,
1332 stderr=subprocess.PIPE)
1333 self.addCleanup(p.stdout.close)
1334 self.addCleanup(p.stderr.close)
1335 self.addCleanup(p.stdin.close)
1336 p.communicate(b"x" * 2**20)
1337
1338 def test_communicate_epipe_only_stdin(self):
1339 # Issue 10963: communicate() should hide EPIPE
1340 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1341 stdin=subprocess.PIPE)
1342 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001343 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001344 p.communicate(b"x" * 2**20)
1345
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001346 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1347 "Requires signal.SIGUSR1")
1348 @unittest.skipUnless(hasattr(os, 'kill'),
1349 "Requires os.kill")
1350 @unittest.skipUnless(hasattr(os, 'getppid'),
1351 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001352 def test_communicate_eintr(self):
1353 # Issue #12493: communicate() should handle EINTR
1354 def handler(signum, frame):
1355 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001356 old_handler = signal.signal(signal.SIGUSR1, handler)
1357 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001358
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001359 args = [sys.executable, "-c",
1360 'import os, signal;'
1361 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001362 for stream in ('stdout', 'stderr'):
1363 kw = {stream: subprocess.PIPE}
1364 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001365 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001366 process.communicate()
1367
Tim Peterse718f612004-10-12 21:51:32 +00001368
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001369 # This test is Linux-ish specific for simplicity to at least have
1370 # some coverage. It is not a platform specific bug.
1371 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1372 "Linux specific")
1373 def test_failed_child_execute_fd_leak(self):
1374 """Test for the fork() failure fd leak reported in issue16327."""
1375 fd_directory = '/proc/%d/fd' % os.getpid()
1376 fds_before_popen = os.listdir(fd_directory)
1377 with self.assertRaises(PopenTestException):
1378 PopenExecuteChildRaises(
1379 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
1380 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1381
1382 # NOTE: This test doesn't verify that the real _execute_child
1383 # does not close the file descriptors itself on the way out
1384 # during an exception. Code inspection has confirmed that.
1385
1386 fds_after_exception = os.listdir(fd_directory)
1387 self.assertEqual(fds_before_popen, fds_after_exception)
1388
Victor Stinner937ee9e2018-06-26 02:11:06 +02001389 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001390 def test_file_not_found_includes_filename(self):
1391 with self.assertRaises(FileNotFoundError) as c:
1392 subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args'])
1393 self.assertEqual(c.exception.filename, '/opt/nonexistent_binary')
1394
Victor Stinner937ee9e2018-06-26 02:11:06 +02001395 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001396 def test_file_not_found_with_bad_cwd(self):
1397 with self.assertRaises(FileNotFoundError) as c:
1398 subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory')
1399 self.assertEqual(c.exception.filename, '/some/nonexistent/directory')
1400
Gregory P. Smith6e730002015-04-14 16:14:25 -07001401
1402class RunFuncTestCase(BaseTestCase):
1403 def run_python(self, code, **kwargs):
1404 """Run Python code in a subprocess using subprocess.run"""
1405 argv = [sys.executable, "-c", code]
1406 return subprocess.run(argv, **kwargs)
1407
1408 def test_returncode(self):
1409 # call() function with sequence argument
1410 cp = self.run_python("import sys; sys.exit(47)")
1411 self.assertEqual(cp.returncode, 47)
1412 with self.assertRaises(subprocess.CalledProcessError):
1413 cp.check_returncode()
1414
1415 def test_check(self):
1416 with self.assertRaises(subprocess.CalledProcessError) as c:
1417 self.run_python("import sys; sys.exit(47)", check=True)
1418 self.assertEqual(c.exception.returncode, 47)
1419
1420 def test_check_zero(self):
1421 # check_returncode shouldn't raise when returncode is zero
1422 cp = self.run_python("import sys; sys.exit(0)", check=True)
1423 self.assertEqual(cp.returncode, 0)
1424
1425 def test_timeout(self):
1426 # run() function with timeout argument; we want to test that the child
1427 # process gets killed when the timeout expires. If the child isn't
1428 # killed, this call will deadlock since subprocess.run waits for the
1429 # child.
1430 with self.assertRaises(subprocess.TimeoutExpired):
1431 self.run_python("while True: pass", timeout=0.0001)
1432
1433 def test_capture_stdout(self):
1434 # capture stdout with zero return code
1435 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1436 self.assertIn(b'BDFL', cp.stdout)
1437
1438 def test_capture_stderr(self):
1439 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1440 stderr=subprocess.PIPE)
1441 self.assertIn(b'BDFL', cp.stderr)
1442
1443 def test_check_output_stdin_arg(self):
1444 # run() can be called with stdin set to a file
1445 tf = tempfile.TemporaryFile()
1446 self.addCleanup(tf.close)
1447 tf.write(b'pear')
1448 tf.seek(0)
1449 cp = self.run_python(
1450 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1451 stdin=tf, stdout=subprocess.PIPE)
1452 self.assertIn(b'PEAR', cp.stdout)
1453
1454 def test_check_output_input_arg(self):
1455 # check_output() can be called with input set to a string
1456 cp = self.run_python(
1457 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1458 input=b'pear', stdout=subprocess.PIPE)
1459 self.assertIn(b'PEAR', cp.stdout)
1460
1461 def test_check_output_stdin_with_input_arg(self):
1462 # run() refuses to accept 'stdin' with 'input'
1463 tf = tempfile.TemporaryFile()
1464 self.addCleanup(tf.close)
1465 tf.write(b'pear')
1466 tf.seek(0)
1467 with self.assertRaises(ValueError,
1468 msg="Expected ValueError when stdin and input args supplied.") as c:
1469 output = self.run_python("print('will not be run')",
1470 stdin=tf, input=b'hare')
1471 self.assertIn('stdin', c.exception.args[0])
1472 self.assertIn('input', c.exception.args[0])
1473
1474 def test_check_output_timeout(self):
1475 with self.assertRaises(subprocess.TimeoutExpired) as c:
1476 cp = self.run_python((
1477 "import sys, time\n"
1478 "sys.stdout.write('BDFL')\n"
1479 "sys.stdout.flush()\n"
1480 "time.sleep(3600)"),
1481 # Some heavily loaded buildbots (sparc Debian 3.x) require
1482 # this much time to start and print.
1483 timeout=3, stdout=subprocess.PIPE)
1484 self.assertEqual(c.exception.output, b'BDFL')
1485 # output is aliased to stdout
1486 self.assertEqual(c.exception.stdout, b'BDFL')
1487
1488 def test_run_kwargs(self):
1489 newenv = os.environ.copy()
1490 newenv["FRUIT"] = "banana"
1491 cp = self.run_python(('import sys, os;'
1492 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1493 env=newenv)
1494 self.assertEqual(cp.returncode, 33)
1495
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001496 def test_run_with_pathlike_path(self):
1497 # bpo-31961: test run(pathlike_object)
1498 # the name of a command that can be run without
1499 # any argumenets that exit fast
1500 prog = 'tree.com' if mswindows else 'ls'
1501 path = shutil.which(prog)
1502 if path is None:
1503 self.skipTest(f'{prog} required for this test')
1504 path = FakePath(path)
1505 res = subprocess.run(path, stdout=subprocess.DEVNULL)
1506 self.assertEqual(res.returncode, 0)
1507 with self.assertRaises(TypeError):
1508 subprocess.run(path, stdout=subprocess.DEVNULL, shell=True)
1509
1510 def test_run_with_bytes_path_and_arguments(self):
1511 # bpo-31961: test run([bytes_object, b'additional arguments'])
1512 path = os.fsencode(sys.executable)
1513 args = [path, '-c', b'import sys; sys.exit(57)']
1514 res = subprocess.run(args)
1515 self.assertEqual(res.returncode, 57)
1516
1517 def test_run_with_pathlike_path_and_arguments(self):
1518 # bpo-31961: test run([pathlike_object, 'additional arguments'])
1519 path = FakePath(sys.executable)
1520 args = [path, '-c', 'import sys; sys.exit(57)']
1521 res = subprocess.run(args)
1522 self.assertEqual(res.returncode, 57)
1523
Bo Baylesce0f33d2018-01-30 00:40:39 -06001524 def test_capture_output(self):
1525 cp = self.run_python(("import sys;"
1526 "sys.stdout.write('BDFL'); "
1527 "sys.stderr.write('FLUFL')"),
1528 capture_output=True)
1529 self.assertIn(b'BDFL', cp.stdout)
1530 self.assertIn(b'FLUFL', cp.stderr)
1531
1532 def test_stdout_with_capture_output_arg(self):
1533 # run() refuses to accept 'stdout' with 'capture_output'
1534 tf = tempfile.TemporaryFile()
1535 self.addCleanup(tf.close)
1536 with self.assertRaises(ValueError,
1537 msg=("Expected ValueError when stdout and capture_output "
1538 "args supplied.")) as c:
1539 output = self.run_python("print('will not be run')",
1540 capture_output=True, stdout=tf)
1541 self.assertIn('stdout', c.exception.args[0])
1542 self.assertIn('capture_output', c.exception.args[0])
1543
1544 def test_stderr_with_capture_output_arg(self):
1545 # run() refuses to accept 'stderr' with 'capture_output'
1546 tf = tempfile.TemporaryFile()
1547 self.addCleanup(tf.close)
1548 with self.assertRaises(ValueError,
1549 msg=("Expected ValueError when stderr and capture_output "
1550 "args supplied.")) as c:
1551 output = self.run_python("print('will not be run')",
1552 capture_output=True, stderr=tf)
1553 self.assertIn('stderr', c.exception.args[0])
1554 self.assertIn('capture_output', c.exception.args[0])
1555
Gregory P. Smith6e730002015-04-14 16:14:25 -07001556
Victor Stinner937ee9e2018-06-26 02:11:06 +02001557@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001558class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001559
Gregory P. Smith5591b022012-10-10 03:34:47 -07001560 def setUp(self):
1561 super().setUp()
1562 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1563
1564 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001565 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001566 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001567 except OSError as e:
1568 # This avoids hard coding the errno value or the OS perror()
1569 # string and instead capture the exception that we want to see
1570 # below for comparison.
1571 desired_exception = e
1572 else:
Martin Pantereb995702016-07-28 01:11:04 +00001573 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001574 self._nonexistent_dir)
1575 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001576
Gregory P. Smith5591b022012-10-10 03:34:47 -07001577 def test_exception_cwd(self):
1578 """Test error in the child raised in the parent for a bad cwd."""
1579 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001580 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001581 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001582 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001583 except OSError as e:
1584 # Test that the child process chdir failure actually makes
1585 # it up to the parent process as the correct exception.
1586 self.assertEqual(desired_exception.errno, e.errno)
1587 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001588 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001589 else:
1590 self.fail("Expected OSError: %s" % desired_exception)
1591
Gregory P. Smith5591b022012-10-10 03:34:47 -07001592 def test_exception_bad_executable(self):
1593 """Test error in the child raised in the parent for a bad executable."""
1594 desired_exception = self._get_chdir_exception()
1595 try:
1596 p = subprocess.Popen([sys.executable, "-c", ""],
1597 executable=self._nonexistent_dir)
1598 except OSError as e:
1599 # Test that the child process exec failure actually makes
1600 # it up to the parent process as the correct exception.
1601 self.assertEqual(desired_exception.errno, e.errno)
1602 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001603 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001604 else:
1605 self.fail("Expected OSError: %s" % desired_exception)
1606
1607 def test_exception_bad_args_0(self):
1608 """Test error in the child raised in the parent for a bad args[0]."""
1609 desired_exception = self._get_chdir_exception()
1610 try:
1611 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1612 except OSError as e:
1613 # Test that the child process exec failure actually makes
1614 # it up to the parent process as the correct exception.
1615 self.assertEqual(desired_exception.errno, e.errno)
1616 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001617 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001618 else:
1619 self.fail("Expected OSError: %s" % desired_exception)
1620
Ammar Askar3fc499b2017-09-06 02:41:30 -04001621 # We mock the __del__ method for Popen in the next two tests
1622 # because it does cleanup based on the pid returned by fork_exec
1623 # along with issuing a resource warning if it still exists. Since
1624 # we don't actually spawn a process in these tests we can forego
1625 # the destructor. An alternative would be to set _child_created to
1626 # False before the destructor is called but there is no easy way
1627 # to do that
1628 class PopenNoDestructor(subprocess.Popen):
1629 def __del__(self):
1630 pass
1631
1632 @mock.patch("subprocess._posixsubprocess.fork_exec")
1633 def test_exception_errpipe_normal(self, fork_exec):
1634 """Test error passing done through errpipe_write in the good case"""
1635 def proper_error(*args):
1636 errpipe_write = args[13]
1637 # Write the hex for the error code EISDIR: 'is a directory'
1638 err_code = '{:x}'.format(errno.EISDIR).encode()
1639 os.write(errpipe_write, b"OSError:" + err_code + b":")
1640 return 0
1641
1642 fork_exec.side_effect = proper_error
1643
Victor Stinner11045c92017-10-05 06:32:53 -07001644 with mock.patch("subprocess.os.waitpid",
1645 side_effect=ChildProcessError):
1646 with self.assertRaises(IsADirectoryError):
1647 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001648
1649 @mock.patch("subprocess._posixsubprocess.fork_exec")
1650 def test_exception_errpipe_bad_data(self, fork_exec):
1651 """Test error passing done through errpipe_write where its not
1652 in the expected format"""
1653 error_data = b"\xFF\x00\xDE\xAD"
1654 def bad_error(*args):
1655 errpipe_write = args[13]
1656 # Anything can be in the pipe, no assumptions should
1657 # be made about its encoding, so we'll write some
1658 # arbitrary hex bytes to test it out
1659 os.write(errpipe_write, error_data)
1660 return 0
1661
1662 fork_exec.side_effect = bad_error
1663
Victor Stinner11045c92017-10-05 06:32:53 -07001664 with mock.patch("subprocess.os.waitpid",
1665 side_effect=ChildProcessError):
1666 with self.assertRaises(subprocess.SubprocessError) as e:
1667 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001668
1669 self.assertIn(repr(error_data), str(e.exception))
1670
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001671 @unittest.skipIf(not os.path.exists('/proc/self/status'),
1672 "need /proc/self/status")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001673 def test_restore_signals(self):
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001674 # Blindly assume that cat exists on systems with /proc/self/status...
1675 default_proc_status = subprocess.check_output(
1676 ['cat', '/proc/self/status'],
1677 restore_signals=False)
1678 for line in default_proc_status.splitlines():
1679 if line.startswith(b'SigIgn'):
1680 default_sig_ign_mask = line
1681 break
1682 else:
1683 self.skipTest("SigIgn not found in /proc/self/status.")
1684 restored_proc_status = subprocess.check_output(
1685 ['cat', '/proc/self/status'],
1686 restore_signals=True)
1687 for line in restored_proc_status.splitlines():
1688 if line.startswith(b'SigIgn'):
1689 restored_sig_ign_mask = line
1690 break
1691 self.assertNotEqual(default_sig_ign_mask, restored_sig_ign_mask,
1692 msg="restore_signals=True should've unblocked "
1693 "SIGPIPE and friends.")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001694
1695 def test_start_new_session(self):
1696 # For code coverage of calling setsid(). We don't care if we get an
1697 # EPERM error from it depending on the test execution environment, that
1698 # still indicates that it was called.
1699 try:
1700 output = subprocess.check_output(
Miss Islington (bot)e696b152019-06-14 10:49:22 -07001701 [sys.executable, "-c", "import os; print(os.getsid(0))"],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001702 start_new_session=True)
1703 except OSError as e:
1704 if e.errno != errno.EPERM:
1705 raise
1706 else:
Miss Islington (bot)e696b152019-06-14 10:49:22 -07001707 parent_sid = os.getsid(0)
1708 child_sid = int(output)
1709 self.assertNotEqual(parent_sid, child_sid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001710
1711 def test_run_abort(self):
1712 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001713 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001714 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001715 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001716 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001717 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001718
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001719 def test_CalledProcessError_str_signal(self):
1720 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
1721 error_string = str(err)
1722 # We're relying on the repr() of the signal.Signals intenum to provide
1723 # the word signal, the signal name and the numeric value.
1724 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00001725 # We're not being specific about the signal name as some signals have
1726 # multiple names and which name is revealed can vary.
1727 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001728 self.assertIn(str(signal.SIGABRT), error_string)
1729
1730 def test_CalledProcessError_str_unknown_signal(self):
1731 err = subprocess.CalledProcessError(-9876543, "fake cmd")
1732 error_string = str(err)
1733 self.assertIn("unknown signal 9876543.", error_string)
1734
1735 def test_CalledProcessError_str_non_zero(self):
1736 err = subprocess.CalledProcessError(2, "fake cmd")
1737 error_string = str(err)
1738 self.assertIn("non-zero exit status 2.", error_string)
1739
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001740 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001741 # DISCLAIMER: Setting environment variables is *not* a good use
1742 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001743 p = subprocess.Popen([sys.executable, "-c",
1744 'import sys,os;'
1745 'sys.stdout.write(os.getenv("FRUIT"))'],
1746 stdout=subprocess.PIPE,
1747 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02001748 with p:
1749 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001750
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001751 def test_preexec_exception(self):
1752 def raise_it():
1753 raise ValueError("What if two swallows carried a coconut?")
1754 try:
1755 p = subprocess.Popen([sys.executable, "-c", ""],
1756 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001757 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001758 self.assertTrue(
1759 subprocess._posixsubprocess,
1760 "Expected a ValueError from the preexec_fn")
1761 except ValueError as e:
1762 self.assertIn("coconut", e.args[0])
1763 else:
1764 self.fail("Exception raised by preexec_fn did not make it "
1765 "to the parent process.")
1766
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001767 class _TestExecuteChildPopen(subprocess.Popen):
1768 """Used to test behavior at the end of _execute_child."""
1769 def __init__(self, testcase, *args, **kwargs):
1770 self._testcase = testcase
1771 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001772
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001773 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001774 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001775 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001776 finally:
1777 # Open a bunch of file descriptors and verify that
1778 # none of them are the same as the ones the Popen
1779 # instance is using for stdin/stdout/stderr.
1780 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1781 for _ in range(8)]
1782 try:
1783 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001784 self._testcase.assertNotIn(
1785 fd, (self.stdin.fileno(), self.stdout.fileno(),
1786 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001787 msg="At least one fd was closed early.")
1788 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01001789 for fd in devzero_fds:
1790 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001791
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001792 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1793 def test_preexec_errpipe_does_not_double_close_pipes(self):
1794 """Issue16140: Don't double close pipes on preexec error."""
1795
1796 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08001797 raise subprocess.SubprocessError(
1798 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001799
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08001800 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001801 self._TestExecuteChildPopen(
1802 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001803 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1804 stderr=subprocess.PIPE, preexec_fn=raise_it)
1805
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001806 def test_preexec_gc_module_failure(self):
1807 # This tests the code that disables garbage collection if the child
1808 # process will execute any Python.
1809 def raise_runtime_error():
1810 raise RuntimeError("this shouldn't escape")
1811 enabled = gc.isenabled()
1812 orig_gc_disable = gc.disable
1813 orig_gc_isenabled = gc.isenabled
1814 try:
1815 gc.disable()
1816 self.assertFalse(gc.isenabled())
1817 subprocess.call([sys.executable, '-c', ''],
1818 preexec_fn=lambda: None)
1819 self.assertFalse(gc.isenabled(),
1820 "Popen enabled gc when it shouldn't.")
1821
1822 gc.enable()
1823 self.assertTrue(gc.isenabled())
1824 subprocess.call([sys.executable, '-c', ''],
1825 preexec_fn=lambda: None)
1826 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1827
1828 gc.disable = raise_runtime_error
1829 self.assertRaises(RuntimeError, subprocess.Popen,
1830 [sys.executable, '-c', ''],
1831 preexec_fn=lambda: None)
1832
1833 del gc.isenabled # force an AttributeError
1834 self.assertRaises(AttributeError, subprocess.Popen,
1835 [sys.executable, '-c', ''],
1836 preexec_fn=lambda: None)
1837 finally:
1838 gc.disable = orig_gc_disable
1839 gc.isenabled = orig_gc_isenabled
1840 if not enabled:
1841 gc.disable()
1842
Martin Panterf7fdbda2015-12-05 09:51:52 +00001843 @unittest.skipIf(
1844 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00001845 def test_preexec_fork_failure(self):
1846 # The internal code did not preserve the previous exception when
1847 # re-enabling garbage collection
1848 try:
1849 from resource import getrlimit, setrlimit, RLIMIT_NPROC
1850 except ImportError as err:
1851 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
1852 limits = getrlimit(RLIMIT_NPROC)
1853 [_, hard] = limits
1854 setrlimit(RLIMIT_NPROC, (0, hard))
1855 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00001856 try:
Martin Panterafdd5132015-11-30 02:21:41 +00001857 subprocess.call([sys.executable, '-c', ''],
1858 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00001859 except BlockingIOError:
1860 # Forking should raise EAGAIN, translated to BlockingIOError
1861 pass
1862 else:
1863 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00001864
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001865 def test_args_string(self):
1866 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03001867 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001868 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001869 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001870 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001871 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1872 sys.executable)
1873 os.chmod(fname, 0o700)
1874 p = subprocess.Popen(fname)
1875 p.wait()
1876 os.remove(fname)
1877 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001878
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001879 def test_invalid_args(self):
1880 # invalid arguments should raise ValueError
1881 self.assertRaises(ValueError, subprocess.call,
1882 [sys.executable, "-c",
1883 "import sys; sys.exit(47)"],
1884 startupinfo=47)
1885 self.assertRaises(ValueError, subprocess.call,
1886 [sys.executable, "-c",
1887 "import sys; sys.exit(47)"],
1888 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001889
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001890 def test_shell_sequence(self):
1891 # Run command through the shell (sequence)
1892 newenv = os.environ.copy()
1893 newenv["FRUIT"] = "apple"
1894 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1895 stdout=subprocess.PIPE,
1896 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001897 with p:
1898 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001899
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001900 def test_shell_string(self):
1901 # Run command through the shell (string)
1902 newenv = os.environ.copy()
1903 newenv["FRUIT"] = "apple"
1904 p = subprocess.Popen("echo $FRUIT", shell=1,
1905 stdout=subprocess.PIPE,
1906 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001907 with p:
1908 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001909
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001910 def test_call_string(self):
1911 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03001912 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001913 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001914 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001915 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001916 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1917 sys.executable)
1918 os.chmod(fname, 0o700)
1919 rc = subprocess.call(fname)
1920 os.remove(fname)
1921 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001922
Stefan Krah9542cc62010-07-19 14:20:53 +00001923 def test_specific_shell(self):
1924 # Issue #9265: Incorrect name passed as arg[0].
1925 shells = []
1926 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1927 for name in ['bash', 'ksh']:
1928 sh = os.path.join(prefix, name)
1929 if os.path.isfile(sh):
1930 shells.append(sh)
1931 if not shells: # Will probably work for any shell but csh.
1932 self.skipTest("bash or ksh required for this test")
1933 sh = '/bin/sh'
1934 if os.path.isfile(sh) and not os.path.islink(sh):
1935 # Test will fail if /bin/sh is a symlink to csh.
1936 shells.append(sh)
1937 for sh in shells:
1938 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1939 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02001940 with p:
1941 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00001942
Florent Xicluna4886d242010-03-08 13:27:26 +00001943 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001944 # Do not inherit file handles from the parent.
1945 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07001946 # Also set the SIGINT handler to the default to make sure it's not
1947 # being ignored (some tests rely on that.)
1948 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
1949 try:
1950 p = subprocess.Popen([sys.executable, "-c", """if 1:
1951 import sys, time
1952 sys.stdout.write('x\\n')
1953 sys.stdout.flush()
1954 time.sleep(30)
1955 """],
1956 close_fds=True,
1957 stdin=subprocess.PIPE,
1958 stdout=subprocess.PIPE,
1959 stderr=subprocess.PIPE)
1960 finally:
1961 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001962 # Wait for the interpreter to be completely initialized before
1963 # sending any signal.
1964 p.stdout.read(1)
1965 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001966 return p
1967
Charles-François Natali53221e32013-01-12 16:52:20 +01001968 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1969 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001970 def _kill_dead_process(self, method, *args):
1971 # Do not inherit file handles from the parent.
1972 # It should fix failures on some platforms.
1973 p = subprocess.Popen([sys.executable, "-c", """if 1:
1974 import sys, time
1975 sys.stdout.write('x\\n')
1976 sys.stdout.flush()
1977 """],
1978 close_fds=True,
1979 stdin=subprocess.PIPE,
1980 stdout=subprocess.PIPE,
1981 stderr=subprocess.PIPE)
1982 # Wait for the interpreter to be completely initialized before
1983 # sending any signal.
1984 p.stdout.read(1)
1985 # The process should end after this
1986 time.sleep(1)
1987 # This shouldn't raise even though the child is now dead
1988 getattr(p, method)(*args)
1989 p.communicate()
1990
Florent Xicluna4886d242010-03-08 13:27:26 +00001991 def test_send_signal(self):
1992 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001993 _, stderr = p.communicate()
1994 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001995 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001996
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001997 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001998 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001999 _, stderr = p.communicate()
2000 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002001 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00002002
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002003 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002004 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00002005 _, stderr = p.communicate()
2006 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002007 self.assertEqual(p.wait(), -signal.SIGTERM)
2008
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002009 def test_send_signal_dead(self):
2010 # Sending a signal to a dead process
2011 self._kill_dead_process('send_signal', signal.SIGINT)
2012
2013 def test_kill_dead(self):
2014 # Killing a dead process
2015 self._kill_dead_process('kill')
2016
2017 def test_terminate_dead(self):
2018 # Terminating a dead process
2019 self._kill_dead_process('terminate')
2020
Victor Stinnerdaf45552013-08-28 00:53:59 +02002021 def _save_fds(self, save_fds):
2022 fds = []
2023 for fd in save_fds:
2024 inheritable = os.get_inheritable(fd)
2025 saved = os.dup(fd)
2026 fds.append((fd, saved, inheritable))
2027 return fds
2028
2029 def _restore_fds(self, fds):
2030 for fd, saved, inheritable in fds:
2031 os.dup2(saved, fd, inheritable=inheritable)
2032 os.close(saved)
2033
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002034 def check_close_std_fds(self, fds):
2035 # Issue #9905: test that subprocess pipes still work properly with
2036 # some standard fds closed
2037 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02002038 saved_fds = self._save_fds(fds)
2039 for fd, saved, inheritable in saved_fds:
2040 if fd == 0:
2041 stdin = saved
2042 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002043 try:
2044 for fd in fds:
2045 os.close(fd)
2046 out, err = subprocess.Popen([sys.executable, "-c",
2047 'import sys;'
2048 'sys.stdout.write("apple");'
2049 'sys.stdout.flush();'
2050 'sys.stderr.write("orange")'],
2051 stdin=stdin,
2052 stdout=subprocess.PIPE,
2053 stderr=subprocess.PIPE).communicate()
2054 err = support.strip_python_stderr(err)
2055 self.assertEqual((out, err), (b'apple', b'orange'))
2056 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002057 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002058
2059 def test_close_fd_0(self):
2060 self.check_close_std_fds([0])
2061
2062 def test_close_fd_1(self):
2063 self.check_close_std_fds([1])
2064
2065 def test_close_fd_2(self):
2066 self.check_close_std_fds([2])
2067
2068 def test_close_fds_0_1(self):
2069 self.check_close_std_fds([0, 1])
2070
2071 def test_close_fds_0_2(self):
2072 self.check_close_std_fds([0, 2])
2073
2074 def test_close_fds_1_2(self):
2075 self.check_close_std_fds([1, 2])
2076
2077 def test_close_fds_0_1_2(self):
2078 # Issue #10806: test that subprocess pipes still work properly with
2079 # all standard fds closed.
2080 self.check_close_std_fds([0, 1, 2])
2081
Gregory P. Smith53dd8162013-12-01 16:03:24 -08002082 def test_small_errpipe_write_fd(self):
2083 """Issue #15798: Popen should work when stdio fds are available."""
2084 new_stdin = os.dup(0)
2085 new_stdout = os.dup(1)
2086 try:
2087 os.close(0)
2088 os.close(1)
2089
2090 # Side test: if errpipe_write fails to have its CLOEXEC
2091 # flag set this should cause the parent to think the exec
2092 # failed. Extremely unlikely: everyone supports CLOEXEC.
2093 subprocess.Popen([
2094 sys.executable, "-c",
2095 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
2096 finally:
2097 # Restore original stdin and stdout
2098 os.dup2(new_stdin, 0)
2099 os.dup2(new_stdout, 1)
2100 os.close(new_stdin)
2101 os.close(new_stdout)
2102
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002103 def test_remapping_std_fds(self):
2104 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002105 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002106 try:
2107 temp_fds = [fd for fd, fname in temps]
2108
2109 # unlink the files -- we won't need to reopen them
2110 for fd, fname in temps:
2111 os.unlink(fname)
2112
2113 # write some data to what will become stdin, and rewind
2114 os.write(temp_fds[1], b"STDIN")
2115 os.lseek(temp_fds[1], 0, 0)
2116
2117 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02002118 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002119 try:
2120 # duplicate the file objects over the standard fd's
2121 for fd, temp_fd in enumerate(temp_fds):
2122 os.dup2(temp_fd, fd)
2123
2124 # now use those files in the "wrong" order, so that subprocess
2125 # has to rearrange them in the child
2126 p = subprocess.Popen([sys.executable, "-c",
2127 'import sys; got = sys.stdin.read();'
2128 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2129 stdin=temp_fds[1],
2130 stdout=temp_fds[2],
2131 stderr=temp_fds[0])
2132 p.wait()
2133 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002134 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002135
2136 for fd in temp_fds:
2137 os.lseek(fd, 0, 0)
2138
2139 out = os.read(temp_fds[2], 1024)
2140 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
2141 self.assertEqual(out, b"got STDIN")
2142 self.assertEqual(err, b"err")
2143
2144 finally:
2145 for fd in temp_fds:
2146 os.close(fd)
2147
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002148 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
2149 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002150 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002151 temp_fds = [fd for fd, fname in temps]
2152 try:
2153 # unlink the files -- we won't need to reopen them
2154 for fd, fname in temps:
2155 os.unlink(fname)
2156
2157 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02002158 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002159 try:
2160 # duplicate the temp files over the standard fd's 0, 1, 2
2161 for fd, temp_fd in enumerate(temp_fds):
2162 os.dup2(temp_fd, fd)
2163
2164 # write some data to what will become stdin, and rewind
2165 os.write(stdin_no, b"STDIN")
2166 os.lseek(stdin_no, 0, 0)
2167
2168 # now use those files in the given order, so that subprocess
2169 # has to rearrange them in the child
2170 p = subprocess.Popen([sys.executable, "-c",
2171 'import sys; got = sys.stdin.read();'
2172 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2173 stdin=stdin_no,
2174 stdout=stdout_no,
2175 stderr=stderr_no)
2176 p.wait()
2177
2178 for fd in temp_fds:
2179 os.lseek(fd, 0, 0)
2180
2181 out = os.read(stdout_no, 1024)
2182 err = support.strip_python_stderr(os.read(stderr_no, 1024))
2183 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002184 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002185
2186 self.assertEqual(out, b"got STDIN")
2187 self.assertEqual(err, b"err")
2188
2189 finally:
2190 for fd in temp_fds:
2191 os.close(fd)
2192
2193 # When duping fds, if there arises a situation where one of the fds is
2194 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
2195 # This tests all combinations of this.
2196 def test_swap_fds(self):
2197 self.check_swap_fds(0, 1, 2)
2198 self.check_swap_fds(0, 2, 1)
2199 self.check_swap_fds(1, 0, 2)
2200 self.check_swap_fds(1, 2, 0)
2201 self.check_swap_fds(2, 0, 1)
2202 self.check_swap_fds(2, 1, 0)
2203
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +03002204 def _check_swap_std_fds_with_one_closed(self, from_fds, to_fds):
2205 saved_fds = self._save_fds(range(3))
2206 try:
2207 for from_fd in from_fds:
2208 with tempfile.TemporaryFile() as f:
2209 os.dup2(f.fileno(), from_fd)
2210
2211 fd_to_close = (set(range(3)) - set(from_fds)).pop()
2212 os.close(fd_to_close)
2213
2214 arg_names = ['stdin', 'stdout', 'stderr']
2215 kwargs = {}
2216 for from_fd, to_fd in zip(from_fds, to_fds):
2217 kwargs[arg_names[to_fd]] = from_fd
2218
2219 code = textwrap.dedent(r'''
2220 import os, sys
2221 skipped_fd = int(sys.argv[1])
2222 for fd in range(3):
2223 if fd != skipped_fd:
2224 os.write(fd, str(fd).encode('ascii'))
2225 ''')
2226
2227 skipped_fd = (set(range(3)) - set(to_fds)).pop()
2228
2229 rc = subprocess.call([sys.executable, '-c', code, str(skipped_fd)],
2230 **kwargs)
2231 self.assertEqual(rc, 0)
2232
2233 for from_fd, to_fd in zip(from_fds, to_fds):
2234 os.lseek(from_fd, 0, os.SEEK_SET)
2235 read_bytes = os.read(from_fd, 1024)
2236 read_fds = list(map(int, read_bytes.decode('ascii')))
2237 msg = textwrap.dedent(f"""
2238 When testing {from_fds} to {to_fds} redirection,
2239 parent descriptor {from_fd} got redirected
2240 to descriptor(s) {read_fds} instead of descriptor {to_fd}.
2241 """)
2242 self.assertEqual([to_fd], read_fds, msg)
2243 finally:
2244 self._restore_fds(saved_fds)
2245
2246 # Check that subprocess can remap std fds correctly even
2247 # if one of them is closed (#32844).
2248 def test_swap_std_fds_with_one_closed(self):
2249 for from_fds in itertools.combinations(range(3), 2):
2250 for to_fds in itertools.permutations(range(3), 2):
2251 self._check_swap_std_fds_with_one_closed(from_fds, to_fds)
2252
Victor Stinner13bb71c2010-04-23 21:41:56 +00002253 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00002254 def prepare():
2255 raise ValueError("surrogate:\uDCff")
2256
2257 try:
2258 subprocess.call(
2259 [sys.executable, "-c", "pass"],
2260 preexec_fn=prepare)
2261 except ValueError as err:
2262 # Pure Python implementations keeps the message
2263 self.assertIsNone(subprocess._posixsubprocess)
2264 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002265 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00002266 # _posixsubprocess uses a default message
2267 self.assertIsNotNone(subprocess._posixsubprocess)
2268 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
2269 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002270 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00002271
Victor Stinner13bb71c2010-04-23 21:41:56 +00002272 def test_undecodable_env(self):
2273 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01002274 encoded_value = value.encode("ascii", "surrogateescape")
2275
Victor Stinner13bb71c2010-04-23 21:41:56 +00002276 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002277 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002278 env = os.environ.copy()
2279 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01002280 # Use C locale to get ASCII for the locale encoding to force
Michael Felt89d79b12018-08-26 19:29:36 +02002281 # surrogate-escaping of \xFF in the child process
Victor Stinnerebc78d22010-10-14 10:38:17 +00002282 env['LC_ALL'] = 'C'
Michael Felt89d79b12018-08-26 19:29:36 +02002283 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002284 stdout = subprocess.check_output(
2285 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002286 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002287 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002288 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002289
2290 # test bytes
2291 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002292 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002293 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01002294 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002295 stdout = subprocess.check_output(
2296 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002297 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002298 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002299 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002300
Victor Stinnerb745a742010-05-18 17:17:23 +00002301 def test_bytes_program(self):
2302 abs_program = os.fsencode(sys.executable)
2303 path, program = os.path.split(sys.executable)
2304 program = os.fsencode(program)
2305
2306 # absolute bytes path
2307 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00002308 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002309
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002310 # absolute bytes path as a string
2311 cmd = b"'" + abs_program + b"' -c pass"
2312 exitcode = subprocess.call(cmd, shell=True)
2313 self.assertEqual(exitcode, 0)
2314
Victor Stinnerb745a742010-05-18 17:17:23 +00002315 # bytes program, unicode PATH
2316 env = os.environ.copy()
2317 env["PATH"] = path
2318 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002319 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002320
2321 # bytes program, bytes PATH
2322 envb = os.environb.copy()
2323 envb[b"PATH"] = os.fsencode(path)
2324 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002325 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002326
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002327 def test_pipe_cloexec(self):
2328 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2329 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2330
2331 p1 = subprocess.Popen([sys.executable, sleeper],
2332 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2333 stderr=subprocess.PIPE, close_fds=False)
2334
2335 self.addCleanup(p1.communicate, b'')
2336
2337 p2 = subprocess.Popen([sys.executable, fd_status],
2338 stdout=subprocess.PIPE, close_fds=False)
2339
2340 output, error = p2.communicate()
2341 result_fds = set(map(int, output.split(b',')))
2342 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2343 p1.stderr.fileno()])
2344
2345 self.assertFalse(result_fds & unwanted_fds,
2346 "Expected no fds from %r to be open in child, "
2347 "found %r" %
2348 (unwanted_fds, result_fds & unwanted_fds))
2349
2350 def test_pipe_cloexec_real_tools(self):
2351 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2352 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2353
2354 subdata = b'zxcvbn'
2355 data = subdata * 4 + b'\n'
2356
2357 p1 = subprocess.Popen([sys.executable, qcat],
2358 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2359 close_fds=False)
2360
2361 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2362 stdin=p1.stdout, stdout=subprocess.PIPE,
2363 close_fds=False)
2364
2365 self.addCleanup(p1.wait)
2366 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002367 def kill_p1():
2368 try:
2369 p1.terminate()
2370 except ProcessLookupError:
2371 pass
2372 def kill_p2():
2373 try:
2374 p2.terminate()
2375 except ProcessLookupError:
2376 pass
2377 self.addCleanup(kill_p1)
2378 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002379
2380 p1.stdin.write(data)
2381 p1.stdin.close()
2382
2383 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2384
2385 self.assertTrue(readfiles, "The child hung")
2386 self.assertEqual(p2.stdout.read(), data)
2387
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002388 p1.stdout.close()
2389 p2.stdout.close()
2390
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002391 def test_close_fds(self):
2392 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2393
2394 fds = os.pipe()
2395 self.addCleanup(os.close, fds[0])
2396 self.addCleanup(os.close, fds[1])
2397
2398 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002399 # add a bunch more fds
2400 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002401 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002402 self.addCleanup(os.close, fd)
2403 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002404
Victor Stinnerdaf45552013-08-28 00:53:59 +02002405 for fd in open_fds:
2406 os.set_inheritable(fd, True)
2407
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002408 p = subprocess.Popen([sys.executable, fd_status],
2409 stdout=subprocess.PIPE, close_fds=False)
2410 output, ignored = p.communicate()
2411 remaining_fds = set(map(int, output.split(b',')))
2412
2413 self.assertEqual(remaining_fds & open_fds, open_fds,
2414 "Some fds were closed")
2415
2416 p = subprocess.Popen([sys.executable, fd_status],
2417 stdout=subprocess.PIPE, close_fds=True)
2418 output, ignored = p.communicate()
2419 remaining_fds = set(map(int, output.split(b',')))
2420
2421 self.assertFalse(remaining_fds & open_fds,
2422 "Some fds were left open")
2423 self.assertIn(1, remaining_fds, "Subprocess failed")
2424
Gregory P. Smith8facece2012-01-21 14:01:08 -08002425 # Keep some of the fd's we opened open in the subprocess.
2426 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2427 fds_to_keep = set(open_fds.pop() for _ in range(8))
2428 p = subprocess.Popen([sys.executable, fd_status],
2429 stdout=subprocess.PIPE, close_fds=True,
izbyshev2d8f0632017-12-19 03:26:49 +07002430 pass_fds=fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002431 output, ignored = p.communicate()
2432 remaining_fds = set(map(int, output.split(b',')))
2433
izbyshev2d8f0632017-12-19 03:26:49 +07002434 self.assertFalse((remaining_fds - fds_to_keep) & open_fds,
Gregory P. Smith8facece2012-01-21 14:01:08 -08002435 "Some fds not in pass_fds were left open")
2436 self.assertIn(1, remaining_fds, "Subprocess failed")
2437
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002438
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002439 @unittest.skipIf(sys.platform.startswith("freebsd") and
2440 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2441 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002442 def test_close_fds_when_max_fd_is_lowered(self):
2443 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2444 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2445
Gregory P. Smith634aa682014-06-15 17:51:04 -07002446 # This launches the meat of the test in a child process to
2447 # avoid messing with the larger unittest processes maximum
2448 # number of file descriptors.
2449 # This process launches:
2450 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2451 # a bunch of high open fds above the new lower rlimit.
2452 # Those are reported via stdout before launching a new
2453 # process with close_fds=False to run the actual test:
2454 # +--> The TEST: This one launches a fd_status.py
2455 # subprocess with close_fds=True so we can find out if
2456 # any of the fds above the lowered rlimit are still open.
2457 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2458 '''
2459 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002460 open_fds = set()
2461 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002462 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002463 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002464 open_fds.add(fd)
2465
2466 # Leave a two pairs of low ones available for use by the
2467 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002468 # We also leave 10 more open as some Python buildbots run into
2469 # "too many open files" errors during the test if we do not.
2470 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002471 os.close(fd)
2472 open_fds.remove(fd)
2473
2474 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002475 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002476 os.set_inheritable(fd, True)
2477
2478 max_fd_open = max(open_fds)
2479
Gregory P. Smith634aa682014-06-15 17:51:04 -07002480 # Communicate the open_fds to the parent unittest.TestCase process.
2481 print(','.join(map(str, sorted(open_fds))))
2482 sys.stdout.flush()
2483
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002484 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2485 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002486 # 29 is lower than the highest fds we are leaving open.
2487 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002488 # Launch a new Python interpreter with our low fd rlim_cur that
2489 # inherits open fds above that limit. It then uses subprocess
2490 # with close_fds=True to get a report of open fds in the child.
2491 # An explicit list of fds to check is passed to fd_status.py as
2492 # letting fd_status rely on its default logic would miss the
2493 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002494 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002495 [sys.executable, '-c',
2496 textwrap.dedent("""
2497 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002498 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002499 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002500 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002501 """.format(max_fd=max_fd_open+1))],
2502 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002503 finally:
2504 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002505 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002506
2507 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002508 output_lines = output.splitlines()
2509 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002510 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002511 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2512 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002513
Gregory P. Smith634aa682014-06-15 17:51:04 -07002514 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002515 msg="Some fds were left open.")
2516
2517
Victor Stinner88701e22011-06-01 13:13:04 +02002518 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2519 # descriptor of a pipe closed in the parent process is valid in the
2520 # child process according to fstat(), but the mode of the file
2521 # descriptor is invalid, and read or write raise an error.
2522 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002523 def test_pass_fds(self):
2524 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2525
2526 open_fds = set()
2527
2528 for x in range(5):
2529 fds = os.pipe()
2530 self.addCleanup(os.close, fds[0])
2531 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002532 os.set_inheritable(fds[0], True)
2533 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002534 open_fds.update(fds)
2535
2536 for fd in open_fds:
2537 p = subprocess.Popen([sys.executable, fd_status],
2538 stdout=subprocess.PIPE, close_fds=True,
2539 pass_fds=(fd, ))
2540 output, ignored = p.communicate()
2541
2542 remaining_fds = set(map(int, output.split(b',')))
2543 to_be_closed = open_fds - {fd}
2544
2545 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2546 self.assertFalse(remaining_fds & to_be_closed,
2547 "fd to be closed passed")
2548
2549 # pass_fds overrides close_fds with a warning.
2550 with self.assertWarns(RuntimeWarning) as context:
2551 self.assertFalse(subprocess.call(
2552 [sys.executable, "-c", "import sys; sys.exit(0)"],
2553 close_fds=False, pass_fds=(fd, )))
2554 self.assertIn('overriding close_fds', str(context.warning))
2555
Victor Stinnerdaf45552013-08-28 00:53:59 +02002556 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002557 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002558
2559 inheritable, non_inheritable = os.pipe()
2560 self.addCleanup(os.close, inheritable)
2561 self.addCleanup(os.close, non_inheritable)
2562 os.set_inheritable(inheritable, True)
2563 os.set_inheritable(non_inheritable, False)
2564 pass_fds = (inheritable, non_inheritable)
2565 args = [sys.executable, script]
2566 args += list(map(str, pass_fds))
2567
2568 p = subprocess.Popen(args,
2569 stdout=subprocess.PIPE, close_fds=True,
2570 pass_fds=pass_fds)
2571 output, ignored = p.communicate()
2572 fds = set(map(int, output.split(b',')))
2573
2574 # the inheritable file descriptor must be inherited, so its inheritable
2575 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002576 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002577
2578 # inheritable flag must not be changed in the parent process
2579 self.assertEqual(os.get_inheritable(inheritable), True)
2580 self.assertEqual(os.get_inheritable(non_inheritable), False)
2581
Gregory P. Smithce344102018-09-10 17:46:22 -07002582
2583 # bpo-32270: Ensure that descriptors specified in pass_fds
2584 # are inherited even if they are used in redirections.
2585 # Contributed by @izbyshev.
2586 def test_pass_fds_redirected(self):
2587 """Regression test for https://bugs.python.org/issue32270."""
2588 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2589 pass_fds = []
2590 for _ in range(2):
2591 fd = os.open(os.devnull, os.O_RDWR)
2592 self.addCleanup(os.close, fd)
2593 pass_fds.append(fd)
2594
2595 stdout_r, stdout_w = os.pipe()
2596 self.addCleanup(os.close, stdout_r)
2597 self.addCleanup(os.close, stdout_w)
2598 pass_fds.insert(1, stdout_w)
2599
2600 with subprocess.Popen([sys.executable, fd_status],
2601 stdin=pass_fds[0],
2602 stdout=pass_fds[1],
2603 stderr=pass_fds[2],
2604 close_fds=True,
2605 pass_fds=pass_fds):
2606 output = os.read(stdout_r, 1024)
2607 fds = {int(num) for num in output.split(b',')}
2608
2609 self.assertEqual(fds, {0, 1, 2} | frozenset(pass_fds), f"output={output!a}")
2610
2611
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002612 def test_stdout_stdin_are_single_inout_fd(self):
2613 with io.open(os.devnull, "r+") as inout:
2614 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2615 stdout=inout, stdin=inout)
2616 p.wait()
2617
2618 def test_stdout_stderr_are_single_inout_fd(self):
2619 with io.open(os.devnull, "r+") as inout:
2620 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2621 stdout=inout, stderr=inout)
2622 p.wait()
2623
2624 def test_stderr_stdin_are_single_inout_fd(self):
2625 with io.open(os.devnull, "r+") as inout:
2626 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2627 stderr=inout, stdin=inout)
2628 p.wait()
2629
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002630 def test_wait_when_sigchild_ignored(self):
2631 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2632 sigchild_ignore = support.findfile("sigchild_ignore.py",
2633 subdir="subprocessdata")
2634 p = subprocess.Popen([sys.executable, sigchild_ignore],
2635 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2636 stdout, stderr = p.communicate()
2637 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002638 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002639 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002640
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002641 def test_select_unbuffered(self):
2642 # Issue #11459: bufsize=0 should really set the pipes as
2643 # unbuffered (and therefore let select() work properly).
2644 select = support.import_module("select")
2645 p = subprocess.Popen([sys.executable, "-c",
2646 'import sys;'
2647 'sys.stdout.write("apple")'],
2648 stdout=subprocess.PIPE,
2649 bufsize=0)
2650 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002651 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002652 try:
2653 self.assertEqual(f.read(4), b"appl")
2654 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2655 finally:
2656 p.wait()
2657
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002658 def test_zombie_fast_process_del(self):
2659 # Issue #12650: on Unix, if Popen.__del__() was called before the
2660 # process exited, it wouldn't be added to subprocess._active, and would
2661 # remain a zombie.
2662 # spawn a Popen, and delete its reference before it exits
2663 p = subprocess.Popen([sys.executable, "-c",
2664 'import sys, time;'
2665 'time.sleep(0.2)'],
2666 stdout=subprocess.PIPE,
2667 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002668 self.addCleanup(p.stdout.close)
2669 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002670 ident = id(p)
2671 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002672 with support.check_warnings(('', ResourceWarning)):
2673 p = None
2674
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002675 # check that p is in the active processes list
2676 self.assertIn(ident, [id(o) for o in subprocess._active])
2677
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002678 def test_leak_fast_process_del_killed(self):
2679 # Issue #12650: on Unix, if Popen.__del__() was called before the
2680 # process exited, and the process got killed by a signal, it would never
2681 # be removed from subprocess._active, which triggered a FD and memory
2682 # leak.
2683 # spawn a Popen, delete its reference and kill it
2684 p = subprocess.Popen([sys.executable, "-c",
2685 'import time;'
2686 'time.sleep(3)'],
2687 stdout=subprocess.PIPE,
2688 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002689 self.addCleanup(p.stdout.close)
2690 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002691 ident = id(p)
2692 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002693 with support.check_warnings(('', ResourceWarning)):
2694 p = None
2695
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002696 os.kill(pid, signal.SIGKILL)
2697 # check that p is in the active processes list
2698 self.assertIn(ident, [id(o) for o in subprocess._active])
2699
2700 # let some time for the process to exit, and create a new Popen: this
2701 # should trigger the wait() of p
2702 time.sleep(0.2)
Victor Stinnerb31206a2018-01-25 19:06:05 +01002703 with self.assertRaises(OSError):
Victor Stinner9a83f652017-08-21 23:51:31 +02002704 with subprocess.Popen(NONEXISTING_CMD,
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002705 stdout=subprocess.PIPE,
2706 stderr=subprocess.PIPE) as proc:
2707 pass
2708 # p should have been wait()ed on, and removed from the _active list
2709 self.assertRaises(OSError, os.waitpid, pid, 0)
2710 self.assertNotIn(ident, [id(o) for o in subprocess._active])
2711
Charles-François Natali249cdc32013-08-25 18:24:45 +02002712 def test_close_fds_after_preexec(self):
2713 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2714
2715 # this FD is used as dup2() target by preexec_fn, and should be closed
2716 # in the child process
2717 fd = os.dup(1)
2718 self.addCleanup(os.close, fd)
2719
2720 p = subprocess.Popen([sys.executable, fd_status],
2721 stdout=subprocess.PIPE, close_fds=True,
2722 preexec_fn=lambda: os.dup2(1, fd))
2723 output, ignored = p.communicate()
2724
2725 remaining_fds = set(map(int, output.split(b',')))
2726
2727 self.assertNotIn(fd, remaining_fds)
2728
Victor Stinner8f437aa2014-10-05 17:25:19 +02002729 @support.cpython_only
2730 def test_fork_exec(self):
2731 # Issue #22290: fork_exec() must not crash on memory allocation failure
2732 # or other errors
2733 import _posixsubprocess
2734 gc_enabled = gc.isenabled()
2735 try:
2736 # Use a preexec function and enable the garbage collector
2737 # to force fork_exec() to re-enable the garbage collector
2738 # on error.
2739 func = lambda: None
2740 gc.enable()
2741
Victor Stinner8f437aa2014-10-05 17:25:19 +02002742 for args, exe_list, cwd, env_list in (
2743 (123, [b"exe"], None, [b"env"]),
2744 ([b"arg"], 123, None, [b"env"]),
2745 ([b"arg"], [b"exe"], 123, [b"env"]),
2746 ([b"arg"], [b"exe"], None, 123),
2747 ):
2748 with self.assertRaises(TypeError):
2749 _posixsubprocess.fork_exec(
2750 args, exe_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002751 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02002752 -1, -1, -1, -1,
2753 1, 2, 3, 4,
2754 True, True, func)
2755 finally:
2756 if not gc_enabled:
2757 gc.disable()
2758
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002759 @support.cpython_only
2760 def test_fork_exec_sorted_fd_sanity_check(self):
2761 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
2762 import _posixsubprocess
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002763 class BadInt:
2764 first = True
2765 def __init__(self, value):
2766 self.value = value
2767 def __int__(self):
2768 if self.first:
2769 self.first = False
2770 return self.value
2771 raise ValueError
2772
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002773 gc_enabled = gc.isenabled()
2774 try:
2775 gc.enable()
2776
2777 for fds_to_keep in (
2778 (-1, 2, 3, 4, 5), # Negative number.
2779 ('str', 4), # Not an int.
2780 (18, 23, 42, 2**63), # Out of range.
2781 (5, 4), # Not sorted.
2782 (6, 7, 7, 8), # Duplicate.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002783 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002784 ):
2785 with self.assertRaises(
2786 ValueError,
2787 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
2788 _posixsubprocess.fork_exec(
2789 [b"false"], [b"false"],
2790 True, fds_to_keep, None, [b"env"],
2791 -1, -1, -1, -1,
2792 1, 2, 3, 4,
2793 True, True, None)
2794 self.assertIn('fds_to_keep', str(c.exception))
2795 finally:
2796 if not gc_enabled:
2797 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02002798
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00002799 def test_communicate_BrokenPipeError_stdin_close(self):
2800 # By not setting stdout or stderr or a timeout we force the fast path
2801 # that just calls _stdin_write() internally due to our mock.
2802 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2803 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2804 mock_proc_stdin.close.side_effect = BrokenPipeError
2805 proc.communicate() # Should swallow BrokenPipeError from close.
2806 mock_proc_stdin.close.assert_called_with()
2807
2808 def test_communicate_BrokenPipeError_stdin_write(self):
2809 # By not setting stdout or stderr or a timeout we force the fast path
2810 # that just calls _stdin_write() internally due to our mock.
2811 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2812 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2813 mock_proc_stdin.write.side_effect = BrokenPipeError
2814 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
2815 mock_proc_stdin.write.assert_called_once_with(b'stuff')
2816 mock_proc_stdin.close.assert_called_once_with()
2817
2818 def test_communicate_BrokenPipeError_stdin_flush(self):
2819 # Setting stdin and stdout forces the ._communicate() code path.
2820 # python -h exits faster than python -c pass (but spams stdout).
2821 proc = subprocess.Popen([sys.executable, '-h'],
2822 stdin=subprocess.PIPE,
2823 stdout=subprocess.PIPE)
2824 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
2825 open(os.devnull, 'wb') as dev_null:
2826 mock_proc_stdin.flush.side_effect = BrokenPipeError
2827 # because _communicate registers a selector using proc.stdin...
2828 mock_proc_stdin.fileno.return_value = dev_null.fileno()
2829 # _communicate() should swallow BrokenPipeError from flush.
2830 proc.communicate(b'stuff')
2831 mock_proc_stdin.flush.assert_called_once_with()
2832
2833 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
2834 # Setting stdin and stdout forces the ._communicate() code path.
2835 # python -h exits faster than python -c pass (but spams stdout).
2836 proc = subprocess.Popen([sys.executable, '-h'],
2837 stdin=subprocess.PIPE,
2838 stdout=subprocess.PIPE)
2839 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2840 mock_proc_stdin.close.side_effect = BrokenPipeError
2841 # _communicate() should swallow BrokenPipeError from close.
2842 proc.communicate(timeout=999)
2843 mock_proc_stdin.close.assert_called_once_with()
2844
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002845 @unittest.skipUnless(_testcapi is not None
2846 and hasattr(_testcapi, 'W_STOPCODE'),
2847 'need _testcapi.W_STOPCODE')
2848 def test_stopped(self):
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002849 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002850 args = [sys.executable, '-c', 'pass']
2851 proc = subprocess.Popen(args)
Victor Stinnercdee3f12017-06-26 17:23:03 +02002852
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002853 # Wait until the real process completes to avoid zombie process
2854 pid = proc.pid
2855 pid, status = os.waitpid(pid, 0)
2856 self.assertEqual(status, 0)
Victor Stinnercdee3f12017-06-26 17:23:03 +02002857
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002858 status = _testcapi.W_STOPCODE(3)
2859 with mock.patch('subprocess.os.waitpid', return_value=(pid, status)):
2860 returncode = proc.wait()
Victor Stinnercdee3f12017-06-26 17:23:03 +02002861
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002862 self.assertEqual(returncode, -3)
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002863
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002864
Victor Stinner937ee9e2018-06-26 02:11:06 +02002865@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00002866class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002867
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002868 def test_startupinfo(self):
2869 # startupinfo argument
2870 # We uses hardcoded constants, because we do not want to
2871 # depend on win32all.
2872 STARTF_USESHOWWINDOW = 1
2873 SW_MAXIMIZE = 3
2874 startupinfo = subprocess.STARTUPINFO()
2875 startupinfo.dwFlags = STARTF_USESHOWWINDOW
2876 startupinfo.wShowWindow = SW_MAXIMIZE
2877 # Since Python is a console process, it won't be affected
2878 # by wShowWindow, but the argument should be silently
2879 # ignored
2880 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002881 startupinfo=startupinfo)
2882
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05302883 def test_startupinfo_keywords(self):
2884 # startupinfo argument
2885 # We use hardcoded constants, because we do not want to
2886 # depend on win32all.
2887 STARTF_USERSHOWWINDOW = 1
2888 SW_MAXIMIZE = 3
2889 startupinfo = subprocess.STARTUPINFO(
2890 dwFlags=STARTF_USERSHOWWINDOW,
2891 wShowWindow=SW_MAXIMIZE
2892 )
2893 # Since Python is a console process, it won't be affected
2894 # by wShowWindow, but the argument should be silently
2895 # ignored
2896 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
2897 startupinfo=startupinfo)
2898
Victor Stinner483422f2018-07-05 22:54:17 +02002899 def test_startupinfo_copy(self):
2900 # bpo-34044: Popen must not modify input STARTUPINFO structure
2901 startupinfo = subprocess.STARTUPINFO()
2902 startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
2903 startupinfo.wShowWindow = subprocess.SW_HIDE
2904
2905 # Call Popen() twice with the same startupinfo object to make sure
2906 # that it's not modified
2907 for _ in range(2):
2908 cmd = [sys.executable, "-c", "pass"]
2909 with open(os.devnull, 'w') as null:
2910 proc = subprocess.Popen(cmd,
2911 stdout=null,
2912 stderr=subprocess.STDOUT,
2913 startupinfo=startupinfo)
2914 with proc:
2915 proc.communicate()
2916 self.assertEqual(proc.returncode, 0)
2917
2918 self.assertEqual(startupinfo.dwFlags,
2919 subprocess.STARTF_USESHOWWINDOW)
2920 self.assertIsNone(startupinfo.hStdInput)
2921 self.assertIsNone(startupinfo.hStdOutput)
2922 self.assertIsNone(startupinfo.hStdError)
2923 self.assertEqual(startupinfo.wShowWindow, subprocess.SW_HIDE)
2924 self.assertEqual(startupinfo.lpAttributeList, {"handle_list": []})
2925
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002926 def test_creationflags(self):
2927 # creationflags argument
2928 CREATE_NEW_CONSOLE = 16
2929 sys.stderr.write(" a DOS box should flash briefly ...\n")
2930 subprocess.call(sys.executable +
2931 ' -c "import time; time.sleep(0.25)"',
2932 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002933
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002934 def test_invalid_args(self):
2935 # invalid arguments should raise ValueError
2936 self.assertRaises(ValueError, subprocess.call,
2937 [sys.executable, "-c",
2938 "import sys; sys.exit(47)"],
2939 preexec_fn=lambda: 1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002940
Oren Milman0b3a87e2017-09-14 22:30:28 +03002941 @support.cpython_only
2942 def test_issue31471(self):
2943 # There shouldn't be an assertion failure in Popen() in case the env
2944 # argument has a bad keys() method.
2945 class BadEnv(dict):
2946 keys = None
2947 with self.assertRaises(TypeError):
2948 subprocess.Popen([sys.executable, "-c", "pass"], env=BadEnv())
2949
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002950 def test_close_fds(self):
2951 # close file descriptors
2952 rc = subprocess.call([sys.executable, "-c",
2953 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002954 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002955 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002956
Segev Finerb2a60832017-12-18 11:28:19 +02002957 def test_close_fds_with_stdio(self):
2958 import msvcrt
2959
2960 fds = os.pipe()
2961 self.addCleanup(os.close, fds[0])
2962 self.addCleanup(os.close, fds[1])
2963
2964 handles = []
2965 for fd in fds:
2966 os.set_inheritable(fd, True)
2967 handles.append(msvcrt.get_osfhandle(fd))
2968
2969 p = subprocess.Popen([sys.executable, "-c",
2970 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
2971 stdout=subprocess.PIPE, close_fds=False)
2972 stdout, stderr = p.communicate()
2973 self.assertEqual(p.returncode, 0)
2974 int(stdout.strip()) # Check that stdout is an integer
2975
2976 p = subprocess.Popen([sys.executable, "-c",
2977 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
2978 stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
2979 stdout, stderr = p.communicate()
2980 self.assertEqual(p.returncode, 1)
2981 self.assertIn(b"OSError", stderr)
2982
2983 # The same as the previous call, but with an empty handle_list
2984 handle_list = []
2985 startupinfo = subprocess.STARTUPINFO()
2986 startupinfo.lpAttributeList = {"handle_list": handle_list}
2987 p = subprocess.Popen([sys.executable, "-c",
2988 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
2989 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
2990 startupinfo=startupinfo, close_fds=True)
2991 stdout, stderr = p.communicate()
2992 self.assertEqual(p.returncode, 1)
2993 self.assertIn(b"OSError", stderr)
2994
2995 # Check for a warning due to using handle_list and close_fds=False
2996 with support.check_warnings((".*overriding close_fds", RuntimeWarning)):
2997 startupinfo = subprocess.STARTUPINFO()
2998 startupinfo.lpAttributeList = {"handle_list": handles[:]}
2999 p = subprocess.Popen([sys.executable, "-c",
3000 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3001 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3002 startupinfo=startupinfo, close_fds=False)
3003 stdout, stderr = p.communicate()
3004 self.assertEqual(p.returncode, 0)
3005
3006 def test_empty_attribute_list(self):
3007 startupinfo = subprocess.STARTUPINFO()
3008 startupinfo.lpAttributeList = {}
3009 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
3010 startupinfo=startupinfo)
3011
3012 def test_empty_handle_list(self):
3013 startupinfo = subprocess.STARTUPINFO()
3014 startupinfo.lpAttributeList = {"handle_list": []}
3015 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
3016 startupinfo=startupinfo)
3017
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003018 def test_shell_sequence(self):
3019 # Run command through the shell (sequence)
3020 newenv = os.environ.copy()
3021 newenv["FRUIT"] = "physalis"
3022 p = subprocess.Popen(["set"], shell=1,
3023 stdout=subprocess.PIPE,
3024 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003025 with p:
3026 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00003027
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003028 def test_shell_string(self):
3029 # Run command through the shell (string)
3030 newenv = os.environ.copy()
3031 newenv["FRUIT"] = "physalis"
3032 p = subprocess.Popen("set", shell=1,
3033 stdout=subprocess.PIPE,
3034 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003035 with p:
3036 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003037
Steve Dower050acae2016-09-06 20:16:17 -07003038 def test_shell_encodings(self):
3039 # Run command through the shell (string)
3040 for enc in ['ansi', 'oem']:
3041 newenv = os.environ.copy()
3042 newenv["FRUIT"] = "physalis"
3043 p = subprocess.Popen("set", shell=1,
3044 stdout=subprocess.PIPE,
3045 env=newenv,
3046 encoding=enc)
3047 with p:
3048 self.assertIn("physalis", p.stdout.read(), enc)
3049
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003050 def test_call_string(self):
3051 # call() function with string argument on Windows
3052 rc = subprocess.call(sys.executable +
3053 ' -c "import sys; sys.exit(47)"')
3054 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003055
Florent Xicluna4886d242010-03-08 13:27:26 +00003056 def _kill_process(self, method, *args):
3057 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00003058 p = subprocess.Popen([sys.executable, "-c", """if 1:
3059 import sys, time
3060 sys.stdout.write('x\\n')
3061 sys.stdout.flush()
3062 time.sleep(30)
3063 """],
3064 stdin=subprocess.PIPE,
3065 stdout=subprocess.PIPE,
3066 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003067 with p:
3068 # Wait for the interpreter to be completely initialized before
3069 # sending any signal.
3070 p.stdout.read(1)
3071 getattr(p, method)(*args)
3072 _, stderr = p.communicate()
3073 self.assertStderrEqual(stderr, b'')
3074 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00003075 self.assertNotEqual(returncode, 0)
3076
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003077 def _kill_dead_process(self, method, *args):
3078 p = subprocess.Popen([sys.executable, "-c", """if 1:
3079 import sys, time
3080 sys.stdout.write('x\\n')
3081 sys.stdout.flush()
3082 sys.exit(42)
3083 """],
3084 stdin=subprocess.PIPE,
3085 stdout=subprocess.PIPE,
3086 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003087 with p:
3088 # Wait for the interpreter to be completely initialized before
3089 # sending any signal.
3090 p.stdout.read(1)
3091 # The process should end after this
3092 time.sleep(1)
3093 # This shouldn't raise even though the child is now dead
3094 getattr(p, method)(*args)
3095 _, stderr = p.communicate()
3096 self.assertStderrEqual(stderr, b'')
3097 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003098 self.assertEqual(rc, 42)
3099
Florent Xicluna4886d242010-03-08 13:27:26 +00003100 def test_send_signal(self):
3101 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00003102
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003103 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003104 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00003105
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003106 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003107 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00003108
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003109 def test_send_signal_dead(self):
3110 self._kill_dead_process('send_signal', signal.SIGTERM)
3111
3112 def test_kill_dead(self):
3113 self._kill_dead_process('kill')
3114
3115 def test_terminate_dead(self):
3116 self._kill_dead_process('terminate')
3117
Martin Panter23172bd2016-04-16 11:28:10 +00003118class MiscTests(unittest.TestCase):
Gregory P. Smithf4d644f2018-01-29 21:27:39 -08003119
3120 class RecordingPopen(subprocess.Popen):
3121 """A Popen that saves a reference to each instance for testing."""
3122 instances_created = []
3123
3124 def __init__(self, *args, **kwargs):
3125 super().__init__(*args, **kwargs)
3126 self.instances_created.append(self)
3127
3128 @mock.patch.object(subprocess.Popen, "_communicate")
3129 def _test_keyboardinterrupt_no_kill(self, popener, mock__communicate,
3130 **kwargs):
3131 """Fake a SIGINT happening during Popen._communicate() and ._wait().
3132
3133 This avoids the need to actually try and get test environments to send
3134 and receive signals reliably across platforms. The net effect of a ^C
3135 happening during a blocking subprocess execution which we want to clean
3136 up from is a KeyboardInterrupt coming out of communicate() or wait().
3137 """
3138
3139 mock__communicate.side_effect = KeyboardInterrupt
3140 try:
3141 with mock.patch.object(subprocess.Popen, "_wait") as mock__wait:
3142 # We patch out _wait() as no signal was involved so the
3143 # child process isn't actually going to exit rapidly.
3144 mock__wait.side_effect = KeyboardInterrupt
3145 with mock.patch.object(subprocess, "Popen",
3146 self.RecordingPopen):
3147 with self.assertRaises(KeyboardInterrupt):
3148 popener([sys.executable, "-c",
3149 "import time\ntime.sleep(9)\nimport sys\n"
3150 "sys.stderr.write('\\n!runaway child!\\n')"],
3151 stdout=subprocess.DEVNULL, **kwargs)
3152 for call in mock__wait.call_args_list[1:]:
3153 self.assertNotEqual(
3154 call, mock.call(timeout=None),
3155 "no open-ended wait() after the first allowed: "
3156 f"{mock__wait.call_args_list}")
3157 sigint_calls = []
3158 for call in mock__wait.call_args_list:
3159 if call == mock.call(timeout=0.25): # from Popen.__init__
3160 sigint_calls.append(call)
3161 self.assertLessEqual(mock__wait.call_count, 2,
3162 msg=mock__wait.call_args_list)
3163 self.assertEqual(len(sigint_calls), 1,
3164 msg=mock__wait.call_args_list)
3165 finally:
3166 # cleanup the forgotten (due to our mocks) child process
3167 process = self.RecordingPopen.instances_created.pop()
3168 process.kill()
3169 process.wait()
3170 self.assertEqual([], self.RecordingPopen.instances_created)
3171
3172 def test_call_keyboardinterrupt_no_kill(self):
3173 self._test_keyboardinterrupt_no_kill(subprocess.call, timeout=6.282)
3174
3175 def test_run_keyboardinterrupt_no_kill(self):
3176 self._test_keyboardinterrupt_no_kill(subprocess.run, timeout=6.282)
3177
3178 def test_context_manager_keyboardinterrupt_no_kill(self):
3179 def popen_via_context_manager(*args, **kwargs):
3180 with subprocess.Popen(*args, **kwargs) as unused_process:
3181 raise KeyboardInterrupt # Test how __exit__ handles ^C.
3182 self._test_keyboardinterrupt_no_kill(popen_via_context_manager)
3183
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003184 def test_getoutput(self):
3185 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
3186 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
3187 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00003188
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003189 # we use mkdtemp in the next line to create an empty directory
3190 # under our exclusive control; from that, we can invent a pathname
3191 # that we _know_ won't exist. This is guaranteed to fail.
3192 dir = None
3193 try:
3194 dir = tempfile.mkdtemp()
3195 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00003196 status, output = subprocess.getstatusoutput(
Victor Stinner937ee9e2018-06-26 02:11:06 +02003197 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003198 self.assertNotEqual(status, 0)
3199 finally:
3200 if dir is not None:
3201 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00003202
Gregory P. Smithace55862015-04-07 15:57:54 -07003203 def test__all__(self):
3204 """Ensure that __all__ is populated properly."""
Martin Panter528619b2016-04-16 23:42:37 +00003205 intentionally_excluded = {"list2cmdline", "Handle"}
Gregory P. Smithace55862015-04-07 15:57:54 -07003206 exported = set(subprocess.__all__)
3207 possible_exports = set()
3208 import types
3209 for name, value in subprocess.__dict__.items():
3210 if name.startswith('_'):
3211 continue
3212 if isinstance(value, (types.ModuleType,)):
3213 continue
3214 possible_exports.add(name)
3215 self.assertEqual(exported, possible_exports - intentionally_excluded)
3216
3217
Martin Panter23172bd2016-04-16 11:28:10 +00003218@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
3219 "Test needs selectors.PollSelector")
3220class ProcessTestCaseNoPoll(ProcessTestCase):
3221 def setUp(self):
3222 self.orig_selector = subprocess._PopenSelector
3223 subprocess._PopenSelector = selectors.SelectSelector
3224 ProcessTestCase.setUp(self)
3225
3226 def tearDown(self):
3227 subprocess._PopenSelector = self.orig_selector
3228 ProcessTestCase.tearDown(self)
3229
Gregory P. Smithd06fa472009-07-04 02:46:54 +00003230
Victor Stinner937ee9e2018-06-26 02:11:06 +02003231@unittest.skipUnless(mswindows, "Windows-specific tests")
Tim Golden126c2962010-08-11 14:20:40 +00003232class CommandsWithSpaces (BaseTestCase):
3233
3234 def setUp(self):
3235 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03003236 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00003237 self.fname = fname.lower ()
3238 os.write(f, b"import sys;"
3239 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
3240 )
3241 os.close(f)
3242
3243 def tearDown(self):
3244 os.remove(self.fname)
3245 super().tearDown()
3246
3247 def with_spaces(self, *args, **kwargs):
3248 kwargs['stdout'] = subprocess.PIPE
3249 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02003250 with p:
3251 self.assertEqual(
3252 p.stdout.read ().decode("mbcs"),
3253 "2 [%r, 'ab cd']" % self.fname
3254 )
Tim Golden126c2962010-08-11 14:20:40 +00003255
3256 def test_shell_string_with_spaces(self):
3257 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003258 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3259 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003260
3261 def test_shell_sequence_with_spaces(self):
3262 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003263 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003264
3265 def test_noshell_string_with_spaces(self):
3266 # call() function with string argument with spaces on Windows
3267 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3268 "ab cd"))
3269
3270 def test_noshell_sequence_with_spaces(self):
3271 # call() function with sequence argument with spaces on Windows
3272 self.with_spaces([sys.executable, self.fname, "ab cd"])
3273
Brian Curtin79cdb662010-12-03 02:46:02 +00003274
Georg Brandla86b2622012-02-20 21:34:57 +01003275class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00003276
3277 def test_pipe(self):
3278 with subprocess.Popen([sys.executable, "-c",
3279 "import sys;"
3280 "sys.stdout.write('stdout');"
3281 "sys.stderr.write('stderr');"],
3282 stdout=subprocess.PIPE,
3283 stderr=subprocess.PIPE) as proc:
3284 self.assertEqual(proc.stdout.read(), b"stdout")
3285 self.assertStderrEqual(proc.stderr.read(), b"stderr")
3286
3287 self.assertTrue(proc.stdout.closed)
3288 self.assertTrue(proc.stderr.closed)
3289
3290 def test_returncode(self):
3291 with subprocess.Popen([sys.executable, "-c",
3292 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07003293 pass
3294 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00003295 self.assertEqual(proc.returncode, 100)
3296
3297 def test_communicate_stdin(self):
3298 with subprocess.Popen([sys.executable, "-c",
3299 "import sys;"
3300 "sys.exit(sys.stdin.read() == 'context')"],
3301 stdin=subprocess.PIPE) as proc:
3302 proc.communicate(b"context")
3303 self.assertEqual(proc.returncode, 1)
3304
3305 def test_invalid_args(self):
Victor Stinnerb31206a2018-01-25 19:06:05 +01003306 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02003307 with subprocess.Popen(NONEXISTING_CMD,
Brian Curtin79cdb662010-12-03 02:46:02 +00003308 stdout=subprocess.PIPE,
3309 stderr=subprocess.PIPE) as proc:
3310 pass
3311
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003312 def test_broken_pipe_cleanup(self):
3313 """Broken pipe error should not prevent wait() (Issue 21619)"""
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003314 proc = subprocess.Popen([sys.executable, '-c', 'pass'],
Victor Stinner20f4bd42015-03-05 02:38:41 +01003315 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003316 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003317 proc = proc.__enter__()
3318 # Prepare to send enough data to overflow any OS pipe buffering and
3319 # guarantee a broken pipe error. Data is held in BufferedWriter
3320 # buffer until closed.
3321 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003322 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003323 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02003324 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003325 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003326 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003327
Brian Curtin79cdb662010-12-03 02:46:02 +00003328
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003329if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04003330 unittest.main()