blob: 91f525df46079a635f36ccad6014bfa7633cc67c [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
Gregory P. Smith580d2782019-09-11 04:23:05 -050013import traceback
Charles-François Natali3a4586a2013-11-08 19:56:59 +010014import selectors
Ezio Melotti184bdfb2010-02-18 09:37:05 +000015import sysconfig
Gregory P. Smith51ee2702010-12-13 07:59:39 +000016import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040017import shutil
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020018import threading
Benjamin Petersonb870aa12011-12-10 12:44:25 -050019import gc
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030020import textwrap
Serhiy Storchakab21d1552018-03-02 11:53:51 +020021from test.support import FakePath
Benjamin Peterson964561b2011-12-10 12:31:42 -050022
23try:
Victor Stinner7b7c6dc2017-08-10 12:37:39 +020024 import _testcapi
25except ImportError:
26 _testcapi = None
27
Victor Stinner8f4ef3b2019-07-01 18:28:25 +020028
Steve Dower22d06982016-09-06 19:38:15 -070029if support.PGO:
30 raise unittest.SkipTest("test is not helpful for PGO")
31
Victor Stinner937ee9e2018-06-26 02:11:06 +020032mswindows = (sys.platform == "win32")
33
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000034#
35# Depends on the following external programs: Python
36#
37
Victor Stinner937ee9e2018-06-26 02:11:06 +020038if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000039 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
40 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000041else:
42 SETBINARY = ''
43
Victor Stinner9a83f652017-08-21 23:51:31 +020044NONEXISTING_CMD = ('nonexisting_i_hope',)
Victor Stinnerb31206a2018-01-25 19:06:05 +010045# Ignore errors that indicate the command was not found
46NONEXISTING_ERRORS = (FileNotFoundError, NotADirectoryError, PermissionError)
Victor Stinner9a83f652017-08-21 23:51:31 +020047
Florent Xiclunab1e94e82010-02-27 22:12:37 +000048
Florent Xiclunac049d872010-03-27 22:47:23 +000049class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000050 def setUp(self):
51 # Try to minimize the number of children we have so this test
52 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000053 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000054
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000055 def tearDown(self):
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +030056 if not mswindows:
57 # subprocess._active is not used on Windows and is set to None.
58 for inst in subprocess._active:
59 inst.wait()
60 subprocess._cleanup()
61 self.assertFalse(
62 subprocess._active, "subprocess._active not empty"
63 )
Victor Stinnercc42c122017-07-28 18:00:22 +020064 self.doCleanups()
65 support.reap_children()
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000066
Florent Xiclunab1e94e82010-02-27 22:12:37 +000067 def assertStderrEqual(self, stderr, expected, msg=None):
68 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
69 # shutdown time. That frustrates tests trying to check stderr produced
70 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000071 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040072 # strip_python_stderr also strips whitespace, so we do too.
73 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000074 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000075
Florent Xiclunac049d872010-03-27 22:47:23 +000076
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080077class PopenTestException(Exception):
78 pass
79
80
81class PopenExecuteChildRaises(subprocess.Popen):
82 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
83 _execute_child fails.
84 """
85 def _execute_child(self, *args, **kwargs):
86 raise PopenTestException("Forced Exception for Test")
87
88
Florent Xiclunac049d872010-03-27 22:47:23 +000089class ProcessTestCase(BaseTestCase):
90
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070091 def test_io_buffered_by_default(self):
92 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
93 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
94 stderr=subprocess.PIPE)
95 try:
96 self.assertIsInstance(p.stdin, io.BufferedIOBase)
97 self.assertIsInstance(p.stdout, io.BufferedIOBase)
98 self.assertIsInstance(p.stderr, io.BufferedIOBase)
99 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700100 p.stdin.close()
101 p.stdout.close()
102 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700103 p.wait()
104
105 def test_io_unbuffered_works(self):
106 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
107 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
108 stderr=subprocess.PIPE, bufsize=0)
109 try:
110 self.assertIsInstance(p.stdin, io.RawIOBase)
111 self.assertIsInstance(p.stdout, io.RawIOBase)
112 self.assertIsInstance(p.stderr, io.RawIOBase)
113 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700114 p.stdin.close()
115 p.stdout.close()
116 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700117 p.wait()
118
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000119 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000120 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000121 rc = subprocess.call([sys.executable, "-c",
122 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000123 self.assertEqual(rc, 47)
124
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400125 def test_call_timeout(self):
126 # call() function with timeout argument; we want to test that the child
127 # process gets killed when the timeout expires. If the child isn't
128 # killed, this call will deadlock since subprocess.call waits for the
129 # child.
130 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
131 [sys.executable, "-c", "while True: pass"],
132 timeout=0.1)
133
Peter Astrand454f7672005-01-01 09:36:35 +0000134 def test_check_call_zero(self):
135 # check_call() function with zero return code
136 rc = subprocess.check_call([sys.executable, "-c",
137 "import sys; sys.exit(0)"])
138 self.assertEqual(rc, 0)
139
140 def test_check_call_nonzero(self):
141 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000142 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000143 subprocess.check_call([sys.executable, "-c",
144 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000145 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000146
Georg Brandlf9734072008-12-07 15:30:06 +0000147 def test_check_output(self):
148 # check_output() function with zero return code
149 output = subprocess.check_output(
150 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000151 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000152
153 def test_check_output_nonzero(self):
154 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000155 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000156 subprocess.check_output(
157 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000158 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000159
160 def test_check_output_stderr(self):
161 # check_output() function stderr redirected to stdout
162 output = subprocess.check_output(
163 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
164 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000165 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000166
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300167 def test_check_output_stdin_arg(self):
168 # check_output() can be called with stdin set to a file
169 tf = tempfile.TemporaryFile()
170 self.addCleanup(tf.close)
171 tf.write(b'pear')
172 tf.seek(0)
173 output = subprocess.check_output(
174 [sys.executable, "-c",
175 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
176 stdin=tf)
177 self.assertIn(b'PEAR', output)
178
179 def test_check_output_input_arg(self):
180 # check_output() can be called with input set to a string
181 output = subprocess.check_output(
182 [sys.executable, "-c",
183 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
184 input=b'pear')
185 self.assertIn(b'PEAR', output)
186
Georg Brandlf9734072008-12-07 15:30:06 +0000187 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300188 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000189 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000190 output = subprocess.check_output(
191 [sys.executable, "-c", "print('will not be run')"],
192 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000193 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000194 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000195
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300196 def test_check_output_stdin_with_input_arg(self):
197 # check_output() refuses to accept 'stdin' with 'input'
198 tf = tempfile.TemporaryFile()
199 self.addCleanup(tf.close)
200 tf.write(b'pear')
201 tf.seek(0)
202 with self.assertRaises(ValueError) as c:
203 output = subprocess.check_output(
204 [sys.executable, "-c", "print('will not be run')"],
205 stdin=tf, input=b'hare')
206 self.fail("Expected ValueError when stdin and input args supplied.")
207 self.assertIn('stdin', c.exception.args[0])
208 self.assertIn('input', c.exception.args[0])
209
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400210 def test_check_output_timeout(self):
211 # check_output() function with timeout arg
212 with self.assertRaises(subprocess.TimeoutExpired) as c:
213 output = subprocess.check_output(
214 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200215 "import sys, time\n"
216 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400217 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200218 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400219 # Some heavily loaded buildbots (sparc Debian 3.x) require
220 # this much time to start and print.
221 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400222 self.fail("Expected TimeoutExpired.")
223 self.assertEqual(c.exception.output, b'BDFL')
224
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000225 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000226 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000227 newenv = os.environ.copy()
228 newenv["FRUIT"] = "banana"
229 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000230 'import sys, os;'
231 'sys.exit(os.getenv("FRUIT")=="banana")'],
232 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000233 self.assertEqual(rc, 1)
234
Victor Stinner87b9bc32011-06-01 00:57:47 +0200235 def test_invalid_args(self):
236 # Popen() called with invalid arguments should raise TypeError
237 # but Popen.__del__ should not complain (issue #12085)
238 with support.captured_stderr() as s:
239 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
240 argcount = subprocess.Popen.__init__.__code__.co_argcount
241 too_many_args = [0] * (argcount + 1)
242 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
243 self.assertEqual(s.getvalue(), '')
244
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000245 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000246 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000247 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000248 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000249 self.addCleanup(p.stdout.close)
250 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000251 p.wait()
252 self.assertEqual(p.stdin, None)
253
254 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200255 # .stdout is None when not redirected, and the child's stdout will
256 # be inherited from the parent. In order to test this we run a
257 # subprocess in a subprocess:
258 # this_test
259 # \-- subprocess created by this test (parent)
260 # \-- subprocess created by the parent subprocess (child)
261 # The parent doesn't specify stdout, so the child will use the
262 # parent's stdout. This test checks that the message printed by the
263 # child goes to the parent stdout. The parent also checks that the
264 # child's stdout is None. See #11963.
265 code = ('import sys; from subprocess import Popen, PIPE;'
266 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
267 ' stdin=PIPE, stderr=PIPE);'
268 'p.wait(); assert p.stdout is None;')
269 p = subprocess.Popen([sys.executable, "-c", code],
270 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
271 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000272 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200273 out, err = p.communicate()
274 self.assertEqual(p.returncode, 0, err)
275 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000276
277 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000278 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000279 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000280 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000281 self.addCleanup(p.stdout.close)
282 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000283 p.wait()
284 self.assertEqual(p.stderr, None)
285
Chris Jerdonek776cb192012-10-08 15:56:43 -0700286 def _assert_python(self, pre_args, **kwargs):
287 # We include sys.exit() to prevent the test runner from hanging
288 # whenever python is found.
289 args = pre_args + ["import sys; sys.exit(47)"]
290 p = subprocess.Popen(args, **kwargs)
291 p.wait()
292 self.assertEqual(47, p.returncode)
293
294 def test_executable(self):
295 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700296 #
297 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
298 # determine where its standard library is, so we need the directory
299 # of args[0] to be valid for the Popen() call to Python to succeed.
300 # See also issue #16170 and issue #7774.
301 doesnotexist = os.path.join(os.path.dirname(sys.executable),
302 "doesnotexist")
303 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700304
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300305 def test_bytes_executable(self):
306 doesnotexist = os.path.join(os.path.dirname(sys.executable),
307 "doesnotexist")
308 self._assert_python([doesnotexist, "-c"],
309 executable=os.fsencode(sys.executable))
310
311 def test_pathlike_executable(self):
312 doesnotexist = os.path.join(os.path.dirname(sys.executable),
313 "doesnotexist")
314 self._assert_python([doesnotexist, "-c"],
315 executable=FakePath(sys.executable))
316
Chris Jerdonek776cb192012-10-08 15:56:43 -0700317 def test_executable_takes_precedence(self):
318 # Check that the executable argument takes precedence over args[0].
319 #
320 # Verify first that the call succeeds without the executable arg.
321 pre_args = [sys.executable, "-c"]
322 self._assert_python(pre_args)
Victor Stinnerb31206a2018-01-25 19:06:05 +0100323 self.assertRaises(NONEXISTING_ERRORS,
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +0100324 self._assert_python, pre_args,
Victor Stinnerb31206a2018-01-25 19:06:05 +0100325 executable=NONEXISTING_CMD[0])
Chris Jerdonek776cb192012-10-08 15:56:43 -0700326
Victor Stinner937ee9e2018-06-26 02:11:06 +0200327 @unittest.skipIf(mswindows, "executable argument replaces shell")
Chris Jerdonek776cb192012-10-08 15:56:43 -0700328 def test_executable_replaces_shell(self):
329 # Check that the executable argument replaces the default shell
330 # when shell=True.
331 self._assert_python([], executable=sys.executable, shell=True)
332
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300333 @unittest.skipIf(mswindows, "executable argument replaces shell")
334 def test_bytes_executable_replaces_shell(self):
335 self._assert_python([], executable=os.fsencode(sys.executable),
336 shell=True)
337
338 @unittest.skipIf(mswindows, "executable argument replaces shell")
339 def test_pathlike_executable_replaces_shell(self):
340 self._assert_python([], executable=FakePath(sys.executable),
341 shell=True)
342
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700343 # For use in the test_cwd* tests below.
344 def _normalize_cwd(self, cwd):
345 # Normalize an expected cwd (for Tru64 support).
346 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
347 # strings. See bug #1063571.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300348 with support.change_cwd(cwd):
349 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700350
351 # For use in the test_cwd* tests below.
352 def _split_python_path(self):
353 # Return normalized (python_dir, python_base).
354 python_path = os.path.realpath(sys.executable)
355 return os.path.split(python_path)
356
357 # For use in the test_cwd* tests below.
358 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
359 # Invoke Python via Popen, and assert that (1) the call succeeds,
360 # and that (2) the current working directory of the child process
361 # matches *expected_cwd*.
362 p = subprocess.Popen([python_arg, "-c",
363 "import os, sys; "
364 "sys.stdout.write(os.getcwd()); "
365 "sys.exit(47)"],
366 stdout=subprocess.PIPE,
367 **kwargs)
368 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000369 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700370 self.assertEqual(47, p.returncode)
371 normcase = os.path.normcase
372 self.assertEqual(normcase(expected_cwd),
373 normcase(p.stdout.read().decode("utf-8")))
374
375 def test_cwd(self):
376 # Check that cwd changes the cwd for the child process.
377 temp_dir = tempfile.gettempdir()
378 temp_dir = self._normalize_cwd(temp_dir)
379 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
380
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300381 def test_cwd_with_bytes(self):
382 temp_dir = tempfile.gettempdir()
383 temp_dir = self._normalize_cwd(temp_dir)
384 self._assert_cwd(temp_dir, sys.executable, cwd=os.fsencode(temp_dir))
385
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530386 def test_cwd_with_pathlike(self):
387 temp_dir = tempfile.gettempdir()
388 temp_dir = self._normalize_cwd(temp_dir)
Serhiy Storchakab21d1552018-03-02 11:53:51 +0200389 self._assert_cwd(temp_dir, sys.executable, cwd=FakePath(temp_dir))
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530390
Victor Stinner937ee9e2018-06-26 02:11:06 +0200391 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700392 def test_cwd_with_relative_arg(self):
393 # Check that Popen looks for args[0] relative to cwd if args[0]
394 # is relative.
395 python_dir, python_base = self._split_python_path()
396 rel_python = os.path.join(os.curdir, python_base)
397 with support.temp_cwd() as wrong_dir:
398 # Before calling with the correct cwd, confirm that the call fails
399 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700400 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700401 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700402 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700403 [rel_python], cwd=wrong_dir)
404 python_dir = self._normalize_cwd(python_dir)
405 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
406
Victor Stinner937ee9e2018-06-26 02:11:06 +0200407 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700408 def test_cwd_with_relative_executable(self):
409 # Check that Popen looks for executable relative to cwd if executable
410 # is relative (and that executable takes precedence over args[0]).
411 python_dir, python_base = self._split_python_path()
412 rel_python = os.path.join(os.curdir, python_base)
413 doesntexist = "somethingyoudonthave"
414 with support.temp_cwd() as wrong_dir:
415 # Before calling with the correct cwd, confirm that the call fails
416 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700417 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700418 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700419 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700420 [doesntexist], executable=rel_python,
421 cwd=wrong_dir)
422 python_dir = self._normalize_cwd(python_dir)
423 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
424 cwd=python_dir)
425
426 def test_cwd_with_absolute_arg(self):
427 # Check that Popen can find the executable when the cwd is wrong
428 # if args[0] is an absolute path.
429 python_dir, python_base = self._split_python_path()
430 abs_python = os.path.join(python_dir, python_base)
431 rel_python = os.path.join(os.curdir, python_base)
Berker Peksagce643912015-05-06 06:33:17 +0300432 with support.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700433 # Before calling with an absolute path, confirm that using a
434 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700435 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700436 [rel_python], cwd=wrong_dir)
437 wrong_dir = self._normalize_cwd(wrong_dir)
438 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
439
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100440 @unittest.skipIf(sys.base_prefix != sys.prefix,
441 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000442 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700443 python_dir, python_base = self._split_python_path()
444 python_dir = self._normalize_cwd(python_dir)
445 self._assert_cwd(python_dir, "somethingyoudonthave",
446 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000447
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100448 @unittest.skipIf(sys.base_prefix != sys.prefix,
449 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000450 @unittest.skipIf(sysconfig.is_python_build(),
451 "need an installed Python. See #7774")
452 def test_executable_without_cwd(self):
453 # For a normal installation, it should work without 'cwd'
454 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700455 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
456 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000457
458 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000459 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000460 p = subprocess.Popen([sys.executable, "-c",
461 'import sys; sys.exit(sys.stdin.read() == "pear")'],
462 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000463 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000464 p.stdin.close()
465 p.wait()
466 self.assertEqual(p.returncode, 1)
467
468 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000469 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000470 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000471 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000472 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000473 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000474 os.lseek(d, 0, 0)
475 p = subprocess.Popen([sys.executable, "-c",
476 'import sys; sys.exit(sys.stdin.read() == "pear")'],
477 stdin=d)
478 p.wait()
479 self.assertEqual(p.returncode, 1)
480
481 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000482 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000483 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000484 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000485 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000486 tf.seek(0)
487 p = subprocess.Popen([sys.executable, "-c",
488 'import sys; sys.exit(sys.stdin.read() == "pear")'],
489 stdin=tf)
490 p.wait()
491 self.assertEqual(p.returncode, 1)
492
493 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000494 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000495 p = subprocess.Popen([sys.executable, "-c",
496 'import sys; sys.stdout.write("orange")'],
497 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200498 with p:
499 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000500
501 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000502 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000503 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000504 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000505 d = tf.fileno()
506 p = subprocess.Popen([sys.executable, "-c",
507 'import sys; sys.stdout.write("orange")'],
508 stdout=d)
509 p.wait()
510 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000511 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000512
513 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000514 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000515 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000516 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000517 p = subprocess.Popen([sys.executable, "-c",
518 'import sys; sys.stdout.write("orange")'],
519 stdout=tf)
520 p.wait()
521 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000522 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000523
524 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000525 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000526 p = subprocess.Popen([sys.executable, "-c",
527 'import sys; sys.stderr.write("strawberry")'],
528 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200529 with p:
530 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000531
532 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000533 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000534 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000535 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000536 d = tf.fileno()
537 p = subprocess.Popen([sys.executable, "-c",
538 'import sys; sys.stderr.write("strawberry")'],
539 stderr=d)
540 p.wait()
541 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000542 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000543
544 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000545 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000546 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000547 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000548 p = subprocess.Popen([sys.executable, "-c",
549 'import sys; sys.stderr.write("strawberry")'],
550 stderr=tf)
551 p.wait()
552 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000553 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000554
Martin Panterc7635892016-05-13 01:54:44 +0000555 def test_stderr_redirect_with_no_stdout_redirect(self):
556 # test stderr=STDOUT while stdout=None (not set)
557
558 # - grandchild prints to stderr
559 # - child redirects grandchild's stderr to its stdout
560 # - the parent should get grandchild's stderr in child's stdout
561 p = subprocess.Popen([sys.executable, "-c",
562 'import sys, subprocess;'
563 'rc = subprocess.call([sys.executable, "-c",'
564 ' "import sys;"'
565 ' "sys.stderr.write(\'42\')"],'
566 ' stderr=subprocess.STDOUT);'
567 'sys.exit(rc)'],
568 stdout=subprocess.PIPE,
569 stderr=subprocess.PIPE)
570 stdout, stderr = p.communicate()
571 #NOTE: stdout should get stderr from grandchild
572 self.assertStderrEqual(stdout, b'42')
573 self.assertStderrEqual(stderr, b'') # should be empty
574 self.assertEqual(p.returncode, 0)
575
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000576 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000577 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000578 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000579 'import sys;'
580 'sys.stdout.write("apple");'
581 'sys.stdout.flush();'
582 'sys.stderr.write("orange")'],
583 stdout=subprocess.PIPE,
584 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200585 with p:
586 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000587
588 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000589 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000590 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000591 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000592 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000593 'import sys;'
594 'sys.stdout.write("apple");'
595 'sys.stdout.flush();'
596 'sys.stderr.write("orange")'],
597 stdout=tf,
598 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000599 p.wait()
600 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000601 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000602
Thomas Wouters89f507f2006-12-13 04:49:30 +0000603 def test_stdout_filedes_of_stdout(self):
604 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200605 # To avoid printing the text on stdout, we do something similar to
606 # test_stdout_none (see above). The parent subprocess calls the child
607 # subprocess passing stdout=1, and this test uses stdout=PIPE in
608 # order to capture and check the output of the parent. See #11963.
609 code = ('import sys, subprocess; '
610 'rc = subprocess.call([sys.executable, "-c", '
611 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
612 'b\'test with stdout=1\'))"], stdout=1); '
613 'assert rc == 18')
614 p = subprocess.Popen([sys.executable, "-c", code],
615 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
616 self.addCleanup(p.stdout.close)
617 self.addCleanup(p.stderr.close)
618 out, err = p.communicate()
619 self.assertEqual(p.returncode, 0, err)
620 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000621
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200622 def test_stdout_devnull(self):
623 p = subprocess.Popen([sys.executable, "-c",
624 'for i in range(10240):'
625 'print("x" * 1024)'],
626 stdout=subprocess.DEVNULL)
627 p.wait()
628 self.assertEqual(p.stdout, None)
629
630 def test_stderr_devnull(self):
631 p = subprocess.Popen([sys.executable, "-c",
632 'import sys\n'
633 'for i in range(10240):'
634 'sys.stderr.write("x" * 1024)'],
635 stderr=subprocess.DEVNULL)
636 p.wait()
637 self.assertEqual(p.stderr, None)
638
639 def test_stdin_devnull(self):
640 p = subprocess.Popen([sys.executable, "-c",
641 'import sys;'
642 'sys.stdin.read(1)'],
643 stdin=subprocess.DEVNULL)
644 p.wait()
645 self.assertEqual(p.stdin, None)
646
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000647 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000648 newenv = os.environ.copy()
649 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200650 with subprocess.Popen([sys.executable, "-c",
651 'import sys,os;'
652 'sys.stdout.write(os.getenv("FRUIT"))'],
653 stdout=subprocess.PIPE,
654 env=newenv) as p:
655 stdout, stderr = p.communicate()
656 self.assertEqual(stdout, b"orange")
657
Victor Stinner62d51182011-06-23 01:02:25 +0200658 # Windows requires at least the SYSTEMROOT environment variable to start
659 # Python
660 @unittest.skipIf(sys.platform == 'win32',
661 'cannot test an empty env on Windows')
Gregory P. Smithb3512482017-05-30 14:40:37 -0700662 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
663 'The Python shared library cannot be loaded '
664 'with an empty environment.')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200665 def test_empty_env(self):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700666 """Verify that env={} is as empty as possible."""
667
Gregory P. Smith85aba232017-05-30 16:21:47 -0700668 def is_env_var_to_ignore(n):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700669 """Determine if an environment variable is under our control."""
670 # This excludes some __CF_* and VERSIONER_* keys MacOS insists
671 # on adding even when the environment in exec is empty.
672 # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist.
Gregory P. Smith85aba232017-05-30 16:21:47 -0700673 return ('VERSIONER' in n or '__CF' in n or # MacOS
Ned Deily918edc02017-09-04 00:00:21 -0400674 '__PYVENV_LAUNCHER__' in n or # MacOS framework build
Nick Coghlan6ea41862017-06-11 13:16:15 +1000675 n == 'LD_PRELOAD' or n.startswith('SANDBOX') or # Gentoo
676 n == 'LC_CTYPE') # Locale coercion triggered
Gregory P. Smithb3512482017-05-30 14:40:37 -0700677
Victor Stinnerf1512a22011-06-21 17:18:38 +0200678 with subprocess.Popen([sys.executable, "-c",
Gregory P. Smithb3512482017-05-30 14:40:37 -0700679 'import os; print(list(os.environ.keys()))'],
680 stdout=subprocess.PIPE, env={}) as p:
Victor Stinnerf1512a22011-06-21 17:18:38 +0200681 stdout, stderr = p.communicate()
Gregory P. Smithb3512482017-05-30 14:40:37 -0700682 child_env_names = eval(stdout.strip())
683 self.assertIsInstance(child_env_names, list)
684 child_env_names = [k for k in child_env_names
685 if not is_env_var_to_ignore(k)]
686 self.assertEqual(child_env_names, [])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000687
Serhiy Storchakad174d242017-06-23 19:39:27 +0300688 def test_invalid_cmd(self):
689 # null character in the command name
690 cmd = sys.executable + '\0'
691 with self.assertRaises(ValueError):
692 subprocess.Popen([cmd, "-c", "pass"])
693
694 # null character in the command argument
695 with self.assertRaises(ValueError):
696 subprocess.Popen([sys.executable, "-c", "pass#\0"])
697
698 def test_invalid_env(self):
Ville Skyttä49b27342017-08-03 09:00:59 +0300699 # null character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300700 newenv = os.environ.copy()
701 newenv["FRUIT\0VEGETABLE"] = "cabbage"
702 with self.assertRaises(ValueError):
703 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
704
Ville Skyttä49b27342017-08-03 09:00:59 +0300705 # null character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300706 newenv = os.environ.copy()
707 newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
708 with self.assertRaises(ValueError):
709 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
710
Ville Skyttä49b27342017-08-03 09:00:59 +0300711 # equal character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300712 newenv = os.environ.copy()
713 newenv["FRUIT=ORANGE"] = "lemon"
714 with self.assertRaises(ValueError):
715 subprocess.Popen([sys.executable, "-c", "pass"], env=newenv)
716
Ville Skyttä49b27342017-08-03 09:00:59 +0300717 # equal character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300718 newenv = os.environ.copy()
719 newenv["FRUIT"] = "orange=lemon"
720 with subprocess.Popen([sys.executable, "-c",
721 'import sys, os;'
722 'sys.stdout.write(os.getenv("FRUIT"))'],
723 stdout=subprocess.PIPE,
724 env=newenv) as p:
725 stdout, stderr = p.communicate()
726 self.assertEqual(stdout, b"orange=lemon")
727
Peter Astrandcbac93c2005-03-03 20:24:28 +0000728 def test_communicate_stdin(self):
729 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000730 'import sys;'
731 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000732 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000733 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000734 self.assertEqual(p.returncode, 1)
735
736 def test_communicate_stdout(self):
737 p = subprocess.Popen([sys.executable, "-c",
738 'import sys; sys.stdout.write("pineapple")'],
739 stdout=subprocess.PIPE)
740 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000741 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000742 self.assertEqual(stderr, None)
743
744 def test_communicate_stderr(self):
745 p = subprocess.Popen([sys.executable, "-c",
746 'import sys; sys.stderr.write("pineapple")'],
747 stderr=subprocess.PIPE)
748 (stdout, stderr) = p.communicate()
749 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000750 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000751
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000752 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000753 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000754 'import sys,os;'
755 'sys.stderr.write("pineapple");'
756 'sys.stdout.write(sys.stdin.read())'],
757 stdin=subprocess.PIPE,
758 stdout=subprocess.PIPE,
759 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000760 self.addCleanup(p.stdout.close)
761 self.addCleanup(p.stderr.close)
762 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000763 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000764 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000765 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000766
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400767 def test_communicate_timeout(self):
768 p = subprocess.Popen([sys.executable, "-c",
769 'import sys,os,time;'
770 'sys.stderr.write("pineapple\\n");'
771 'time.sleep(1);'
772 'sys.stderr.write("pear\\n");'
773 'sys.stdout.write(sys.stdin.read())'],
774 universal_newlines=True,
775 stdin=subprocess.PIPE,
776 stdout=subprocess.PIPE,
777 stderr=subprocess.PIPE)
778 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
779 timeout=0.3)
780 # Make sure we can keep waiting for it, and that we get the whole output
781 # after it completes.
782 (stdout, stderr) = p.communicate()
783 self.assertEqual(stdout, "banana")
784 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
785
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700786 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200787 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400788 p = subprocess.Popen([sys.executable, "-c",
789 'import sys,os,time;'
790 'sys.stdout.write("a" * (64 * 1024));'
791 'time.sleep(0.2);'
792 'sys.stdout.write("a" * (64 * 1024));'
793 'time.sleep(0.2);'
794 'sys.stdout.write("a" * (64 * 1024));'
795 'time.sleep(0.2);'
796 'sys.stdout.write("a" * (64 * 1024));'],
797 stdout=subprocess.PIPE)
798 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
799 (stdout, _) = p.communicate()
800 self.assertEqual(len(stdout), 4 * 64 * 1024)
801
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000802 # Test for the fd leak reported in http://bugs.python.org/issue2791.
803 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000804 for stdin_pipe in (False, True):
805 for stdout_pipe in (False, True):
806 for stderr_pipe in (False, True):
807 options = {}
808 if stdin_pipe:
809 options['stdin'] = subprocess.PIPE
810 if stdout_pipe:
811 options['stdout'] = subprocess.PIPE
812 if stderr_pipe:
813 options['stderr'] = subprocess.PIPE
814 if not options:
815 continue
816 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
817 p.communicate()
818 if p.stdin is not None:
819 self.assertTrue(p.stdin.closed)
820 if p.stdout is not None:
821 self.assertTrue(p.stdout.closed)
822 if p.stderr is not None:
823 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000824
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000825 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000826 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000827 p = subprocess.Popen([sys.executable, "-c",
828 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000829 (stdout, stderr) = p.communicate()
830 self.assertEqual(stdout, None)
831 self.assertEqual(stderr, None)
832
833 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000834 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000835 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000836 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000837 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000838 os.close(x)
839 os.close(y)
840 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000841 'import sys,os;'
842 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200843 'sys.stderr.write("x" * %d);'
844 'sys.stdout.write(sys.stdin.read())' %
845 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000846 stdin=subprocess.PIPE,
847 stdout=subprocess.PIPE,
848 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000849 self.addCleanup(p.stdout.close)
850 self.addCleanup(p.stderr.close)
851 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200852 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000853 (stdout, stderr) = p.communicate(string_to_write)
854 self.assertEqual(stdout, string_to_write)
855
856 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000857 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000858 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000859 'import sys,os;'
860 'sys.stdout.write(sys.stdin.read())'],
861 stdin=subprocess.PIPE,
862 stdout=subprocess.PIPE,
863 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000864 self.addCleanup(p.stdout.close)
865 self.addCleanup(p.stderr.close)
866 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000867 p.stdin.write(b"banana")
868 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000869 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000870 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000871
andyclegg7fed7bd2017-10-23 03:01:19 +0100872 def test_universal_newlines_and_text(self):
873 args = [
874 sys.executable, "-c",
875 'import sys,os;' + SETBINARY +
876 'buf = sys.stdout.buffer;'
877 'buf.write(sys.stdin.readline().encode());'
878 'buf.flush();'
879 'buf.write(b"line2\\n");'
880 'buf.flush();'
881 'buf.write(sys.stdin.read().encode());'
882 'buf.flush();'
883 'buf.write(b"line4\\n");'
884 'buf.flush();'
885 'buf.write(b"line5\\r\\n");'
886 'buf.flush();'
887 'buf.write(b"line6\\r");'
888 'buf.flush();'
889 'buf.write(b"\\nline7");'
890 'buf.flush();'
891 'buf.write(b"\\nline8");']
892
893 for extra_kwarg in ('universal_newlines', 'text'):
894 p = subprocess.Popen(args, **{'stdin': subprocess.PIPE,
895 'stdout': subprocess.PIPE,
896 extra_kwarg: True})
897 with p:
898 p.stdin.write("line1\n")
899 p.stdin.flush()
900 self.assertEqual(p.stdout.readline(), "line1\n")
901 p.stdin.write("line3\n")
902 p.stdin.close()
903 self.addCleanup(p.stdout.close)
904 self.assertEqual(p.stdout.readline(),
905 "line2\n")
906 self.assertEqual(p.stdout.read(6),
907 "line3\n")
908 self.assertEqual(p.stdout.read(),
909 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000910
911 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000912 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000913 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000914 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200915 'buf = sys.stdout.buffer;'
916 'buf.write(b"line2\\n");'
917 'buf.flush();'
918 'buf.write(b"line4\\n");'
919 'buf.flush();'
920 'buf.write(b"line5\\r\\n");'
921 'buf.flush();'
922 'buf.write(b"line6\\r");'
923 'buf.flush();'
924 'buf.write(b"\\nline7");'
925 'buf.flush();'
926 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200927 stderr=subprocess.PIPE,
928 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000929 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000930 self.addCleanup(p.stdout.close)
931 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000932 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200933 self.assertEqual(stdout,
934 "line2\nline4\nline5\nline6\nline7\nline8")
935
936 def test_universal_newlines_communicate_stdin(self):
937 # universal newlines through communicate(), with only stdin
938 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300939 'import sys,os;' + SETBINARY + textwrap.dedent('''
940 s = sys.stdin.readline()
941 assert s == "line1\\n", repr(s)
942 s = sys.stdin.read()
943 assert s == "line3\\n", repr(s)
944 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200945 stdin=subprocess.PIPE,
946 universal_newlines=1)
947 (stdout, stderr) = p.communicate("line1\nline3\n")
948 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000949
Andrew Svetlovf3765072012-08-14 18:35:17 +0300950 def test_universal_newlines_communicate_input_none(self):
951 # Test communicate(input=None) with universal newlines.
952 #
953 # We set stdout to PIPE because, as of this writing, a different
954 # code path is tested when the number of pipes is zero or one.
955 p = subprocess.Popen([sys.executable, "-c", "pass"],
956 stdin=subprocess.PIPE,
957 stdout=subprocess.PIPE,
958 universal_newlines=True)
959 p.communicate()
960 self.assertEqual(p.returncode, 0)
961
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300962 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300963 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300964 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300965 'import sys,os;' + SETBINARY + textwrap.dedent('''
966 s = sys.stdin.buffer.readline()
967 sys.stdout.buffer.write(s)
968 sys.stdout.buffer.write(b"line2\\r")
969 sys.stderr.buffer.write(b"eline2\\n")
970 s = sys.stdin.buffer.read()
971 sys.stdout.buffer.write(s)
972 sys.stdout.buffer.write(b"line4\\n")
973 sys.stdout.buffer.write(b"line5\\r\\n")
974 sys.stderr.buffer.write(b"eline6\\r")
975 sys.stderr.buffer.write(b"eline7\\r\\nz")
976 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300977 stdin=subprocess.PIPE,
978 stderr=subprocess.PIPE,
979 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300980 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300981 self.addCleanup(p.stdout.close)
982 self.addCleanup(p.stderr.close)
983 (stdout, stderr) = p.communicate("line1\nline3\n")
984 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300985 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300986 # Python debug build push something like "[42442 refs]\n"
987 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300988 # Don't use assertStderrEqual because it strips CR and LF from output.
989 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300990
Andrew Svetlov82860712012-08-19 22:13:41 +0300991 def test_universal_newlines_communicate_encodings(self):
992 # Check that universal newlines mode works for various encodings,
993 # in particular for encodings in the UTF-16 and UTF-32 families.
994 # See issue #15595.
995 #
996 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
997 # without, and UTF-16 and UTF-32.
998 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +0300999 code = ("import sys; "
1000 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
1001 encoding)
1002 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -07001003 # We set stdin to be non-None because, as of this writing,
1004 # a different code path is used when the number of pipes is
1005 # zero or one.
1006 popen = subprocess.Popen(args,
1007 stdin=subprocess.PIPE,
1008 stdout=subprocess.PIPE,
1009 encoding=encoding)
1010 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +03001011 self.assertEqual(stdout, '1\n2\n3\n4')
1012
Steve Dower050acae2016-09-06 20:16:17 -07001013 def test_communicate_errors(self):
1014 for errors, expected in [
1015 ('ignore', ''),
1016 ('replace', '\ufffd\ufffd'),
1017 ('surrogateescape', '\udc80\udc80'),
1018 ('backslashreplace', '\\x80\\x80'),
1019 ]:
1020 code = ("import sys; "
1021 r"sys.stdout.buffer.write(b'[\x80\x80]')")
1022 args = [sys.executable, '-c', code]
1023 # We set stdin to be non-None because, as of this writing,
1024 # a different code path is used when the number of pipes is
1025 # zero or one.
1026 popen = subprocess.Popen(args,
1027 stdin=subprocess.PIPE,
1028 stdout=subprocess.PIPE,
1029 encoding='utf-8',
1030 errors=errors)
1031 stdout, stderr = popen.communicate(input='')
1032 self.assertEqual(stdout, '[{}]'.format(expected))
1033
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001034 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +00001035 # Make sure we leak no resources
Victor Stinner937ee9e2018-06-26 02:11:06 +02001036 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +00001037 max_handles = 1026 # too much for most UNIX systems
1038 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +00001039 max_handles = 2050 # too much for (at least some) Windows setups
1040 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001041 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +00001042 try:
1043 for i in range(max_handles):
1044 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001045 tmpfile = os.path.join(tmpdir, support.TESTFN)
1046 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +00001047 except OSError as e:
1048 if e.errno != errno.EMFILE:
1049 raise
1050 break
1051 else:
1052 self.skipTest("failed to reach the file descriptor limit "
1053 "(tried %d)" % max_handles)
1054 # Close a couple of them (should be enough for a subprocess)
1055 for i in range(10):
1056 os.close(handles.pop())
1057 # Loop creating some subprocesses. If one of them leaks some fds,
1058 # the next loop iteration will fail by reaching the max fd limit.
1059 for i in range(15):
1060 p = subprocess.Popen([sys.executable, "-c",
1061 "import sys;"
1062 "sys.stdout.write(sys.stdin.read())"],
1063 stdin=subprocess.PIPE,
1064 stdout=subprocess.PIPE,
1065 stderr=subprocess.PIPE)
1066 data = p.communicate(b"lime")[0]
1067 self.assertEqual(data, b"lime")
1068 finally:
1069 for h in handles:
1070 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001071 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001072
1073 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001074 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
1075 '"a b c" d e')
1076 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
1077 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +00001078 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
1079 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001080 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
1081 'a\\\\\\b "de fg" h')
1082 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
1083 'a\\\\\\"b c d')
1084 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
1085 '"a\\\\b c" d e')
1086 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
1087 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001088 self.assertEqual(subprocess.list2cmdline(['ab', '']),
1089 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001090
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001091 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001092 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +02001093 "import os; os.read(0, 1)"],
1094 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001095 self.addCleanup(p.stdin.close)
1096 self.assertIsNone(p.poll())
1097 os.write(p.stdin.fileno(), b'A')
1098 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001099 # Subsequent invocations should just return the returncode
1100 self.assertEqual(p.poll(), 0)
1101
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001102 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001103 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001104 self.assertEqual(p.wait(), 0)
1105 # Subsequent invocations should just return the returncode
1106 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001107
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001108 def test_wait_timeout(self):
1109 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001110 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001111 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001112 p.wait(timeout=0.0001)
1113 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -04001114 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
1115 # time to start.
1116 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001117
Peter Astrand738131d2004-11-30 21:04:45 +00001118 def test_invalid_bufsize(self):
1119 # an invalid type of the bufsize argument should raise
1120 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001121 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +00001122 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001123
Guido van Rossum46a05a72007-06-07 21:56:45 +00001124 def test_bufsize_is_none(self):
1125 # bufsize=None should be the same as bufsize=0.
1126 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
1127 self.assertEqual(p.wait(), 0)
1128 # Again with keyword arg
1129 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
1130 self.assertEqual(p.wait(), 0)
1131
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001132 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1133 # subprocess may deadlock with bufsize=1, see issue #21332
1134 with subprocess.Popen([sys.executable, "-c", "import sys;"
1135 "sys.stdout.write(sys.stdin.readline());"
1136 "sys.stdout.flush()"],
1137 stdin=subprocess.PIPE,
1138 stdout=subprocess.PIPE,
1139 stderr=subprocess.DEVNULL,
1140 bufsize=1,
1141 universal_newlines=universal_newlines) as p:
1142 p.stdin.write(line) # expect that it flushes the line in text mode
1143 os.close(p.stdin.fileno()) # close it without flushing the buffer
1144 read_line = p.stdout.readline()
Segev Finer4d385172017-08-18 16:18:13 +03001145 with support.SuppressCrashReport():
1146 try:
1147 p.stdin.close()
1148 except OSError:
1149 pass
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001150 p.stdin = None
1151 self.assertEqual(p.returncode, 0)
1152 self.assertEqual(read_line, expected)
1153
1154 def test_bufsize_equal_one_text_mode(self):
1155 # line is flushed in text mode with bufsize=1.
1156 # we should get the full line in return
1157 line = "line\n"
1158 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1159
1160 def test_bufsize_equal_one_binary_mode(self):
1161 # line is not flushed in binary mode with bufsize=1.
1162 # we should get empty response
1163 line = b'line' + os.linesep.encode() # assume ascii-based locale
Alexey Izbysheva2670562018-10-20 03:22:31 +03001164 with self.assertWarnsRegex(RuntimeWarning, 'line buffering'):
1165 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001166
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001167 def test_leaking_fds_on_error(self):
1168 # see bug #5179: Popen leaks file descriptors to PIPEs if
1169 # the child fails to execute; this will eventually exhaust
1170 # the maximum number of open fds. 1024 seems a very common
1171 # value for that limit, but Windows has 2048, so we loop
1172 # 1024 times (each call leaked two fds).
1173 for i in range(1024):
Victor Stinnerb31206a2018-01-25 19:06:05 +01001174 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02001175 subprocess.Popen(NONEXISTING_CMD,
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001176 stdout=subprocess.PIPE,
1177 stderr=subprocess.PIPE)
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001178
Victor Stinner9a83f652017-08-21 23:51:31 +02001179 def test_nonexisting_with_pipes(self):
1180 # bpo-30121: Popen with pipes must close properly pipes on error.
1181 # Previously, os.close() was called with a Windows handle which is not
1182 # a valid file descriptor.
1183 #
1184 # Run the test in a subprocess to control how the CRT reports errors
1185 # and to get stderr content.
1186 try:
1187 import msvcrt
1188 msvcrt.CrtSetReportMode
1189 except (AttributeError, ImportError):
1190 self.skipTest("need msvcrt.CrtSetReportMode")
1191
1192 code = textwrap.dedent(f"""
1193 import msvcrt
1194 import subprocess
1195
1196 cmd = {NONEXISTING_CMD!r}
1197
1198 for report_type in [msvcrt.CRT_WARN,
1199 msvcrt.CRT_ERROR,
1200 msvcrt.CRT_ASSERT]:
1201 msvcrt.CrtSetReportMode(report_type, msvcrt.CRTDBG_MODE_FILE)
1202 msvcrt.CrtSetReportFile(report_type, msvcrt.CRTDBG_FILE_STDERR)
1203
1204 try:
Zachary Ware55376462018-02-19 14:02:38 -06001205 subprocess.Popen(cmd,
Victor Stinner9a83f652017-08-21 23:51:31 +02001206 stdout=subprocess.PIPE,
1207 stderr=subprocess.PIPE)
1208 except OSError:
1209 pass
1210 """)
1211 cmd = [sys.executable, "-c", code]
1212 proc = subprocess.Popen(cmd,
1213 stderr=subprocess.PIPE,
1214 universal_newlines=True)
1215 with proc:
1216 stderr = proc.communicate()[1]
1217 self.assertEqual(stderr, "")
1218 self.assertEqual(proc.returncode, 0)
1219
Antoine Pitroua8392712013-08-30 23:38:13 +02001220 def test_double_close_on_error(self):
1221 # Issue #18851
1222 fds = []
1223 def open_fds():
1224 for i in range(20):
1225 fds.extend(os.pipe())
1226 time.sleep(0.001)
1227 t = threading.Thread(target=open_fds)
1228 t.start()
1229 try:
1230 with self.assertRaises(EnvironmentError):
Victor Stinner9a83f652017-08-21 23:51:31 +02001231 subprocess.Popen(NONEXISTING_CMD,
Antoine Pitroua8392712013-08-30 23:38:13 +02001232 stdin=subprocess.PIPE,
1233 stdout=subprocess.PIPE,
1234 stderr=subprocess.PIPE)
1235 finally:
1236 t.join()
1237 exc = None
1238 for fd in fds:
1239 # If a double close occurred, some of those fds will
1240 # already have been closed by mistake, and os.close()
1241 # here will raise.
1242 try:
1243 os.close(fd)
1244 except OSError as e:
1245 exc = e
1246 if exc is not None:
1247 raise exc
1248
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001249 def test_threadsafe_wait(self):
1250 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1251 proc = subprocess.Popen([sys.executable, '-c',
1252 'import time; time.sleep(12)'])
1253 self.assertEqual(proc.returncode, None)
1254 results = []
1255
1256 def kill_proc_timer_thread():
1257 results.append(('thread-start-poll-result', proc.poll()))
1258 # terminate it from the thread and wait for the result.
1259 proc.kill()
1260 proc.wait()
1261 results.append(('thread-after-kill-and-wait', proc.returncode))
1262 # this wait should be a no-op given the above.
1263 proc.wait()
1264 results.append(('thread-after-second-wait', proc.returncode))
1265
1266 # This is a timing sensitive test, the failure mode is
1267 # triggered when both the main thread and this thread are in
1268 # the wait() call at once. The delay here is to allow the
1269 # main thread to most likely be blocked in its wait() call.
1270 t = threading.Timer(0.2, kill_proc_timer_thread)
1271 t.start()
1272
Victor Stinner937ee9e2018-06-26 02:11:06 +02001273 if mswindows:
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001274 expected_errorcode = 1
1275 else:
1276 # Should be -9 because of the proc.kill() from the thread.
1277 expected_errorcode = -9
1278
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001279 # Wait for the process to finish; the thread should kill it
1280 # long before it finishes on its own. Supplying a timeout
1281 # triggers a different code path for better coverage.
1282 proc.wait(timeout=20)
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 wait from main thread")
1285
1286 # This should be a no-op with no change in returncode.
1287 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001288 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001289 msg="unexpected result in second main wait.")
1290
1291 t.join()
1292 # Ensure that all of the thread results are as expected.
1293 # When a race condition occurs in wait(), the returncode could
1294 # be set by the wrong thread that doesn't actually have it
1295 # leading to an incorrect value.
1296 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001297 ('thread-after-kill-and-wait', expected_errorcode),
1298 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001299 results)
1300
Victor Stinnerb3693582010-05-21 20:13:12 +00001301 def test_issue8780(self):
1302 # Ensure that stdout is inherited from the parent
1303 # if stdout=PIPE is not used
1304 code = ';'.join((
1305 'import subprocess, sys',
1306 'retcode = subprocess.call('
1307 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1308 'assert retcode == 0'))
1309 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001310 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001311
Tim Goldenaf5ac392010-08-06 13:03:56 +00001312 def test_handles_closed_on_exception(self):
1313 # If CreateProcess exits with an error, ensure the
1314 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001315 ifhandle, ifname = tempfile.mkstemp()
1316 ofhandle, ofname = tempfile.mkstemp()
1317 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001318 try:
1319 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1320 stderr=efhandle)
1321 except OSError:
1322 os.close(ifhandle)
1323 os.remove(ifname)
1324 os.close(ofhandle)
1325 os.remove(ofname)
1326 os.close(efhandle)
1327 os.remove(efname)
1328 self.assertFalse(os.path.exists(ifname))
1329 self.assertFalse(os.path.exists(ofname))
1330 self.assertFalse(os.path.exists(efname))
1331
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001332 def test_communicate_epipe(self):
1333 # Issue 10963: communicate() should hide EPIPE
1334 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1335 stdin=subprocess.PIPE,
1336 stdout=subprocess.PIPE,
1337 stderr=subprocess.PIPE)
1338 self.addCleanup(p.stdout.close)
1339 self.addCleanup(p.stderr.close)
1340 self.addCleanup(p.stdin.close)
1341 p.communicate(b"x" * 2**20)
1342
1343 def test_communicate_epipe_only_stdin(self):
1344 # Issue 10963: communicate() should hide EPIPE
1345 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1346 stdin=subprocess.PIPE)
1347 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001348 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001349 p.communicate(b"x" * 2**20)
1350
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001351 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1352 "Requires signal.SIGUSR1")
1353 @unittest.skipUnless(hasattr(os, 'kill'),
1354 "Requires os.kill")
1355 @unittest.skipUnless(hasattr(os, 'getppid'),
1356 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001357 def test_communicate_eintr(self):
1358 # Issue #12493: communicate() should handle EINTR
1359 def handler(signum, frame):
1360 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001361 old_handler = signal.signal(signal.SIGUSR1, handler)
1362 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001363
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001364 args = [sys.executable, "-c",
1365 'import os, signal;'
1366 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001367 for stream in ('stdout', 'stderr'):
1368 kw = {stream: subprocess.PIPE}
1369 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001370 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001371 process.communicate()
1372
Tim Peterse718f612004-10-12 21:51:32 +00001373
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001374 # This test is Linux-ish specific for simplicity to at least have
1375 # some coverage. It is not a platform specific bug.
1376 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1377 "Linux specific")
1378 def test_failed_child_execute_fd_leak(self):
1379 """Test for the fork() failure fd leak reported in issue16327."""
1380 fd_directory = '/proc/%d/fd' % os.getpid()
1381 fds_before_popen = os.listdir(fd_directory)
1382 with self.assertRaises(PopenTestException):
1383 PopenExecuteChildRaises(
1384 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
1385 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1386
1387 # NOTE: This test doesn't verify that the real _execute_child
1388 # does not close the file descriptors itself on the way out
1389 # during an exception. Code inspection has confirmed that.
1390
1391 fds_after_exception = os.listdir(fd_directory)
1392 self.assertEqual(fds_before_popen, fds_after_exception)
1393
Victor Stinner937ee9e2018-06-26 02:11:06 +02001394 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001395 def test_file_not_found_includes_filename(self):
1396 with self.assertRaises(FileNotFoundError) as c:
1397 subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args'])
1398 self.assertEqual(c.exception.filename, '/opt/nonexistent_binary')
1399
Victor Stinner937ee9e2018-06-26 02:11:06 +02001400 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001401 def test_file_not_found_with_bad_cwd(self):
1402 with self.assertRaises(FileNotFoundError) as c:
1403 subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory')
1404 self.assertEqual(c.exception.filename, '/some/nonexistent/directory')
1405
Gregory P. Smith6e730002015-04-14 16:14:25 -07001406
1407class RunFuncTestCase(BaseTestCase):
1408 def run_python(self, code, **kwargs):
1409 """Run Python code in a subprocess using subprocess.run"""
1410 argv = [sys.executable, "-c", code]
1411 return subprocess.run(argv, **kwargs)
1412
1413 def test_returncode(self):
1414 # call() function with sequence argument
1415 cp = self.run_python("import sys; sys.exit(47)")
1416 self.assertEqual(cp.returncode, 47)
1417 with self.assertRaises(subprocess.CalledProcessError):
1418 cp.check_returncode()
1419
1420 def test_check(self):
1421 with self.assertRaises(subprocess.CalledProcessError) as c:
1422 self.run_python("import sys; sys.exit(47)", check=True)
1423 self.assertEqual(c.exception.returncode, 47)
1424
1425 def test_check_zero(self):
1426 # check_returncode shouldn't raise when returncode is zero
1427 cp = self.run_python("import sys; sys.exit(0)", check=True)
1428 self.assertEqual(cp.returncode, 0)
1429
1430 def test_timeout(self):
1431 # run() function with timeout argument; we want to test that the child
1432 # process gets killed when the timeout expires. If the child isn't
1433 # killed, this call will deadlock since subprocess.run waits for the
1434 # child.
1435 with self.assertRaises(subprocess.TimeoutExpired):
1436 self.run_python("while True: pass", timeout=0.0001)
1437
1438 def test_capture_stdout(self):
1439 # capture stdout with zero return code
1440 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1441 self.assertIn(b'BDFL', cp.stdout)
1442
1443 def test_capture_stderr(self):
1444 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1445 stderr=subprocess.PIPE)
1446 self.assertIn(b'BDFL', cp.stderr)
1447
1448 def test_check_output_stdin_arg(self):
1449 # run() can be called with stdin set to a file
1450 tf = tempfile.TemporaryFile()
1451 self.addCleanup(tf.close)
1452 tf.write(b'pear')
1453 tf.seek(0)
1454 cp = self.run_python(
1455 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1456 stdin=tf, stdout=subprocess.PIPE)
1457 self.assertIn(b'PEAR', cp.stdout)
1458
1459 def test_check_output_input_arg(self):
1460 # check_output() can be called with input set to a string
1461 cp = self.run_python(
1462 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1463 input=b'pear', stdout=subprocess.PIPE)
1464 self.assertIn(b'PEAR', cp.stdout)
1465
1466 def test_check_output_stdin_with_input_arg(self):
1467 # run() refuses to accept 'stdin' with 'input'
1468 tf = tempfile.TemporaryFile()
1469 self.addCleanup(tf.close)
1470 tf.write(b'pear')
1471 tf.seek(0)
1472 with self.assertRaises(ValueError,
1473 msg="Expected ValueError when stdin and input args supplied.") as c:
1474 output = self.run_python("print('will not be run')",
1475 stdin=tf, input=b'hare')
1476 self.assertIn('stdin', c.exception.args[0])
1477 self.assertIn('input', c.exception.args[0])
1478
1479 def test_check_output_timeout(self):
1480 with self.assertRaises(subprocess.TimeoutExpired) as c:
1481 cp = self.run_python((
1482 "import sys, time\n"
1483 "sys.stdout.write('BDFL')\n"
1484 "sys.stdout.flush()\n"
1485 "time.sleep(3600)"),
1486 # Some heavily loaded buildbots (sparc Debian 3.x) require
1487 # this much time to start and print.
1488 timeout=3, stdout=subprocess.PIPE)
1489 self.assertEqual(c.exception.output, b'BDFL')
1490 # output is aliased to stdout
1491 self.assertEqual(c.exception.stdout, b'BDFL')
1492
1493 def test_run_kwargs(self):
1494 newenv = os.environ.copy()
1495 newenv["FRUIT"] = "banana"
1496 cp = self.run_python(('import sys, os;'
1497 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1498 env=newenv)
1499 self.assertEqual(cp.returncode, 33)
1500
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001501 def test_run_with_pathlike_path(self):
1502 # bpo-31961: test run(pathlike_object)
1503 # the name of a command that can be run without
Min ho Kimc4cacc82019-07-31 08:16:13 +10001504 # any arguments that exit fast
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001505 prog = 'tree.com' if mswindows else 'ls'
1506 path = shutil.which(prog)
1507 if path is None:
1508 self.skipTest(f'{prog} required for this test')
1509 path = FakePath(path)
1510 res = subprocess.run(path, stdout=subprocess.DEVNULL)
1511 self.assertEqual(res.returncode, 0)
1512 with self.assertRaises(TypeError):
1513 subprocess.run(path, stdout=subprocess.DEVNULL, shell=True)
1514
1515 def test_run_with_bytes_path_and_arguments(self):
1516 # bpo-31961: test run([bytes_object, b'additional arguments'])
1517 path = os.fsencode(sys.executable)
1518 args = [path, '-c', b'import sys; sys.exit(57)']
1519 res = subprocess.run(args)
1520 self.assertEqual(res.returncode, 57)
1521
1522 def test_run_with_pathlike_path_and_arguments(self):
1523 # bpo-31961: test run([pathlike_object, 'additional arguments'])
1524 path = FakePath(sys.executable)
1525 args = [path, '-c', 'import sys; sys.exit(57)']
1526 res = subprocess.run(args)
1527 self.assertEqual(res.returncode, 57)
1528
Bo Baylesce0f33d2018-01-30 00:40:39 -06001529 def test_capture_output(self):
1530 cp = self.run_python(("import sys;"
1531 "sys.stdout.write('BDFL'); "
1532 "sys.stderr.write('FLUFL')"),
1533 capture_output=True)
1534 self.assertIn(b'BDFL', cp.stdout)
1535 self.assertIn(b'FLUFL', cp.stderr)
1536
1537 def test_stdout_with_capture_output_arg(self):
1538 # run() refuses to accept 'stdout' with 'capture_output'
1539 tf = tempfile.TemporaryFile()
1540 self.addCleanup(tf.close)
1541 with self.assertRaises(ValueError,
1542 msg=("Expected ValueError when stdout and capture_output "
1543 "args supplied.")) as c:
1544 output = self.run_python("print('will not be run')",
1545 capture_output=True, stdout=tf)
1546 self.assertIn('stdout', c.exception.args[0])
1547 self.assertIn('capture_output', c.exception.args[0])
1548
1549 def test_stderr_with_capture_output_arg(self):
1550 # run() refuses to accept 'stderr' with 'capture_output'
1551 tf = tempfile.TemporaryFile()
1552 self.addCleanup(tf.close)
1553 with self.assertRaises(ValueError,
1554 msg=("Expected ValueError when stderr and capture_output "
1555 "args supplied.")) as c:
1556 output = self.run_python("print('will not be run')",
1557 capture_output=True, stderr=tf)
1558 self.assertIn('stderr', c.exception.args[0])
1559 self.assertIn('capture_output', c.exception.args[0])
1560
Gregory P. Smith580d2782019-09-11 04:23:05 -05001561 # This test _might_ wind up a bit fragile on loaded build+test machines
1562 # as it depends on the timing with wide enough margins for normal situations
1563 # but does assert that it happened "soon enough" to believe the right thing
1564 # happened.
1565 @unittest.skipIf(mswindows, "requires posix like 'sleep' shell command")
1566 def test_run_with_shell_timeout_and_capture_output(self):
1567 """Output capturing after a timeout mustn't hang forever on open filehandles."""
1568 before_secs = time.monotonic()
1569 try:
1570 subprocess.run('sleep 3', shell=True, timeout=0.1,
1571 capture_output=True) # New session unspecified.
1572 except subprocess.TimeoutExpired as exc:
1573 after_secs = time.monotonic()
1574 stacks = traceback.format_exc() # assertRaises doesn't give this.
1575 else:
1576 self.fail("TimeoutExpired not raised.")
1577 self.assertLess(after_secs - before_secs, 1.5,
1578 msg="TimeoutExpired was delayed! Bad traceback:\n```\n"
1579 f"{stacks}```")
1580
Gregory P. Smith6e730002015-04-14 16:14:25 -07001581
Victor Stinner937ee9e2018-06-26 02:11:06 +02001582@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001583class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001584
Gregory P. Smith5591b022012-10-10 03:34:47 -07001585 def setUp(self):
1586 super().setUp()
1587 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1588
1589 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001590 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001591 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001592 except OSError as e:
1593 # This avoids hard coding the errno value or the OS perror()
1594 # string and instead capture the exception that we want to see
1595 # below for comparison.
1596 desired_exception = e
1597 else:
Martin Pantereb995702016-07-28 01:11:04 +00001598 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001599 self._nonexistent_dir)
1600 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001601
Gregory P. Smith5591b022012-10-10 03:34:47 -07001602 def test_exception_cwd(self):
1603 """Test error in the child raised in the parent for a bad cwd."""
1604 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001605 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001606 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001607 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001608 except OSError as e:
1609 # Test that the child process chdir failure actually makes
1610 # it up to the parent process as the correct exception.
1611 self.assertEqual(desired_exception.errno, e.errno)
1612 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001613 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001614 else:
1615 self.fail("Expected OSError: %s" % desired_exception)
1616
Gregory P. Smith5591b022012-10-10 03:34:47 -07001617 def test_exception_bad_executable(self):
1618 """Test error in the child raised in the parent for a bad executable."""
1619 desired_exception = self._get_chdir_exception()
1620 try:
1621 p = subprocess.Popen([sys.executable, "-c", ""],
1622 executable=self._nonexistent_dir)
1623 except OSError as e:
1624 # Test that the child process exec failure actually makes
1625 # it up to the parent process as the correct exception.
1626 self.assertEqual(desired_exception.errno, e.errno)
1627 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001628 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001629 else:
1630 self.fail("Expected OSError: %s" % desired_exception)
1631
1632 def test_exception_bad_args_0(self):
1633 """Test error in the child raised in the parent for a bad args[0]."""
1634 desired_exception = self._get_chdir_exception()
1635 try:
1636 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1637 except OSError as e:
1638 # Test that the child process exec failure actually makes
1639 # it up to the parent process as the correct exception.
1640 self.assertEqual(desired_exception.errno, e.errno)
1641 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001642 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001643 else:
1644 self.fail("Expected OSError: %s" % desired_exception)
1645
Ammar Askar3fc499b2017-09-06 02:41:30 -04001646 # We mock the __del__ method for Popen in the next two tests
1647 # because it does cleanup based on the pid returned by fork_exec
1648 # along with issuing a resource warning if it still exists. Since
1649 # we don't actually spawn a process in these tests we can forego
1650 # the destructor. An alternative would be to set _child_created to
1651 # False before the destructor is called but there is no easy way
1652 # to do that
1653 class PopenNoDestructor(subprocess.Popen):
1654 def __del__(self):
1655 pass
1656
1657 @mock.patch("subprocess._posixsubprocess.fork_exec")
1658 def test_exception_errpipe_normal(self, fork_exec):
1659 """Test error passing done through errpipe_write in the good case"""
1660 def proper_error(*args):
1661 errpipe_write = args[13]
1662 # Write the hex for the error code EISDIR: 'is a directory'
1663 err_code = '{:x}'.format(errno.EISDIR).encode()
1664 os.write(errpipe_write, b"OSError:" + err_code + b":")
1665 return 0
1666
1667 fork_exec.side_effect = proper_error
1668
Victor Stinner11045c92017-10-05 06:32:53 -07001669 with mock.patch("subprocess.os.waitpid",
1670 side_effect=ChildProcessError):
1671 with self.assertRaises(IsADirectoryError):
1672 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001673
1674 @mock.patch("subprocess._posixsubprocess.fork_exec")
1675 def test_exception_errpipe_bad_data(self, fork_exec):
1676 """Test error passing done through errpipe_write where its not
1677 in the expected format"""
1678 error_data = b"\xFF\x00\xDE\xAD"
1679 def bad_error(*args):
1680 errpipe_write = args[13]
1681 # Anything can be in the pipe, no assumptions should
1682 # be made about its encoding, so we'll write some
1683 # arbitrary hex bytes to test it out
1684 os.write(errpipe_write, error_data)
1685 return 0
1686
1687 fork_exec.side_effect = bad_error
1688
Victor Stinner11045c92017-10-05 06:32:53 -07001689 with mock.patch("subprocess.os.waitpid",
1690 side_effect=ChildProcessError):
1691 with self.assertRaises(subprocess.SubprocessError) as e:
1692 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001693
1694 self.assertIn(repr(error_data), str(e.exception))
1695
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001696 @unittest.skipIf(not os.path.exists('/proc/self/status'),
1697 "need /proc/self/status")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001698 def test_restore_signals(self):
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001699 # Blindly assume that cat exists on systems with /proc/self/status...
1700 default_proc_status = subprocess.check_output(
1701 ['cat', '/proc/self/status'],
1702 restore_signals=False)
1703 for line in default_proc_status.splitlines():
1704 if line.startswith(b'SigIgn'):
1705 default_sig_ign_mask = line
1706 break
1707 else:
1708 self.skipTest("SigIgn not found in /proc/self/status.")
1709 restored_proc_status = subprocess.check_output(
1710 ['cat', '/proc/self/status'],
1711 restore_signals=True)
1712 for line in restored_proc_status.splitlines():
1713 if line.startswith(b'SigIgn'):
1714 restored_sig_ign_mask = line
1715 break
1716 self.assertNotEqual(default_sig_ign_mask, restored_sig_ign_mask,
1717 msg="restore_signals=True should've unblocked "
1718 "SIGPIPE and friends.")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001719
1720 def test_start_new_session(self):
1721 # For code coverage of calling setsid(). We don't care if we get an
1722 # EPERM error from it depending on the test execution environment, that
1723 # still indicates that it was called.
1724 try:
1725 output = subprocess.check_output(
Victor Stinner58840432019-06-14 19:31:43 +02001726 [sys.executable, "-c", "import os; print(os.getsid(0))"],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001727 start_new_session=True)
1728 except OSError as e:
1729 if e.errno != errno.EPERM:
1730 raise
1731 else:
Victor Stinner58840432019-06-14 19:31:43 +02001732 parent_sid = os.getsid(0)
1733 child_sid = int(output)
1734 self.assertNotEqual(parent_sid, child_sid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001735
1736 def test_run_abort(self):
1737 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001738 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001739 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001740 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001741 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001742 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001743
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001744 def test_CalledProcessError_str_signal(self):
1745 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
1746 error_string = str(err)
1747 # We're relying on the repr() of the signal.Signals intenum to provide
1748 # the word signal, the signal name and the numeric value.
1749 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00001750 # We're not being specific about the signal name as some signals have
1751 # multiple names and which name is revealed can vary.
1752 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001753 self.assertIn(str(signal.SIGABRT), error_string)
1754
1755 def test_CalledProcessError_str_unknown_signal(self):
1756 err = subprocess.CalledProcessError(-9876543, "fake cmd")
1757 error_string = str(err)
1758 self.assertIn("unknown signal 9876543.", error_string)
1759
1760 def test_CalledProcessError_str_non_zero(self):
1761 err = subprocess.CalledProcessError(2, "fake cmd")
1762 error_string = str(err)
1763 self.assertIn("non-zero exit status 2.", error_string)
1764
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001765 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001766 # DISCLAIMER: Setting environment variables is *not* a good use
1767 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001768 p = subprocess.Popen([sys.executable, "-c",
1769 'import sys,os;'
1770 'sys.stdout.write(os.getenv("FRUIT"))'],
1771 stdout=subprocess.PIPE,
1772 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02001773 with p:
1774 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001775
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001776 def test_preexec_exception(self):
1777 def raise_it():
1778 raise ValueError("What if two swallows carried a coconut?")
1779 try:
1780 p = subprocess.Popen([sys.executable, "-c", ""],
1781 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001782 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001783 self.assertTrue(
1784 subprocess._posixsubprocess,
1785 "Expected a ValueError from the preexec_fn")
1786 except ValueError as e:
1787 self.assertIn("coconut", e.args[0])
1788 else:
1789 self.fail("Exception raised by preexec_fn did not make it "
1790 "to the parent process.")
1791
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001792 class _TestExecuteChildPopen(subprocess.Popen):
1793 """Used to test behavior at the end of _execute_child."""
1794 def __init__(self, testcase, *args, **kwargs):
1795 self._testcase = testcase
1796 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001797
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001798 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001799 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001800 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001801 finally:
1802 # Open a bunch of file descriptors and verify that
1803 # none of them are the same as the ones the Popen
1804 # instance is using for stdin/stdout/stderr.
1805 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1806 for _ in range(8)]
1807 try:
1808 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001809 self._testcase.assertNotIn(
1810 fd, (self.stdin.fileno(), self.stdout.fileno(),
1811 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001812 msg="At least one fd was closed early.")
1813 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01001814 for fd in devzero_fds:
1815 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001816
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001817 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1818 def test_preexec_errpipe_does_not_double_close_pipes(self):
1819 """Issue16140: Don't double close pipes on preexec error."""
1820
1821 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08001822 raise subprocess.SubprocessError(
1823 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001824
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08001825 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001826 self._TestExecuteChildPopen(
1827 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001828 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1829 stderr=subprocess.PIPE, preexec_fn=raise_it)
1830
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001831 def test_preexec_gc_module_failure(self):
1832 # This tests the code that disables garbage collection if the child
1833 # process will execute any Python.
1834 def raise_runtime_error():
1835 raise RuntimeError("this shouldn't escape")
1836 enabled = gc.isenabled()
1837 orig_gc_disable = gc.disable
1838 orig_gc_isenabled = gc.isenabled
1839 try:
1840 gc.disable()
1841 self.assertFalse(gc.isenabled())
1842 subprocess.call([sys.executable, '-c', ''],
1843 preexec_fn=lambda: None)
1844 self.assertFalse(gc.isenabled(),
1845 "Popen enabled gc when it shouldn't.")
1846
1847 gc.enable()
1848 self.assertTrue(gc.isenabled())
1849 subprocess.call([sys.executable, '-c', ''],
1850 preexec_fn=lambda: None)
1851 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1852
1853 gc.disable = raise_runtime_error
1854 self.assertRaises(RuntimeError, subprocess.Popen,
1855 [sys.executable, '-c', ''],
1856 preexec_fn=lambda: None)
1857
1858 del gc.isenabled # force an AttributeError
1859 self.assertRaises(AttributeError, subprocess.Popen,
1860 [sys.executable, '-c', ''],
1861 preexec_fn=lambda: None)
1862 finally:
1863 gc.disable = orig_gc_disable
1864 gc.isenabled = orig_gc_isenabled
1865 if not enabled:
1866 gc.disable()
1867
Martin Panterf7fdbda2015-12-05 09:51:52 +00001868 @unittest.skipIf(
1869 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00001870 def test_preexec_fork_failure(self):
1871 # The internal code did not preserve the previous exception when
1872 # re-enabling garbage collection
1873 try:
1874 from resource import getrlimit, setrlimit, RLIMIT_NPROC
1875 except ImportError as err:
1876 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
1877 limits = getrlimit(RLIMIT_NPROC)
1878 [_, hard] = limits
1879 setrlimit(RLIMIT_NPROC, (0, hard))
1880 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00001881 try:
Martin Panterafdd5132015-11-30 02:21:41 +00001882 subprocess.call([sys.executable, '-c', ''],
1883 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00001884 except BlockingIOError:
1885 # Forking should raise EAGAIN, translated to BlockingIOError
1886 pass
1887 else:
1888 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00001889
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001890 def test_args_string(self):
1891 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03001892 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001893 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001894 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001895 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001896 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1897 sys.executable)
1898 os.chmod(fname, 0o700)
1899 p = subprocess.Popen(fname)
1900 p.wait()
1901 os.remove(fname)
1902 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001903
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001904 def test_invalid_args(self):
1905 # invalid arguments should raise ValueError
1906 self.assertRaises(ValueError, subprocess.call,
1907 [sys.executable, "-c",
1908 "import sys; sys.exit(47)"],
1909 startupinfo=47)
1910 self.assertRaises(ValueError, subprocess.call,
1911 [sys.executable, "-c",
1912 "import sys; sys.exit(47)"],
1913 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001914
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001915 def test_shell_sequence(self):
1916 # Run command through the shell (sequence)
1917 newenv = os.environ.copy()
1918 newenv["FRUIT"] = "apple"
1919 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1920 stdout=subprocess.PIPE,
1921 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001922 with p:
1923 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001924
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001925 def test_shell_string(self):
1926 # Run command through the shell (string)
1927 newenv = os.environ.copy()
1928 newenv["FRUIT"] = "apple"
1929 p = subprocess.Popen("echo $FRUIT", shell=1,
1930 stdout=subprocess.PIPE,
1931 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001932 with p:
1933 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001934
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001935 def test_call_string(self):
1936 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03001937 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001938 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001939 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001940 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001941 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1942 sys.executable)
1943 os.chmod(fname, 0o700)
1944 rc = subprocess.call(fname)
1945 os.remove(fname)
1946 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001947
Stefan Krah9542cc62010-07-19 14:20:53 +00001948 def test_specific_shell(self):
1949 # Issue #9265: Incorrect name passed as arg[0].
1950 shells = []
1951 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1952 for name in ['bash', 'ksh']:
1953 sh = os.path.join(prefix, name)
1954 if os.path.isfile(sh):
1955 shells.append(sh)
1956 if not shells: # Will probably work for any shell but csh.
1957 self.skipTest("bash or ksh required for this test")
1958 sh = '/bin/sh'
1959 if os.path.isfile(sh) and not os.path.islink(sh):
1960 # Test will fail if /bin/sh is a symlink to csh.
1961 shells.append(sh)
1962 for sh in shells:
1963 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1964 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02001965 with p:
1966 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00001967
Florent Xicluna4886d242010-03-08 13:27:26 +00001968 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001969 # Do not inherit file handles from the parent.
1970 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07001971 # Also set the SIGINT handler to the default to make sure it's not
1972 # being ignored (some tests rely on that.)
1973 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
1974 try:
1975 p = subprocess.Popen([sys.executable, "-c", """if 1:
1976 import sys, time
1977 sys.stdout.write('x\\n')
1978 sys.stdout.flush()
1979 time.sleep(30)
1980 """],
1981 close_fds=True,
1982 stdin=subprocess.PIPE,
1983 stdout=subprocess.PIPE,
1984 stderr=subprocess.PIPE)
1985 finally:
1986 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001987 # Wait for the interpreter to be completely initialized before
1988 # sending any signal.
1989 p.stdout.read(1)
1990 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001991 return p
1992
Charles-François Natali53221e32013-01-12 16:52:20 +01001993 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1994 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001995 def _kill_dead_process(self, method, *args):
1996 # Do not inherit file handles from the parent.
1997 # It should fix failures on some platforms.
1998 p = subprocess.Popen([sys.executable, "-c", """if 1:
1999 import sys, time
2000 sys.stdout.write('x\\n')
2001 sys.stdout.flush()
2002 """],
2003 close_fds=True,
2004 stdin=subprocess.PIPE,
2005 stdout=subprocess.PIPE,
2006 stderr=subprocess.PIPE)
2007 # Wait for the interpreter to be completely initialized before
2008 # sending any signal.
2009 p.stdout.read(1)
2010 # The process should end after this
2011 time.sleep(1)
2012 # This shouldn't raise even though the child is now dead
2013 getattr(p, method)(*args)
2014 p.communicate()
2015
Florent Xicluna4886d242010-03-08 13:27:26 +00002016 def test_send_signal(self):
2017 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00002018 _, stderr = p.communicate()
2019 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002020 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00002021
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002022 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002023 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00002024 _, stderr = p.communicate()
2025 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002026 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00002027
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002028 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002029 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00002030 _, stderr = p.communicate()
2031 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002032 self.assertEqual(p.wait(), -signal.SIGTERM)
2033
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002034 def test_send_signal_dead(self):
2035 # Sending a signal to a dead process
2036 self._kill_dead_process('send_signal', signal.SIGINT)
2037
2038 def test_kill_dead(self):
2039 # Killing a dead process
2040 self._kill_dead_process('kill')
2041
2042 def test_terminate_dead(self):
2043 # Terminating a dead process
2044 self._kill_dead_process('terminate')
2045
Victor Stinnerdaf45552013-08-28 00:53:59 +02002046 def _save_fds(self, save_fds):
2047 fds = []
2048 for fd in save_fds:
2049 inheritable = os.get_inheritable(fd)
2050 saved = os.dup(fd)
2051 fds.append((fd, saved, inheritable))
2052 return fds
2053
2054 def _restore_fds(self, fds):
2055 for fd, saved, inheritable in fds:
2056 os.dup2(saved, fd, inheritable=inheritable)
2057 os.close(saved)
2058
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002059 def check_close_std_fds(self, fds):
2060 # Issue #9905: test that subprocess pipes still work properly with
2061 # some standard fds closed
2062 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02002063 saved_fds = self._save_fds(fds)
2064 for fd, saved, inheritable in saved_fds:
2065 if fd == 0:
2066 stdin = saved
2067 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002068 try:
2069 for fd in fds:
2070 os.close(fd)
2071 out, err = subprocess.Popen([sys.executable, "-c",
2072 'import sys;'
2073 'sys.stdout.write("apple");'
2074 'sys.stdout.flush();'
2075 'sys.stderr.write("orange")'],
2076 stdin=stdin,
2077 stdout=subprocess.PIPE,
2078 stderr=subprocess.PIPE).communicate()
2079 err = support.strip_python_stderr(err)
2080 self.assertEqual((out, err), (b'apple', b'orange'))
2081 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002082 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002083
2084 def test_close_fd_0(self):
2085 self.check_close_std_fds([0])
2086
2087 def test_close_fd_1(self):
2088 self.check_close_std_fds([1])
2089
2090 def test_close_fd_2(self):
2091 self.check_close_std_fds([2])
2092
2093 def test_close_fds_0_1(self):
2094 self.check_close_std_fds([0, 1])
2095
2096 def test_close_fds_0_2(self):
2097 self.check_close_std_fds([0, 2])
2098
2099 def test_close_fds_1_2(self):
2100 self.check_close_std_fds([1, 2])
2101
2102 def test_close_fds_0_1_2(self):
2103 # Issue #10806: test that subprocess pipes still work properly with
2104 # all standard fds closed.
2105 self.check_close_std_fds([0, 1, 2])
2106
Gregory P. Smith53dd8162013-12-01 16:03:24 -08002107 def test_small_errpipe_write_fd(self):
2108 """Issue #15798: Popen should work when stdio fds are available."""
2109 new_stdin = os.dup(0)
2110 new_stdout = os.dup(1)
2111 try:
2112 os.close(0)
2113 os.close(1)
2114
2115 # Side test: if errpipe_write fails to have its CLOEXEC
2116 # flag set this should cause the parent to think the exec
2117 # failed. Extremely unlikely: everyone supports CLOEXEC.
2118 subprocess.Popen([
2119 sys.executable, "-c",
2120 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
2121 finally:
2122 # Restore original stdin and stdout
2123 os.dup2(new_stdin, 0)
2124 os.dup2(new_stdout, 1)
2125 os.close(new_stdin)
2126 os.close(new_stdout)
2127
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002128 def test_remapping_std_fds(self):
2129 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002130 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002131 try:
2132 temp_fds = [fd for fd, fname in temps]
2133
2134 # unlink the files -- we won't need to reopen them
2135 for fd, fname in temps:
2136 os.unlink(fname)
2137
2138 # write some data to what will become stdin, and rewind
2139 os.write(temp_fds[1], b"STDIN")
2140 os.lseek(temp_fds[1], 0, 0)
2141
2142 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02002143 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002144 try:
2145 # duplicate the file objects over the standard fd's
2146 for fd, temp_fd in enumerate(temp_fds):
2147 os.dup2(temp_fd, fd)
2148
2149 # now use those files in the "wrong" order, so that subprocess
2150 # has to rearrange them in the child
2151 p = subprocess.Popen([sys.executable, "-c",
2152 'import sys; got = sys.stdin.read();'
2153 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2154 stdin=temp_fds[1],
2155 stdout=temp_fds[2],
2156 stderr=temp_fds[0])
2157 p.wait()
2158 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002159 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002160
2161 for fd in temp_fds:
2162 os.lseek(fd, 0, 0)
2163
2164 out = os.read(temp_fds[2], 1024)
2165 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
2166 self.assertEqual(out, b"got STDIN")
2167 self.assertEqual(err, b"err")
2168
2169 finally:
2170 for fd in temp_fds:
2171 os.close(fd)
2172
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002173 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
2174 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002175 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002176 temp_fds = [fd for fd, fname in temps]
2177 try:
2178 # unlink the files -- we won't need to reopen them
2179 for fd, fname in temps:
2180 os.unlink(fname)
2181
2182 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02002183 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002184 try:
2185 # duplicate the temp files over the standard fd's 0, 1, 2
2186 for fd, temp_fd in enumerate(temp_fds):
2187 os.dup2(temp_fd, fd)
2188
2189 # write some data to what will become stdin, and rewind
2190 os.write(stdin_no, b"STDIN")
2191 os.lseek(stdin_no, 0, 0)
2192
2193 # now use those files in the given order, so that subprocess
2194 # has to rearrange them in the child
2195 p = subprocess.Popen([sys.executable, "-c",
2196 'import sys; got = sys.stdin.read();'
2197 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2198 stdin=stdin_no,
2199 stdout=stdout_no,
2200 stderr=stderr_no)
2201 p.wait()
2202
2203 for fd in temp_fds:
2204 os.lseek(fd, 0, 0)
2205
2206 out = os.read(stdout_no, 1024)
2207 err = support.strip_python_stderr(os.read(stderr_no, 1024))
2208 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002209 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002210
2211 self.assertEqual(out, b"got STDIN")
2212 self.assertEqual(err, b"err")
2213
2214 finally:
2215 for fd in temp_fds:
2216 os.close(fd)
2217
2218 # When duping fds, if there arises a situation where one of the fds is
2219 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
2220 # This tests all combinations of this.
2221 def test_swap_fds(self):
2222 self.check_swap_fds(0, 1, 2)
2223 self.check_swap_fds(0, 2, 1)
2224 self.check_swap_fds(1, 0, 2)
2225 self.check_swap_fds(1, 2, 0)
2226 self.check_swap_fds(2, 0, 1)
2227 self.check_swap_fds(2, 1, 0)
2228
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +03002229 def _check_swap_std_fds_with_one_closed(self, from_fds, to_fds):
2230 saved_fds = self._save_fds(range(3))
2231 try:
2232 for from_fd in from_fds:
2233 with tempfile.TemporaryFile() as f:
2234 os.dup2(f.fileno(), from_fd)
2235
2236 fd_to_close = (set(range(3)) - set(from_fds)).pop()
2237 os.close(fd_to_close)
2238
2239 arg_names = ['stdin', 'stdout', 'stderr']
2240 kwargs = {}
2241 for from_fd, to_fd in zip(from_fds, to_fds):
2242 kwargs[arg_names[to_fd]] = from_fd
2243
2244 code = textwrap.dedent(r'''
2245 import os, sys
2246 skipped_fd = int(sys.argv[1])
2247 for fd in range(3):
2248 if fd != skipped_fd:
2249 os.write(fd, str(fd).encode('ascii'))
2250 ''')
2251
2252 skipped_fd = (set(range(3)) - set(to_fds)).pop()
2253
2254 rc = subprocess.call([sys.executable, '-c', code, str(skipped_fd)],
2255 **kwargs)
2256 self.assertEqual(rc, 0)
2257
2258 for from_fd, to_fd in zip(from_fds, to_fds):
2259 os.lseek(from_fd, 0, os.SEEK_SET)
2260 read_bytes = os.read(from_fd, 1024)
2261 read_fds = list(map(int, read_bytes.decode('ascii')))
2262 msg = textwrap.dedent(f"""
2263 When testing {from_fds} to {to_fds} redirection,
2264 parent descriptor {from_fd} got redirected
2265 to descriptor(s) {read_fds} instead of descriptor {to_fd}.
2266 """)
2267 self.assertEqual([to_fd], read_fds, msg)
2268 finally:
2269 self._restore_fds(saved_fds)
2270
2271 # Check that subprocess can remap std fds correctly even
2272 # if one of them is closed (#32844).
2273 def test_swap_std_fds_with_one_closed(self):
2274 for from_fds in itertools.combinations(range(3), 2):
2275 for to_fds in itertools.permutations(range(3), 2):
2276 self._check_swap_std_fds_with_one_closed(from_fds, to_fds)
2277
Victor Stinner13bb71c2010-04-23 21:41:56 +00002278 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00002279 def prepare():
2280 raise ValueError("surrogate:\uDCff")
2281
2282 try:
2283 subprocess.call(
2284 [sys.executable, "-c", "pass"],
2285 preexec_fn=prepare)
2286 except ValueError as err:
2287 # Pure Python implementations keeps the message
2288 self.assertIsNone(subprocess._posixsubprocess)
2289 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002290 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00002291 # _posixsubprocess uses a default message
2292 self.assertIsNotNone(subprocess._posixsubprocess)
2293 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
2294 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002295 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00002296
Victor Stinner13bb71c2010-04-23 21:41:56 +00002297 def test_undecodable_env(self):
2298 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01002299 encoded_value = value.encode("ascii", "surrogateescape")
2300
Victor Stinner13bb71c2010-04-23 21:41:56 +00002301 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002302 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002303 env = os.environ.copy()
2304 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01002305 # Use C locale to get ASCII for the locale encoding to force
Michael Felt89d79b12018-08-26 19:29:36 +02002306 # surrogate-escaping of \xFF in the child process
Victor Stinnerebc78d22010-10-14 10:38:17 +00002307 env['LC_ALL'] = 'C'
Michael Felt89d79b12018-08-26 19:29:36 +02002308 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002309 stdout = subprocess.check_output(
2310 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002311 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002312 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002313 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002314
2315 # test bytes
2316 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002317 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002318 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01002319 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002320 stdout = subprocess.check_output(
2321 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002322 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002323 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002324 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002325
Victor Stinnerb745a742010-05-18 17:17:23 +00002326 def test_bytes_program(self):
2327 abs_program = os.fsencode(sys.executable)
2328 path, program = os.path.split(sys.executable)
2329 program = os.fsencode(program)
2330
2331 # absolute bytes path
2332 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00002333 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002334
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002335 # absolute bytes path as a string
2336 cmd = b"'" + abs_program + b"' -c pass"
2337 exitcode = subprocess.call(cmd, shell=True)
2338 self.assertEqual(exitcode, 0)
2339
Victor Stinnerb745a742010-05-18 17:17:23 +00002340 # bytes program, unicode PATH
2341 env = os.environ.copy()
2342 env["PATH"] = path
2343 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002344 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002345
2346 # bytes program, bytes PATH
2347 envb = os.environb.copy()
2348 envb[b"PATH"] = os.fsencode(path)
2349 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002350 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002351
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002352 def test_pipe_cloexec(self):
2353 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2354 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2355
2356 p1 = subprocess.Popen([sys.executable, sleeper],
2357 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2358 stderr=subprocess.PIPE, close_fds=False)
2359
2360 self.addCleanup(p1.communicate, b'')
2361
2362 p2 = subprocess.Popen([sys.executable, fd_status],
2363 stdout=subprocess.PIPE, close_fds=False)
2364
2365 output, error = p2.communicate()
2366 result_fds = set(map(int, output.split(b',')))
2367 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2368 p1.stderr.fileno()])
2369
2370 self.assertFalse(result_fds & unwanted_fds,
2371 "Expected no fds from %r to be open in child, "
2372 "found %r" %
2373 (unwanted_fds, result_fds & unwanted_fds))
2374
2375 def test_pipe_cloexec_real_tools(self):
2376 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2377 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2378
2379 subdata = b'zxcvbn'
2380 data = subdata * 4 + b'\n'
2381
2382 p1 = subprocess.Popen([sys.executable, qcat],
2383 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2384 close_fds=False)
2385
2386 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2387 stdin=p1.stdout, stdout=subprocess.PIPE,
2388 close_fds=False)
2389
2390 self.addCleanup(p1.wait)
2391 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002392 def kill_p1():
2393 try:
2394 p1.terminate()
2395 except ProcessLookupError:
2396 pass
2397 def kill_p2():
2398 try:
2399 p2.terminate()
2400 except ProcessLookupError:
2401 pass
2402 self.addCleanup(kill_p1)
2403 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002404
2405 p1.stdin.write(data)
2406 p1.stdin.close()
2407
2408 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2409
2410 self.assertTrue(readfiles, "The child hung")
2411 self.assertEqual(p2.stdout.read(), data)
2412
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002413 p1.stdout.close()
2414 p2.stdout.close()
2415
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002416 def test_close_fds(self):
2417 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2418
2419 fds = os.pipe()
2420 self.addCleanup(os.close, fds[0])
2421 self.addCleanup(os.close, fds[1])
2422
2423 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002424 # add a bunch more fds
2425 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002426 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002427 self.addCleanup(os.close, fd)
2428 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002429
Victor Stinnerdaf45552013-08-28 00:53:59 +02002430 for fd in open_fds:
2431 os.set_inheritable(fd, True)
2432
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002433 p = subprocess.Popen([sys.executable, fd_status],
2434 stdout=subprocess.PIPE, close_fds=False)
2435 output, ignored = p.communicate()
2436 remaining_fds = set(map(int, output.split(b',')))
2437
2438 self.assertEqual(remaining_fds & open_fds, open_fds,
2439 "Some fds were closed")
2440
2441 p = subprocess.Popen([sys.executable, fd_status],
2442 stdout=subprocess.PIPE, close_fds=True)
2443 output, ignored = p.communicate()
2444 remaining_fds = set(map(int, output.split(b',')))
2445
2446 self.assertFalse(remaining_fds & open_fds,
2447 "Some fds were left open")
2448 self.assertIn(1, remaining_fds, "Subprocess failed")
2449
Gregory P. Smith8facece2012-01-21 14:01:08 -08002450 # Keep some of the fd's we opened open in the subprocess.
2451 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2452 fds_to_keep = set(open_fds.pop() for _ in range(8))
2453 p = subprocess.Popen([sys.executable, fd_status],
2454 stdout=subprocess.PIPE, close_fds=True,
izbyshev2d8f0632017-12-19 03:26:49 +07002455 pass_fds=fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002456 output, ignored = p.communicate()
2457 remaining_fds = set(map(int, output.split(b',')))
2458
izbyshev2d8f0632017-12-19 03:26:49 +07002459 self.assertFalse((remaining_fds - fds_to_keep) & open_fds,
Gregory P. Smith8facece2012-01-21 14:01:08 -08002460 "Some fds not in pass_fds were left open")
2461 self.assertIn(1, remaining_fds, "Subprocess failed")
2462
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002463
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002464 @unittest.skipIf(sys.platform.startswith("freebsd") and
2465 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2466 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002467 def test_close_fds_when_max_fd_is_lowered(self):
2468 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2469 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2470
Gregory P. Smith634aa682014-06-15 17:51:04 -07002471 # This launches the meat of the test in a child process to
2472 # avoid messing with the larger unittest processes maximum
2473 # number of file descriptors.
2474 # This process launches:
2475 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2476 # a bunch of high open fds above the new lower rlimit.
2477 # Those are reported via stdout before launching a new
2478 # process with close_fds=False to run the actual test:
2479 # +--> The TEST: This one launches a fd_status.py
2480 # subprocess with close_fds=True so we can find out if
2481 # any of the fds above the lowered rlimit are still open.
2482 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2483 '''
2484 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002485 open_fds = set()
2486 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002487 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002488 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002489 open_fds.add(fd)
2490
2491 # Leave a two pairs of low ones available for use by the
2492 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002493 # We also leave 10 more open as some Python buildbots run into
2494 # "too many open files" errors during the test if we do not.
2495 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002496 os.close(fd)
2497 open_fds.remove(fd)
2498
2499 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002500 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002501 os.set_inheritable(fd, True)
2502
2503 max_fd_open = max(open_fds)
2504
Gregory P. Smith634aa682014-06-15 17:51:04 -07002505 # Communicate the open_fds to the parent unittest.TestCase process.
2506 print(','.join(map(str, sorted(open_fds))))
2507 sys.stdout.flush()
2508
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002509 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2510 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002511 # 29 is lower than the highest fds we are leaving open.
2512 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002513 # Launch a new Python interpreter with our low fd rlim_cur that
2514 # inherits open fds above that limit. It then uses subprocess
2515 # with close_fds=True to get a report of open fds in the child.
2516 # An explicit list of fds to check is passed to fd_status.py as
2517 # letting fd_status rely on its default logic would miss the
2518 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002519 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002520 [sys.executable, '-c',
2521 textwrap.dedent("""
2522 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002523 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002524 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002525 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002526 """.format(max_fd=max_fd_open+1))],
2527 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002528 finally:
2529 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002530 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002531
2532 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002533 output_lines = output.splitlines()
2534 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002535 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002536 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2537 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002538
Gregory P. Smith634aa682014-06-15 17:51:04 -07002539 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002540 msg="Some fds were left open.")
2541
2542
Victor Stinner88701e22011-06-01 13:13:04 +02002543 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2544 # descriptor of a pipe closed in the parent process is valid in the
2545 # child process according to fstat(), but the mode of the file
2546 # descriptor is invalid, and read or write raise an error.
2547 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002548 def test_pass_fds(self):
2549 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2550
2551 open_fds = set()
2552
2553 for x in range(5):
2554 fds = os.pipe()
2555 self.addCleanup(os.close, fds[0])
2556 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002557 os.set_inheritable(fds[0], True)
2558 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002559 open_fds.update(fds)
2560
2561 for fd in open_fds:
2562 p = subprocess.Popen([sys.executable, fd_status],
2563 stdout=subprocess.PIPE, close_fds=True,
2564 pass_fds=(fd, ))
2565 output, ignored = p.communicate()
2566
2567 remaining_fds = set(map(int, output.split(b',')))
2568 to_be_closed = open_fds - {fd}
2569
2570 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2571 self.assertFalse(remaining_fds & to_be_closed,
2572 "fd to be closed passed")
2573
2574 # pass_fds overrides close_fds with a warning.
2575 with self.assertWarns(RuntimeWarning) as context:
2576 self.assertFalse(subprocess.call(
2577 [sys.executable, "-c", "import sys; sys.exit(0)"],
2578 close_fds=False, pass_fds=(fd, )))
2579 self.assertIn('overriding close_fds', str(context.warning))
2580
Victor Stinnerdaf45552013-08-28 00:53:59 +02002581 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002582 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002583
2584 inheritable, non_inheritable = os.pipe()
2585 self.addCleanup(os.close, inheritable)
2586 self.addCleanup(os.close, non_inheritable)
2587 os.set_inheritable(inheritable, True)
2588 os.set_inheritable(non_inheritable, False)
2589 pass_fds = (inheritable, non_inheritable)
2590 args = [sys.executable, script]
2591 args += list(map(str, pass_fds))
2592
2593 p = subprocess.Popen(args,
2594 stdout=subprocess.PIPE, close_fds=True,
2595 pass_fds=pass_fds)
2596 output, ignored = p.communicate()
2597 fds = set(map(int, output.split(b',')))
2598
2599 # the inheritable file descriptor must be inherited, so its inheritable
2600 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002601 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002602
2603 # inheritable flag must not be changed in the parent process
2604 self.assertEqual(os.get_inheritable(inheritable), True)
2605 self.assertEqual(os.get_inheritable(non_inheritable), False)
2606
Gregory P. Smithce344102018-09-10 17:46:22 -07002607
2608 # bpo-32270: Ensure that descriptors specified in pass_fds
2609 # are inherited even if they are used in redirections.
2610 # Contributed by @izbyshev.
2611 def test_pass_fds_redirected(self):
2612 """Regression test for https://bugs.python.org/issue32270."""
2613 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2614 pass_fds = []
2615 for _ in range(2):
2616 fd = os.open(os.devnull, os.O_RDWR)
2617 self.addCleanup(os.close, fd)
2618 pass_fds.append(fd)
2619
2620 stdout_r, stdout_w = os.pipe()
2621 self.addCleanup(os.close, stdout_r)
2622 self.addCleanup(os.close, stdout_w)
2623 pass_fds.insert(1, stdout_w)
2624
2625 with subprocess.Popen([sys.executable, fd_status],
2626 stdin=pass_fds[0],
2627 stdout=pass_fds[1],
2628 stderr=pass_fds[2],
2629 close_fds=True,
2630 pass_fds=pass_fds):
2631 output = os.read(stdout_r, 1024)
2632 fds = {int(num) for num in output.split(b',')}
2633
2634 self.assertEqual(fds, {0, 1, 2} | frozenset(pass_fds), f"output={output!a}")
2635
2636
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002637 def test_stdout_stdin_are_single_inout_fd(self):
2638 with io.open(os.devnull, "r+") as inout:
2639 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2640 stdout=inout, stdin=inout)
2641 p.wait()
2642
2643 def test_stdout_stderr_are_single_inout_fd(self):
2644 with io.open(os.devnull, "r+") as inout:
2645 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2646 stdout=inout, stderr=inout)
2647 p.wait()
2648
2649 def test_stderr_stdin_are_single_inout_fd(self):
2650 with io.open(os.devnull, "r+") as inout:
2651 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2652 stderr=inout, stdin=inout)
2653 p.wait()
2654
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002655 def test_wait_when_sigchild_ignored(self):
2656 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2657 sigchild_ignore = support.findfile("sigchild_ignore.py",
2658 subdir="subprocessdata")
2659 p = subprocess.Popen([sys.executable, sigchild_ignore],
2660 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2661 stdout, stderr = p.communicate()
2662 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002663 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002664 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002665
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002666 def test_select_unbuffered(self):
2667 # Issue #11459: bufsize=0 should really set the pipes as
2668 # unbuffered (and therefore let select() work properly).
2669 select = support.import_module("select")
2670 p = subprocess.Popen([sys.executable, "-c",
2671 'import sys;'
2672 'sys.stdout.write("apple")'],
2673 stdout=subprocess.PIPE,
2674 bufsize=0)
2675 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002676 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002677 try:
2678 self.assertEqual(f.read(4), b"appl")
2679 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2680 finally:
2681 p.wait()
2682
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002683 def test_zombie_fast_process_del(self):
2684 # Issue #12650: on Unix, if Popen.__del__() was called before the
2685 # process exited, it wouldn't be added to subprocess._active, and would
2686 # remain a zombie.
2687 # spawn a Popen, and delete its reference before it exits
2688 p = subprocess.Popen([sys.executable, "-c",
2689 'import sys, time;'
2690 'time.sleep(0.2)'],
2691 stdout=subprocess.PIPE,
2692 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002693 self.addCleanup(p.stdout.close)
2694 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002695 ident = id(p)
2696 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002697 with support.check_warnings(('', ResourceWarning)):
2698 p = None
2699
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002700 if mswindows:
2701 # subprocess._active is not used on Windows and is set to None.
2702 self.assertIsNone(subprocess._active)
2703 else:
2704 # check that p is in the active processes list
2705 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002706
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002707 def test_leak_fast_process_del_killed(self):
2708 # Issue #12650: on Unix, if Popen.__del__() was called before the
2709 # process exited, and the process got killed by a signal, it would never
2710 # be removed from subprocess._active, which triggered a FD and memory
2711 # leak.
2712 # spawn a Popen, delete its reference and kill it
2713 p = subprocess.Popen([sys.executable, "-c",
2714 'import time;'
2715 'time.sleep(3)'],
2716 stdout=subprocess.PIPE,
2717 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002718 self.addCleanup(p.stdout.close)
2719 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002720 ident = id(p)
2721 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002722 with support.check_warnings(('', ResourceWarning)):
2723 p = None
2724
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002725 os.kill(pid, signal.SIGKILL)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002726 if mswindows:
2727 # subprocess._active is not used on Windows and is set to None.
2728 self.assertIsNone(subprocess._active)
2729 else:
2730 # check that p is in the active processes list
2731 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002732
2733 # let some time for the process to exit, and create a new Popen: this
2734 # should trigger the wait() of p
2735 time.sleep(0.2)
Victor Stinnerb31206a2018-01-25 19:06:05 +01002736 with self.assertRaises(OSError):
Victor Stinner9a83f652017-08-21 23:51:31 +02002737 with subprocess.Popen(NONEXISTING_CMD,
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002738 stdout=subprocess.PIPE,
2739 stderr=subprocess.PIPE) as proc:
2740 pass
2741 # p should have been wait()ed on, and removed from the _active list
2742 self.assertRaises(OSError, os.waitpid, pid, 0)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002743 if mswindows:
2744 # subprocess._active is not used on Windows and is set to None.
2745 self.assertIsNone(subprocess._active)
2746 else:
2747 self.assertNotIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002748
Charles-François Natali249cdc32013-08-25 18:24:45 +02002749 def test_close_fds_after_preexec(self):
2750 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2751
2752 # this FD is used as dup2() target by preexec_fn, and should be closed
2753 # in the child process
2754 fd = os.dup(1)
2755 self.addCleanup(os.close, fd)
2756
2757 p = subprocess.Popen([sys.executable, fd_status],
2758 stdout=subprocess.PIPE, close_fds=True,
2759 preexec_fn=lambda: os.dup2(1, fd))
2760 output, ignored = p.communicate()
2761
2762 remaining_fds = set(map(int, output.split(b',')))
2763
2764 self.assertNotIn(fd, remaining_fds)
2765
Victor Stinner8f437aa2014-10-05 17:25:19 +02002766 @support.cpython_only
2767 def test_fork_exec(self):
2768 # Issue #22290: fork_exec() must not crash on memory allocation failure
2769 # or other errors
2770 import _posixsubprocess
2771 gc_enabled = gc.isenabled()
2772 try:
2773 # Use a preexec function and enable the garbage collector
2774 # to force fork_exec() to re-enable the garbage collector
2775 # on error.
2776 func = lambda: None
2777 gc.enable()
2778
Victor Stinner8f437aa2014-10-05 17:25:19 +02002779 for args, exe_list, cwd, env_list in (
2780 (123, [b"exe"], None, [b"env"]),
2781 ([b"arg"], 123, None, [b"env"]),
2782 ([b"arg"], [b"exe"], 123, [b"env"]),
2783 ([b"arg"], [b"exe"], None, 123),
2784 ):
2785 with self.assertRaises(TypeError):
2786 _posixsubprocess.fork_exec(
2787 args, exe_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002788 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02002789 -1, -1, -1, -1,
2790 1, 2, 3, 4,
2791 True, True, func)
2792 finally:
2793 if not gc_enabled:
2794 gc.disable()
2795
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002796 @support.cpython_only
2797 def test_fork_exec_sorted_fd_sanity_check(self):
2798 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
2799 import _posixsubprocess
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002800 class BadInt:
2801 first = True
2802 def __init__(self, value):
2803 self.value = value
2804 def __int__(self):
2805 if self.first:
2806 self.first = False
2807 return self.value
2808 raise ValueError
2809
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002810 gc_enabled = gc.isenabled()
2811 try:
2812 gc.enable()
2813
2814 for fds_to_keep in (
2815 (-1, 2, 3, 4, 5), # Negative number.
2816 ('str', 4), # Not an int.
2817 (18, 23, 42, 2**63), # Out of range.
2818 (5, 4), # Not sorted.
2819 (6, 7, 7, 8), # Duplicate.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002820 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002821 ):
2822 with self.assertRaises(
2823 ValueError,
2824 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
2825 _posixsubprocess.fork_exec(
2826 [b"false"], [b"false"],
2827 True, fds_to_keep, None, [b"env"],
2828 -1, -1, -1, -1,
2829 1, 2, 3, 4,
2830 True, True, None)
2831 self.assertIn('fds_to_keep', str(c.exception))
2832 finally:
2833 if not gc_enabled:
2834 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02002835
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00002836 def test_communicate_BrokenPipeError_stdin_close(self):
2837 # By not setting stdout or stderr or a timeout we force the fast path
2838 # that just calls _stdin_write() internally due to our mock.
2839 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2840 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2841 mock_proc_stdin.close.side_effect = BrokenPipeError
2842 proc.communicate() # Should swallow BrokenPipeError from close.
2843 mock_proc_stdin.close.assert_called_with()
2844
2845 def test_communicate_BrokenPipeError_stdin_write(self):
2846 # By not setting stdout or stderr or a timeout we force the fast path
2847 # that just calls _stdin_write() internally due to our mock.
2848 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2849 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2850 mock_proc_stdin.write.side_effect = BrokenPipeError
2851 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
2852 mock_proc_stdin.write.assert_called_once_with(b'stuff')
2853 mock_proc_stdin.close.assert_called_once_with()
2854
2855 def test_communicate_BrokenPipeError_stdin_flush(self):
2856 # Setting stdin and stdout forces the ._communicate() code path.
2857 # python -h exits faster than python -c pass (but spams stdout).
2858 proc = subprocess.Popen([sys.executable, '-h'],
2859 stdin=subprocess.PIPE,
2860 stdout=subprocess.PIPE)
2861 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
2862 open(os.devnull, 'wb') as dev_null:
2863 mock_proc_stdin.flush.side_effect = BrokenPipeError
2864 # because _communicate registers a selector using proc.stdin...
2865 mock_proc_stdin.fileno.return_value = dev_null.fileno()
2866 # _communicate() should swallow BrokenPipeError from flush.
2867 proc.communicate(b'stuff')
2868 mock_proc_stdin.flush.assert_called_once_with()
2869
2870 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
2871 # Setting stdin and stdout forces the ._communicate() code path.
2872 # python -h exits faster than python -c pass (but spams stdout).
2873 proc = subprocess.Popen([sys.executable, '-h'],
2874 stdin=subprocess.PIPE,
2875 stdout=subprocess.PIPE)
2876 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2877 mock_proc_stdin.close.side_effect = BrokenPipeError
2878 # _communicate() should swallow BrokenPipeError from close.
2879 proc.communicate(timeout=999)
2880 mock_proc_stdin.close.assert_called_once_with()
2881
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002882 @unittest.skipUnless(_testcapi is not None
2883 and hasattr(_testcapi, 'W_STOPCODE'),
2884 'need _testcapi.W_STOPCODE')
2885 def test_stopped(self):
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002886 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002887 args = [sys.executable, '-c', 'pass']
2888 proc = subprocess.Popen(args)
Victor Stinnercdee3f12017-06-26 17:23:03 +02002889
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002890 # Wait until the real process completes to avoid zombie process
2891 pid = proc.pid
2892 pid, status = os.waitpid(pid, 0)
2893 self.assertEqual(status, 0)
Victor Stinnercdee3f12017-06-26 17:23:03 +02002894
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002895 status = _testcapi.W_STOPCODE(3)
2896 with mock.patch('subprocess.os.waitpid', return_value=(pid, status)):
2897 returncode = proc.wait()
Victor Stinnercdee3f12017-06-26 17:23:03 +02002898
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02002899 self.assertEqual(returncode, -3)
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002900
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002901
Victor Stinner937ee9e2018-06-26 02:11:06 +02002902@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00002903class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002904
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002905 def test_startupinfo(self):
2906 # startupinfo argument
2907 # We uses hardcoded constants, because we do not want to
2908 # depend on win32all.
2909 STARTF_USESHOWWINDOW = 1
2910 SW_MAXIMIZE = 3
2911 startupinfo = subprocess.STARTUPINFO()
2912 startupinfo.dwFlags = STARTF_USESHOWWINDOW
2913 startupinfo.wShowWindow = SW_MAXIMIZE
2914 # Since Python is a console process, it won't be affected
2915 # by wShowWindow, but the argument should be silently
2916 # ignored
2917 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002918 startupinfo=startupinfo)
2919
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05302920 def test_startupinfo_keywords(self):
2921 # startupinfo argument
2922 # We use hardcoded constants, because we do not want to
2923 # depend on win32all.
2924 STARTF_USERSHOWWINDOW = 1
2925 SW_MAXIMIZE = 3
2926 startupinfo = subprocess.STARTUPINFO(
2927 dwFlags=STARTF_USERSHOWWINDOW,
2928 wShowWindow=SW_MAXIMIZE
2929 )
2930 # Since Python is a console process, it won't be affected
2931 # by wShowWindow, but the argument should be silently
2932 # ignored
2933 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
2934 startupinfo=startupinfo)
2935
Victor Stinner483422f2018-07-05 22:54:17 +02002936 def test_startupinfo_copy(self):
2937 # bpo-34044: Popen must not modify input STARTUPINFO structure
2938 startupinfo = subprocess.STARTUPINFO()
2939 startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
2940 startupinfo.wShowWindow = subprocess.SW_HIDE
2941
2942 # Call Popen() twice with the same startupinfo object to make sure
2943 # that it's not modified
2944 for _ in range(2):
2945 cmd = [sys.executable, "-c", "pass"]
2946 with open(os.devnull, 'w') as null:
2947 proc = subprocess.Popen(cmd,
2948 stdout=null,
2949 stderr=subprocess.STDOUT,
2950 startupinfo=startupinfo)
2951 with proc:
2952 proc.communicate()
2953 self.assertEqual(proc.returncode, 0)
2954
2955 self.assertEqual(startupinfo.dwFlags,
2956 subprocess.STARTF_USESHOWWINDOW)
2957 self.assertIsNone(startupinfo.hStdInput)
2958 self.assertIsNone(startupinfo.hStdOutput)
2959 self.assertIsNone(startupinfo.hStdError)
2960 self.assertEqual(startupinfo.wShowWindow, subprocess.SW_HIDE)
2961 self.assertEqual(startupinfo.lpAttributeList, {"handle_list": []})
2962
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002963 def test_creationflags(self):
2964 # creationflags argument
2965 CREATE_NEW_CONSOLE = 16
2966 sys.stderr.write(" a DOS box should flash briefly ...\n")
2967 subprocess.call(sys.executable +
2968 ' -c "import time; time.sleep(0.25)"',
2969 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002970
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002971 def test_invalid_args(self):
2972 # invalid arguments should raise ValueError
2973 self.assertRaises(ValueError, subprocess.call,
2974 [sys.executable, "-c",
2975 "import sys; sys.exit(47)"],
2976 preexec_fn=lambda: 1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002977
Oren Milman0b3a87e2017-09-14 22:30:28 +03002978 @support.cpython_only
2979 def test_issue31471(self):
2980 # There shouldn't be an assertion failure in Popen() in case the env
2981 # argument has a bad keys() method.
2982 class BadEnv(dict):
2983 keys = None
2984 with self.assertRaises(TypeError):
2985 subprocess.Popen([sys.executable, "-c", "pass"], env=BadEnv())
2986
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002987 def test_close_fds(self):
2988 # close file descriptors
2989 rc = subprocess.call([sys.executable, "-c",
2990 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002991 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002992 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002993
Segev Finerb2a60832017-12-18 11:28:19 +02002994 def test_close_fds_with_stdio(self):
2995 import msvcrt
2996
2997 fds = os.pipe()
2998 self.addCleanup(os.close, fds[0])
2999 self.addCleanup(os.close, fds[1])
3000
3001 handles = []
3002 for fd in fds:
3003 os.set_inheritable(fd, True)
3004 handles.append(msvcrt.get_osfhandle(fd))
3005
3006 p = subprocess.Popen([sys.executable, "-c",
3007 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3008 stdout=subprocess.PIPE, close_fds=False)
3009 stdout, stderr = p.communicate()
3010 self.assertEqual(p.returncode, 0)
3011 int(stdout.strip()) # Check that stdout is an integer
3012
3013 p = subprocess.Popen([sys.executable, "-c",
3014 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3015 stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
3016 stdout, stderr = p.communicate()
3017 self.assertEqual(p.returncode, 1)
3018 self.assertIn(b"OSError", stderr)
3019
3020 # The same as the previous call, but with an empty handle_list
3021 handle_list = []
3022 startupinfo = subprocess.STARTUPINFO()
3023 startupinfo.lpAttributeList = {"handle_list": handle_list}
3024 p = subprocess.Popen([sys.executable, "-c",
3025 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3026 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3027 startupinfo=startupinfo, close_fds=True)
3028 stdout, stderr = p.communicate()
3029 self.assertEqual(p.returncode, 1)
3030 self.assertIn(b"OSError", stderr)
3031
3032 # Check for a warning due to using handle_list and close_fds=False
3033 with support.check_warnings((".*overriding close_fds", RuntimeWarning)):
3034 startupinfo = subprocess.STARTUPINFO()
3035 startupinfo.lpAttributeList = {"handle_list": handles[:]}
3036 p = subprocess.Popen([sys.executable, "-c",
3037 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3038 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3039 startupinfo=startupinfo, close_fds=False)
3040 stdout, stderr = p.communicate()
3041 self.assertEqual(p.returncode, 0)
3042
3043 def test_empty_attribute_list(self):
3044 startupinfo = subprocess.STARTUPINFO()
3045 startupinfo.lpAttributeList = {}
3046 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
3047 startupinfo=startupinfo)
3048
3049 def test_empty_handle_list(self):
3050 startupinfo = subprocess.STARTUPINFO()
3051 startupinfo.lpAttributeList = {"handle_list": []}
3052 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
3053 startupinfo=startupinfo)
3054
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003055 def test_shell_sequence(self):
3056 # Run command through the shell (sequence)
3057 newenv = os.environ.copy()
3058 newenv["FRUIT"] = "physalis"
3059 p = subprocess.Popen(["set"], shell=1,
3060 stdout=subprocess.PIPE,
3061 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003062 with p:
3063 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00003064
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003065 def test_shell_string(self):
3066 # Run command through the shell (string)
3067 newenv = os.environ.copy()
3068 newenv["FRUIT"] = "physalis"
3069 p = subprocess.Popen("set", shell=1,
3070 stdout=subprocess.PIPE,
3071 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003072 with p:
3073 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003074
Steve Dower050acae2016-09-06 20:16:17 -07003075 def test_shell_encodings(self):
3076 # Run command through the shell (string)
3077 for enc in ['ansi', 'oem']:
3078 newenv = os.environ.copy()
3079 newenv["FRUIT"] = "physalis"
3080 p = subprocess.Popen("set", shell=1,
3081 stdout=subprocess.PIPE,
3082 env=newenv,
3083 encoding=enc)
3084 with p:
3085 self.assertIn("physalis", p.stdout.read(), enc)
3086
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003087 def test_call_string(self):
3088 # call() function with string argument on Windows
3089 rc = subprocess.call(sys.executable +
3090 ' -c "import sys; sys.exit(47)"')
3091 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003092
Florent Xicluna4886d242010-03-08 13:27:26 +00003093 def _kill_process(self, method, *args):
3094 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00003095 p = subprocess.Popen([sys.executable, "-c", """if 1:
3096 import sys, time
3097 sys.stdout.write('x\\n')
3098 sys.stdout.flush()
3099 time.sleep(30)
3100 """],
3101 stdin=subprocess.PIPE,
3102 stdout=subprocess.PIPE,
3103 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003104 with p:
3105 # Wait for the interpreter to be completely initialized before
3106 # sending any signal.
3107 p.stdout.read(1)
3108 getattr(p, method)(*args)
3109 _, stderr = p.communicate()
3110 self.assertStderrEqual(stderr, b'')
3111 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00003112 self.assertNotEqual(returncode, 0)
3113
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003114 def _kill_dead_process(self, method, *args):
3115 p = subprocess.Popen([sys.executable, "-c", """if 1:
3116 import sys, time
3117 sys.stdout.write('x\\n')
3118 sys.stdout.flush()
3119 sys.exit(42)
3120 """],
3121 stdin=subprocess.PIPE,
3122 stdout=subprocess.PIPE,
3123 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003124 with p:
3125 # Wait for the interpreter to be completely initialized before
3126 # sending any signal.
3127 p.stdout.read(1)
3128 # The process should end after this
3129 time.sleep(1)
3130 # This shouldn't raise even though the child is now dead
3131 getattr(p, method)(*args)
3132 _, stderr = p.communicate()
3133 self.assertStderrEqual(stderr, b'')
3134 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003135 self.assertEqual(rc, 42)
3136
Florent Xicluna4886d242010-03-08 13:27:26 +00003137 def test_send_signal(self):
3138 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00003139
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003140 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003141 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00003142
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003143 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003144 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00003145
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003146 def test_send_signal_dead(self):
3147 self._kill_dead_process('send_signal', signal.SIGTERM)
3148
3149 def test_kill_dead(self):
3150 self._kill_dead_process('kill')
3151
3152 def test_terminate_dead(self):
3153 self._kill_dead_process('terminate')
3154
Martin Panter23172bd2016-04-16 11:28:10 +00003155class MiscTests(unittest.TestCase):
Gregory P. Smithf4d644f2018-01-29 21:27:39 -08003156
3157 class RecordingPopen(subprocess.Popen):
3158 """A Popen that saves a reference to each instance for testing."""
3159 instances_created = []
3160
3161 def __init__(self, *args, **kwargs):
3162 super().__init__(*args, **kwargs)
3163 self.instances_created.append(self)
3164
3165 @mock.patch.object(subprocess.Popen, "_communicate")
3166 def _test_keyboardinterrupt_no_kill(self, popener, mock__communicate,
3167 **kwargs):
3168 """Fake a SIGINT happening during Popen._communicate() and ._wait().
3169
3170 This avoids the need to actually try and get test environments to send
3171 and receive signals reliably across platforms. The net effect of a ^C
3172 happening during a blocking subprocess execution which we want to clean
3173 up from is a KeyboardInterrupt coming out of communicate() or wait().
3174 """
3175
3176 mock__communicate.side_effect = KeyboardInterrupt
3177 try:
3178 with mock.patch.object(subprocess.Popen, "_wait") as mock__wait:
3179 # We patch out _wait() as no signal was involved so the
3180 # child process isn't actually going to exit rapidly.
3181 mock__wait.side_effect = KeyboardInterrupt
3182 with mock.patch.object(subprocess, "Popen",
3183 self.RecordingPopen):
3184 with self.assertRaises(KeyboardInterrupt):
3185 popener([sys.executable, "-c",
3186 "import time\ntime.sleep(9)\nimport sys\n"
3187 "sys.stderr.write('\\n!runaway child!\\n')"],
3188 stdout=subprocess.DEVNULL, **kwargs)
3189 for call in mock__wait.call_args_list[1:]:
3190 self.assertNotEqual(
3191 call, mock.call(timeout=None),
3192 "no open-ended wait() after the first allowed: "
3193 f"{mock__wait.call_args_list}")
3194 sigint_calls = []
3195 for call in mock__wait.call_args_list:
3196 if call == mock.call(timeout=0.25): # from Popen.__init__
3197 sigint_calls.append(call)
3198 self.assertLessEqual(mock__wait.call_count, 2,
3199 msg=mock__wait.call_args_list)
3200 self.assertEqual(len(sigint_calls), 1,
3201 msg=mock__wait.call_args_list)
3202 finally:
3203 # cleanup the forgotten (due to our mocks) child process
3204 process = self.RecordingPopen.instances_created.pop()
3205 process.kill()
3206 process.wait()
3207 self.assertEqual([], self.RecordingPopen.instances_created)
3208
3209 def test_call_keyboardinterrupt_no_kill(self):
3210 self._test_keyboardinterrupt_no_kill(subprocess.call, timeout=6.282)
3211
3212 def test_run_keyboardinterrupt_no_kill(self):
3213 self._test_keyboardinterrupt_no_kill(subprocess.run, timeout=6.282)
3214
3215 def test_context_manager_keyboardinterrupt_no_kill(self):
3216 def popen_via_context_manager(*args, **kwargs):
3217 with subprocess.Popen(*args, **kwargs) as unused_process:
3218 raise KeyboardInterrupt # Test how __exit__ handles ^C.
3219 self._test_keyboardinterrupt_no_kill(popen_via_context_manager)
3220
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003221 def test_getoutput(self):
3222 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
3223 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
3224 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00003225
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003226 # we use mkdtemp in the next line to create an empty directory
3227 # under our exclusive control; from that, we can invent a pathname
3228 # that we _know_ won't exist. This is guaranteed to fail.
3229 dir = None
3230 try:
3231 dir = tempfile.mkdtemp()
3232 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00003233 status, output = subprocess.getstatusoutput(
Victor Stinner937ee9e2018-06-26 02:11:06 +02003234 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003235 self.assertNotEqual(status, 0)
3236 finally:
3237 if dir is not None:
3238 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00003239
Gregory P. Smithace55862015-04-07 15:57:54 -07003240 def test__all__(self):
3241 """Ensure that __all__ is populated properly."""
Martin Panter528619b2016-04-16 23:42:37 +00003242 intentionally_excluded = {"list2cmdline", "Handle"}
Gregory P. Smithace55862015-04-07 15:57:54 -07003243 exported = set(subprocess.__all__)
3244 possible_exports = set()
3245 import types
3246 for name, value in subprocess.__dict__.items():
3247 if name.startswith('_'):
3248 continue
3249 if isinstance(value, (types.ModuleType,)):
3250 continue
3251 possible_exports.add(name)
3252 self.assertEqual(exported, possible_exports - intentionally_excluded)
3253
3254
Martin Panter23172bd2016-04-16 11:28:10 +00003255@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
3256 "Test needs selectors.PollSelector")
3257class ProcessTestCaseNoPoll(ProcessTestCase):
3258 def setUp(self):
3259 self.orig_selector = subprocess._PopenSelector
3260 subprocess._PopenSelector = selectors.SelectSelector
3261 ProcessTestCase.setUp(self)
3262
3263 def tearDown(self):
3264 subprocess._PopenSelector = self.orig_selector
3265 ProcessTestCase.tearDown(self)
3266
Gregory P. Smithd06fa472009-07-04 02:46:54 +00003267
Victor Stinner937ee9e2018-06-26 02:11:06 +02003268@unittest.skipUnless(mswindows, "Windows-specific tests")
Tim Golden126c2962010-08-11 14:20:40 +00003269class CommandsWithSpaces (BaseTestCase):
3270
3271 def setUp(self):
3272 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03003273 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00003274 self.fname = fname.lower ()
3275 os.write(f, b"import sys;"
3276 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
3277 )
3278 os.close(f)
3279
3280 def tearDown(self):
3281 os.remove(self.fname)
3282 super().tearDown()
3283
3284 def with_spaces(self, *args, **kwargs):
3285 kwargs['stdout'] = subprocess.PIPE
3286 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02003287 with p:
3288 self.assertEqual(
3289 p.stdout.read ().decode("mbcs"),
3290 "2 [%r, 'ab cd']" % self.fname
3291 )
Tim Golden126c2962010-08-11 14:20:40 +00003292
3293 def test_shell_string_with_spaces(self):
3294 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003295 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3296 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003297
3298 def test_shell_sequence_with_spaces(self):
3299 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003300 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003301
3302 def test_noshell_string_with_spaces(self):
3303 # call() function with string argument with spaces on Windows
3304 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3305 "ab cd"))
3306
3307 def test_noshell_sequence_with_spaces(self):
3308 # call() function with sequence argument with spaces on Windows
3309 self.with_spaces([sys.executable, self.fname, "ab cd"])
3310
Brian Curtin79cdb662010-12-03 02:46:02 +00003311
Georg Brandla86b2622012-02-20 21:34:57 +01003312class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00003313
3314 def test_pipe(self):
3315 with subprocess.Popen([sys.executable, "-c",
3316 "import sys;"
3317 "sys.stdout.write('stdout');"
3318 "sys.stderr.write('stderr');"],
3319 stdout=subprocess.PIPE,
3320 stderr=subprocess.PIPE) as proc:
3321 self.assertEqual(proc.stdout.read(), b"stdout")
3322 self.assertStderrEqual(proc.stderr.read(), b"stderr")
3323
3324 self.assertTrue(proc.stdout.closed)
3325 self.assertTrue(proc.stderr.closed)
3326
3327 def test_returncode(self):
3328 with subprocess.Popen([sys.executable, "-c",
3329 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07003330 pass
3331 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00003332 self.assertEqual(proc.returncode, 100)
3333
3334 def test_communicate_stdin(self):
3335 with subprocess.Popen([sys.executable, "-c",
3336 "import sys;"
3337 "sys.exit(sys.stdin.read() == 'context')"],
3338 stdin=subprocess.PIPE) as proc:
3339 proc.communicate(b"context")
3340 self.assertEqual(proc.returncode, 1)
3341
3342 def test_invalid_args(self):
Victor Stinnerb31206a2018-01-25 19:06:05 +01003343 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02003344 with subprocess.Popen(NONEXISTING_CMD,
Brian Curtin79cdb662010-12-03 02:46:02 +00003345 stdout=subprocess.PIPE,
3346 stderr=subprocess.PIPE) as proc:
3347 pass
3348
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003349 def test_broken_pipe_cleanup(self):
3350 """Broken pipe error should not prevent wait() (Issue 21619)"""
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003351 proc = subprocess.Popen([sys.executable, '-c', 'pass'],
Victor Stinner20f4bd42015-03-05 02:38:41 +01003352 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003353 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003354 proc = proc.__enter__()
3355 # Prepare to send enough data to overflow any OS pipe buffering and
3356 # guarantee a broken pipe error. Data is held in BufferedWriter
3357 # buffer until closed.
3358 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003359 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003360 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02003361 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003362 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003363 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003364
Brian Curtin79cdb662010-12-03 02:46:02 +00003365
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003366if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04003367 unittest.main()