blob: 87322c6406bd553ca6fa5f1d4e86be53bcb2965d [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
Patrick McLean2b2ead72019-09-12 10:15:44 -070021import json
Serhiy Storchakab21d1552018-03-02 11:53:51 +020022from test.support import FakePath
Benjamin Peterson964561b2011-12-10 12:31:42 -050023
24try:
Victor Stinner7b7c6dc2017-08-10 12:37:39 +020025 import _testcapi
26except ImportError:
27 _testcapi = None
28
Patrick McLean2b2ead72019-09-12 10:15:44 -070029try:
30 import pwd
31except ImportError:
32 pwd = None
33try:
34 import grp
35except ImportError:
36 grp = None
Victor Stinner8f4ef3b2019-07-01 18:28:25 +020037
Steve Dower22d06982016-09-06 19:38:15 -070038if support.PGO:
39 raise unittest.SkipTest("test is not helpful for PGO")
40
Victor Stinner937ee9e2018-06-26 02:11:06 +020041mswindows = (sys.platform == "win32")
42
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000043#
44# Depends on the following external programs: Python
45#
46
Victor Stinner937ee9e2018-06-26 02:11:06 +020047if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000048 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
49 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000050else:
51 SETBINARY = ''
52
Victor Stinner9a83f652017-08-21 23:51:31 +020053NONEXISTING_CMD = ('nonexisting_i_hope',)
Victor Stinnerb31206a2018-01-25 19:06:05 +010054# Ignore errors that indicate the command was not found
55NONEXISTING_ERRORS = (FileNotFoundError, NotADirectoryError, PermissionError)
Victor Stinner9a83f652017-08-21 23:51:31 +020056
Gregory P. Smith67b93f82019-10-12 16:35:53 -070057ZERO_RETURN_CMD = (sys.executable, '-c', 'pass')
58
59
60def setUpModule():
61 shell_true = shutil.which('true')
Pablo Galindo46113e02019-10-13 02:40:24 +010062 if shell_true is None:
63 return
Gregory P. Smith67b93f82019-10-12 16:35:53 -070064 if (os.access(shell_true, os.X_OK) and
65 subprocess.run([shell_true]).returncode == 0):
66 global ZERO_RETURN_CMD
67 ZERO_RETURN_CMD = (shell_true,) # Faster than Python startup.
68
Florent Xiclunab1e94e82010-02-27 22:12:37 +000069
Florent Xiclunac049d872010-03-27 22:47:23 +000070class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000071 def setUp(self):
72 # Try to minimize the number of children we have so this test
73 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000074 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000075
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000076 def tearDown(self):
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +030077 if not mswindows:
78 # subprocess._active is not used on Windows and is set to None.
79 for inst in subprocess._active:
80 inst.wait()
81 subprocess._cleanup()
82 self.assertFalse(
83 subprocess._active, "subprocess._active not empty"
84 )
Victor Stinnercc42c122017-07-28 18:00:22 +020085 self.doCleanups()
86 support.reap_children()
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000087
Florent Xiclunac049d872010-03-27 22:47:23 +000088
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080089class PopenTestException(Exception):
90 pass
91
92
93class PopenExecuteChildRaises(subprocess.Popen):
94 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
95 _execute_child fails.
96 """
97 def _execute_child(self, *args, **kwargs):
98 raise PopenTestException("Forced Exception for Test")
99
100
Florent Xiclunac049d872010-03-27 22:47:23 +0000101class ProcessTestCase(BaseTestCase):
102
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700103 def test_io_buffered_by_default(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700104 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700105 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
106 stderr=subprocess.PIPE)
107 try:
108 self.assertIsInstance(p.stdin, io.BufferedIOBase)
109 self.assertIsInstance(p.stdout, io.BufferedIOBase)
110 self.assertIsInstance(p.stderr, io.BufferedIOBase)
111 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700112 p.stdin.close()
113 p.stdout.close()
114 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700115 p.wait()
116
117 def test_io_unbuffered_works(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700118 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700119 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
120 stderr=subprocess.PIPE, bufsize=0)
121 try:
122 self.assertIsInstance(p.stdin, io.RawIOBase)
123 self.assertIsInstance(p.stdout, io.RawIOBase)
124 self.assertIsInstance(p.stderr, io.RawIOBase)
125 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700126 p.stdin.close()
127 p.stdout.close()
128 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700129 p.wait()
130
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000131 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000132 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000133 rc = subprocess.call([sys.executable, "-c",
134 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000135 self.assertEqual(rc, 47)
136
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400137 def test_call_timeout(self):
138 # call() function with timeout argument; we want to test that the child
139 # process gets killed when the timeout expires. If the child isn't
140 # killed, this call will deadlock since subprocess.call waits for the
141 # child.
142 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
143 [sys.executable, "-c", "while True: pass"],
144 timeout=0.1)
145
Peter Astrand454f7672005-01-01 09:36:35 +0000146 def test_check_call_zero(self):
147 # check_call() function with zero return code
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700148 rc = subprocess.check_call(ZERO_RETURN_CMD)
Peter Astrand454f7672005-01-01 09:36:35 +0000149 self.assertEqual(rc, 0)
150
151 def test_check_call_nonzero(self):
152 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000153 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000154 subprocess.check_call([sys.executable, "-c",
155 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000156 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000157
Georg Brandlf9734072008-12-07 15:30:06 +0000158 def test_check_output(self):
159 # check_output() function with zero return code
160 output = subprocess.check_output(
161 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000162 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000163
164 def test_check_output_nonzero(self):
165 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000166 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000167 subprocess.check_output(
168 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000169 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000170
171 def test_check_output_stderr(self):
172 # check_output() function stderr redirected to stdout
173 output = subprocess.check_output(
174 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
175 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000176 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000177
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300178 def test_check_output_stdin_arg(self):
179 # check_output() can be called with stdin set to a file
180 tf = tempfile.TemporaryFile()
181 self.addCleanup(tf.close)
182 tf.write(b'pear')
183 tf.seek(0)
184 output = subprocess.check_output(
185 [sys.executable, "-c",
186 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
187 stdin=tf)
188 self.assertIn(b'PEAR', output)
189
190 def test_check_output_input_arg(self):
191 # check_output() can be called with input set to a string
192 output = subprocess.check_output(
193 [sys.executable, "-c",
194 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
195 input=b'pear')
196 self.assertIn(b'PEAR', output)
197
Georg Brandlf9734072008-12-07 15:30:06 +0000198 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300199 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000200 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000201 output = subprocess.check_output(
202 [sys.executable, "-c", "print('will not be run')"],
203 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000204 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000205 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000206
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300207 def test_check_output_stdin_with_input_arg(self):
208 # check_output() refuses to accept 'stdin' with 'input'
209 tf = tempfile.TemporaryFile()
210 self.addCleanup(tf.close)
211 tf.write(b'pear')
212 tf.seek(0)
213 with self.assertRaises(ValueError) as c:
214 output = subprocess.check_output(
215 [sys.executable, "-c", "print('will not be run')"],
216 stdin=tf, input=b'hare')
217 self.fail("Expected ValueError when stdin and input args supplied.")
218 self.assertIn('stdin', c.exception.args[0])
219 self.assertIn('input', c.exception.args[0])
220
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400221 def test_check_output_timeout(self):
222 # check_output() function with timeout arg
223 with self.assertRaises(subprocess.TimeoutExpired) as c:
224 output = subprocess.check_output(
225 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200226 "import sys, time\n"
227 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400228 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200229 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400230 # Some heavily loaded buildbots (sparc Debian 3.x) require
231 # this much time to start and print.
232 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400233 self.fail("Expected TimeoutExpired.")
234 self.assertEqual(c.exception.output, b'BDFL')
235
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000236 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000237 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000238 newenv = os.environ.copy()
239 newenv["FRUIT"] = "banana"
240 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000241 'import sys, os;'
242 'sys.exit(os.getenv("FRUIT")=="banana")'],
243 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000244 self.assertEqual(rc, 1)
245
Victor Stinner87b9bc32011-06-01 00:57:47 +0200246 def test_invalid_args(self):
247 # Popen() called with invalid arguments should raise TypeError
248 # but Popen.__del__ should not complain (issue #12085)
249 with support.captured_stderr() as s:
250 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
251 argcount = subprocess.Popen.__init__.__code__.co_argcount
252 too_many_args = [0] * (argcount + 1)
253 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
254 self.assertEqual(s.getvalue(), '')
255
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000256 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000257 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000258 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000259 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000260 self.addCleanup(p.stdout.close)
261 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000262 p.wait()
263 self.assertEqual(p.stdin, None)
264
265 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200266 # .stdout is None when not redirected, and the child's stdout will
267 # be inherited from the parent. In order to test this we run a
268 # subprocess in a subprocess:
269 # this_test
270 # \-- subprocess created by this test (parent)
271 # \-- subprocess created by the parent subprocess (child)
272 # The parent doesn't specify stdout, so the child will use the
273 # parent's stdout. This test checks that the message printed by the
274 # child goes to the parent stdout. The parent also checks that the
275 # child's stdout is None. See #11963.
276 code = ('import sys; from subprocess import Popen, PIPE;'
277 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
278 ' stdin=PIPE, stderr=PIPE);'
279 'p.wait(); assert p.stdout is None;')
280 p = subprocess.Popen([sys.executable, "-c", code],
281 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
282 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000283 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200284 out, err = p.communicate()
285 self.assertEqual(p.returncode, 0, err)
286 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000287
288 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000289 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000290 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000291 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000292 self.addCleanup(p.stdout.close)
293 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000294 p.wait()
295 self.assertEqual(p.stderr, None)
296
Chris Jerdonek776cb192012-10-08 15:56:43 -0700297 def _assert_python(self, pre_args, **kwargs):
298 # We include sys.exit() to prevent the test runner from hanging
299 # whenever python is found.
300 args = pre_args + ["import sys; sys.exit(47)"]
301 p = subprocess.Popen(args, **kwargs)
302 p.wait()
303 self.assertEqual(47, p.returncode)
304
305 def test_executable(self):
306 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700307 #
308 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
309 # determine where its standard library is, so we need the directory
310 # of args[0] to be valid for the Popen() call to Python to succeed.
311 # See also issue #16170 and issue #7774.
312 doesnotexist = os.path.join(os.path.dirname(sys.executable),
313 "doesnotexist")
314 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700315
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300316 def test_bytes_executable(self):
317 doesnotexist = os.path.join(os.path.dirname(sys.executable),
318 "doesnotexist")
319 self._assert_python([doesnotexist, "-c"],
320 executable=os.fsencode(sys.executable))
321
322 def test_pathlike_executable(self):
323 doesnotexist = os.path.join(os.path.dirname(sys.executable),
324 "doesnotexist")
325 self._assert_python([doesnotexist, "-c"],
326 executable=FakePath(sys.executable))
327
Chris Jerdonek776cb192012-10-08 15:56:43 -0700328 def test_executable_takes_precedence(self):
329 # Check that the executable argument takes precedence over args[0].
330 #
331 # Verify first that the call succeeds without the executable arg.
332 pre_args = [sys.executable, "-c"]
333 self._assert_python(pre_args)
Victor Stinnerb31206a2018-01-25 19:06:05 +0100334 self.assertRaises(NONEXISTING_ERRORS,
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +0100335 self._assert_python, pre_args,
Victor Stinnerb31206a2018-01-25 19:06:05 +0100336 executable=NONEXISTING_CMD[0])
Chris Jerdonek776cb192012-10-08 15:56:43 -0700337
Victor Stinner937ee9e2018-06-26 02:11:06 +0200338 @unittest.skipIf(mswindows, "executable argument replaces shell")
Chris Jerdonek776cb192012-10-08 15:56:43 -0700339 def test_executable_replaces_shell(self):
340 # Check that the executable argument replaces the default shell
341 # when shell=True.
342 self._assert_python([], executable=sys.executable, shell=True)
343
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300344 @unittest.skipIf(mswindows, "executable argument replaces shell")
345 def test_bytes_executable_replaces_shell(self):
346 self._assert_python([], executable=os.fsencode(sys.executable),
347 shell=True)
348
349 @unittest.skipIf(mswindows, "executable argument replaces shell")
350 def test_pathlike_executable_replaces_shell(self):
351 self._assert_python([], executable=FakePath(sys.executable),
352 shell=True)
353
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700354 # For use in the test_cwd* tests below.
355 def _normalize_cwd(self, cwd):
356 # Normalize an expected cwd (for Tru64 support).
357 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
358 # strings. See bug #1063571.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300359 with support.change_cwd(cwd):
360 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700361
362 # For use in the test_cwd* tests below.
363 def _split_python_path(self):
364 # Return normalized (python_dir, python_base).
365 python_path = os.path.realpath(sys.executable)
366 return os.path.split(python_path)
367
368 # For use in the test_cwd* tests below.
369 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
370 # Invoke Python via Popen, and assert that (1) the call succeeds,
371 # and that (2) the current working directory of the child process
372 # matches *expected_cwd*.
373 p = subprocess.Popen([python_arg, "-c",
374 "import os, sys; "
375 "sys.stdout.write(os.getcwd()); "
376 "sys.exit(47)"],
377 stdout=subprocess.PIPE,
378 **kwargs)
379 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000380 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700381 self.assertEqual(47, p.returncode)
382 normcase = os.path.normcase
383 self.assertEqual(normcase(expected_cwd),
384 normcase(p.stdout.read().decode("utf-8")))
385
386 def test_cwd(self):
387 # Check that cwd changes the cwd for the child process.
388 temp_dir = tempfile.gettempdir()
389 temp_dir = self._normalize_cwd(temp_dir)
390 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
391
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300392 def test_cwd_with_bytes(self):
393 temp_dir = tempfile.gettempdir()
394 temp_dir = self._normalize_cwd(temp_dir)
395 self._assert_cwd(temp_dir, sys.executable, cwd=os.fsencode(temp_dir))
396
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530397 def test_cwd_with_pathlike(self):
398 temp_dir = tempfile.gettempdir()
399 temp_dir = self._normalize_cwd(temp_dir)
Serhiy Storchakab21d1552018-03-02 11:53:51 +0200400 self._assert_cwd(temp_dir, sys.executable, cwd=FakePath(temp_dir))
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530401
Victor Stinner937ee9e2018-06-26 02:11:06 +0200402 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700403 def test_cwd_with_relative_arg(self):
404 # Check that Popen looks for args[0] relative to cwd if args[0]
405 # is relative.
406 python_dir, python_base = self._split_python_path()
407 rel_python = os.path.join(os.curdir, python_base)
408 with support.temp_cwd() as wrong_dir:
409 # Before calling with the correct cwd, confirm that the call fails
410 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700411 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700412 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700413 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700414 [rel_python], cwd=wrong_dir)
415 python_dir = self._normalize_cwd(python_dir)
416 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
417
Victor Stinner937ee9e2018-06-26 02:11:06 +0200418 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700419 def test_cwd_with_relative_executable(self):
420 # Check that Popen looks for executable relative to cwd if executable
421 # is relative (and that executable takes precedence over args[0]).
422 python_dir, python_base = self._split_python_path()
423 rel_python = os.path.join(os.curdir, python_base)
424 doesntexist = "somethingyoudonthave"
425 with support.temp_cwd() as wrong_dir:
426 # Before calling with the correct cwd, confirm that the call fails
427 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700428 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700429 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700430 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700431 [doesntexist], executable=rel_python,
432 cwd=wrong_dir)
433 python_dir = self._normalize_cwd(python_dir)
434 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
435 cwd=python_dir)
436
437 def test_cwd_with_absolute_arg(self):
438 # Check that Popen can find the executable when the cwd is wrong
439 # if args[0] is an absolute path.
440 python_dir, python_base = self._split_python_path()
441 abs_python = os.path.join(python_dir, python_base)
442 rel_python = os.path.join(os.curdir, python_base)
Berker Peksagce643912015-05-06 06:33:17 +0300443 with support.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700444 # Before calling with an absolute path, confirm that using a
445 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700446 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700447 [rel_python], cwd=wrong_dir)
448 wrong_dir = self._normalize_cwd(wrong_dir)
449 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
450
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100451 @unittest.skipIf(sys.base_prefix != sys.prefix,
452 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000453 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700454 python_dir, python_base = self._split_python_path()
455 python_dir = self._normalize_cwd(python_dir)
456 self._assert_cwd(python_dir, "somethingyoudonthave",
457 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000458
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100459 @unittest.skipIf(sys.base_prefix != sys.prefix,
460 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000461 @unittest.skipIf(sysconfig.is_python_build(),
462 "need an installed Python. See #7774")
463 def test_executable_without_cwd(self):
464 # For a normal installation, it should work without 'cwd'
465 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700466 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
467 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000468
469 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000470 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000471 p = subprocess.Popen([sys.executable, "-c",
472 'import sys; sys.exit(sys.stdin.read() == "pear")'],
473 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000474 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000475 p.stdin.close()
476 p.wait()
477 self.assertEqual(p.returncode, 1)
478
479 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000480 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000481 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000482 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000483 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000484 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000485 os.lseek(d, 0, 0)
486 p = subprocess.Popen([sys.executable, "-c",
487 'import sys; sys.exit(sys.stdin.read() == "pear")'],
488 stdin=d)
489 p.wait()
490 self.assertEqual(p.returncode, 1)
491
492 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000493 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000494 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000495 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000496 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000497 tf.seek(0)
498 p = subprocess.Popen([sys.executable, "-c",
499 'import sys; sys.exit(sys.stdin.read() == "pear")'],
500 stdin=tf)
501 p.wait()
502 self.assertEqual(p.returncode, 1)
503
504 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000505 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000506 p = subprocess.Popen([sys.executable, "-c",
507 'import sys; sys.stdout.write("orange")'],
508 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200509 with p:
510 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000511
512 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000513 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000514 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000515 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000516 d = tf.fileno()
517 p = subprocess.Popen([sys.executable, "-c",
518 'import sys; sys.stdout.write("orange")'],
519 stdout=d)
520 p.wait()
521 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000522 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000523
524 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000525 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000526 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000527 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000528 p = subprocess.Popen([sys.executable, "-c",
529 'import sys; sys.stdout.write("orange")'],
530 stdout=tf)
531 p.wait()
532 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000533 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000534
535 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000536 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000537 p = subprocess.Popen([sys.executable, "-c",
538 'import sys; sys.stderr.write("strawberry")'],
539 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200540 with p:
Victor Stinner6cac1132019-12-08 08:38:16 +0100541 self.assertEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000542
543 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000544 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000545 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000546 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000547 d = tf.fileno()
548 p = subprocess.Popen([sys.executable, "-c",
549 'import sys; sys.stderr.write("strawberry")'],
550 stderr=d)
551 p.wait()
552 os.lseek(d, 0, 0)
Victor Stinner6cac1132019-12-08 08:38:16 +0100553 self.assertEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000554
555 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000556 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000557 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000558 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000559 p = subprocess.Popen([sys.executable, "-c",
560 'import sys; sys.stderr.write("strawberry")'],
561 stderr=tf)
562 p.wait()
563 tf.seek(0)
Victor Stinner6cac1132019-12-08 08:38:16 +0100564 self.assertEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000565
Martin Panterc7635892016-05-13 01:54:44 +0000566 def test_stderr_redirect_with_no_stdout_redirect(self):
567 # test stderr=STDOUT while stdout=None (not set)
568
569 # - grandchild prints to stderr
570 # - child redirects grandchild's stderr to its stdout
571 # - the parent should get grandchild's stderr in child's stdout
572 p = subprocess.Popen([sys.executable, "-c",
573 'import sys, subprocess;'
574 'rc = subprocess.call([sys.executable, "-c",'
575 ' "import sys;"'
576 ' "sys.stderr.write(\'42\')"],'
577 ' stderr=subprocess.STDOUT);'
578 'sys.exit(rc)'],
579 stdout=subprocess.PIPE,
580 stderr=subprocess.PIPE)
581 stdout, stderr = p.communicate()
582 #NOTE: stdout should get stderr from grandchild
Victor Stinner6cac1132019-12-08 08:38:16 +0100583 self.assertEqual(stdout, b'42')
584 self.assertEqual(stderr, b'') # should be empty
Martin Panterc7635892016-05-13 01:54:44 +0000585 self.assertEqual(p.returncode, 0)
586
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000587 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000588 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000589 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000590 'import sys;'
591 'sys.stdout.write("apple");'
592 'sys.stdout.flush();'
593 'sys.stderr.write("orange")'],
594 stdout=subprocess.PIPE,
595 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200596 with p:
Victor Stinner6cac1132019-12-08 08:38:16 +0100597 self.assertEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000598
599 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000600 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000601 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000602 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000603 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000604 'import sys;'
605 'sys.stdout.write("apple");'
606 'sys.stdout.flush();'
607 'sys.stderr.write("orange")'],
608 stdout=tf,
609 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000610 p.wait()
611 tf.seek(0)
Victor Stinner6cac1132019-12-08 08:38:16 +0100612 self.assertEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000613
Thomas Wouters89f507f2006-12-13 04:49:30 +0000614 def test_stdout_filedes_of_stdout(self):
615 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200616 # To avoid printing the text on stdout, we do something similar to
617 # test_stdout_none (see above). The parent subprocess calls the child
618 # subprocess passing stdout=1, and this test uses stdout=PIPE in
619 # order to capture and check the output of the parent. See #11963.
620 code = ('import sys, subprocess; '
621 'rc = subprocess.call([sys.executable, "-c", '
622 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
623 'b\'test with stdout=1\'))"], stdout=1); '
624 'assert rc == 18')
625 p = subprocess.Popen([sys.executable, "-c", code],
626 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
627 self.addCleanup(p.stdout.close)
628 self.addCleanup(p.stderr.close)
629 out, err = p.communicate()
630 self.assertEqual(p.returncode, 0, err)
631 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000632
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200633 def test_stdout_devnull(self):
634 p = subprocess.Popen([sys.executable, "-c",
635 'for i in range(10240):'
636 'print("x" * 1024)'],
637 stdout=subprocess.DEVNULL)
638 p.wait()
639 self.assertEqual(p.stdout, None)
640
641 def test_stderr_devnull(self):
642 p = subprocess.Popen([sys.executable, "-c",
643 'import sys\n'
644 'for i in range(10240):'
645 'sys.stderr.write("x" * 1024)'],
646 stderr=subprocess.DEVNULL)
647 p.wait()
648 self.assertEqual(p.stderr, None)
649
650 def test_stdin_devnull(self):
651 p = subprocess.Popen([sys.executable, "-c",
652 'import sys;'
653 'sys.stdin.read(1)'],
654 stdin=subprocess.DEVNULL)
655 p.wait()
656 self.assertEqual(p.stdin, None)
657
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000658 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000659 newenv = os.environ.copy()
660 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200661 with subprocess.Popen([sys.executable, "-c",
662 'import sys,os;'
663 'sys.stdout.write(os.getenv("FRUIT"))'],
664 stdout=subprocess.PIPE,
665 env=newenv) as p:
666 stdout, stderr = p.communicate()
667 self.assertEqual(stdout, b"orange")
668
Victor Stinner62d51182011-06-23 01:02:25 +0200669 # Windows requires at least the SYSTEMROOT environment variable to start
670 # Python
671 @unittest.skipIf(sys.platform == 'win32',
672 'cannot test an empty env on Windows')
Gregory P. Smithb3512482017-05-30 14:40:37 -0700673 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
674 'The Python shared library cannot be loaded '
675 'with an empty environment.')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200676 def test_empty_env(self):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700677 """Verify that env={} is as empty as possible."""
678
Gregory P. Smith85aba232017-05-30 16:21:47 -0700679 def is_env_var_to_ignore(n):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700680 """Determine if an environment variable is under our control."""
681 # This excludes some __CF_* and VERSIONER_* keys MacOS insists
682 # on adding even when the environment in exec is empty.
683 # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist.
Gregory P. Smith85aba232017-05-30 16:21:47 -0700684 return ('VERSIONER' in n or '__CF' in n or # MacOS
Ned Deily918edc02017-09-04 00:00:21 -0400685 '__PYVENV_LAUNCHER__' in n or # MacOS framework build
Nick Coghlan6ea41862017-06-11 13:16:15 +1000686 n == 'LD_PRELOAD' or n.startswith('SANDBOX') or # Gentoo
687 n == 'LC_CTYPE') # Locale coercion triggered
Gregory P. Smithb3512482017-05-30 14:40:37 -0700688
Victor Stinnerf1512a22011-06-21 17:18:38 +0200689 with subprocess.Popen([sys.executable, "-c",
Gregory P. Smithb3512482017-05-30 14:40:37 -0700690 'import os; print(list(os.environ.keys()))'],
691 stdout=subprocess.PIPE, env={}) as p:
Victor Stinnerf1512a22011-06-21 17:18:38 +0200692 stdout, stderr = p.communicate()
Gregory P. Smithb3512482017-05-30 14:40:37 -0700693 child_env_names = eval(stdout.strip())
694 self.assertIsInstance(child_env_names, list)
695 child_env_names = [k for k in child_env_names
696 if not is_env_var_to_ignore(k)]
697 self.assertEqual(child_env_names, [])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000698
Serhiy Storchakad174d242017-06-23 19:39:27 +0300699 def test_invalid_cmd(self):
700 # null character in the command name
701 cmd = sys.executable + '\0'
702 with self.assertRaises(ValueError):
703 subprocess.Popen([cmd, "-c", "pass"])
704
705 # null character in the command argument
706 with self.assertRaises(ValueError):
707 subprocess.Popen([sys.executable, "-c", "pass#\0"])
708
709 def test_invalid_env(self):
Ville Skyttä49b27342017-08-03 09:00:59 +0300710 # null character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300711 newenv = os.environ.copy()
712 newenv["FRUIT\0VEGETABLE"] = "cabbage"
713 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700714 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300715
Ville Skyttä49b27342017-08-03 09:00:59 +0300716 # null character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300717 newenv = os.environ.copy()
718 newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
719 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700720 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300721
Ville Skyttä49b27342017-08-03 09:00:59 +0300722 # equal character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300723 newenv = os.environ.copy()
724 newenv["FRUIT=ORANGE"] = "lemon"
725 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700726 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300727
Ville Skyttä49b27342017-08-03 09:00:59 +0300728 # equal character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300729 newenv = os.environ.copy()
730 newenv["FRUIT"] = "orange=lemon"
731 with subprocess.Popen([sys.executable, "-c",
732 'import sys, os;'
733 'sys.stdout.write(os.getenv("FRUIT"))'],
734 stdout=subprocess.PIPE,
735 env=newenv) as p:
736 stdout, stderr = p.communicate()
737 self.assertEqual(stdout, b"orange=lemon")
738
Peter Astrandcbac93c2005-03-03 20:24:28 +0000739 def test_communicate_stdin(self):
740 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000741 'import sys;'
742 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000743 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000744 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000745 self.assertEqual(p.returncode, 1)
746
747 def test_communicate_stdout(self):
748 p = subprocess.Popen([sys.executable, "-c",
749 'import sys; sys.stdout.write("pineapple")'],
750 stdout=subprocess.PIPE)
751 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000752 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000753 self.assertEqual(stderr, None)
754
755 def test_communicate_stderr(self):
756 p = subprocess.Popen([sys.executable, "-c",
757 'import sys; sys.stderr.write("pineapple")'],
758 stderr=subprocess.PIPE)
759 (stdout, stderr) = p.communicate()
760 self.assertEqual(stdout, None)
Victor Stinner6cac1132019-12-08 08:38:16 +0100761 self.assertEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000762
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000763 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000764 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000765 'import sys,os;'
766 'sys.stderr.write("pineapple");'
767 'sys.stdout.write(sys.stdin.read())'],
768 stdin=subprocess.PIPE,
769 stdout=subprocess.PIPE,
770 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000771 self.addCleanup(p.stdout.close)
772 self.addCleanup(p.stderr.close)
773 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000774 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000775 self.assertEqual(stdout, b"banana")
Victor Stinner6cac1132019-12-08 08:38:16 +0100776 self.assertEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000777
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400778 def test_communicate_timeout(self):
779 p = subprocess.Popen([sys.executable, "-c",
780 'import sys,os,time;'
781 'sys.stderr.write("pineapple\\n");'
782 'time.sleep(1);'
783 'sys.stderr.write("pear\\n");'
784 'sys.stdout.write(sys.stdin.read())'],
785 universal_newlines=True,
786 stdin=subprocess.PIPE,
787 stdout=subprocess.PIPE,
788 stderr=subprocess.PIPE)
789 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
790 timeout=0.3)
791 # Make sure we can keep waiting for it, and that we get the whole output
792 # after it completes.
793 (stdout, stderr) = p.communicate()
794 self.assertEqual(stdout, "banana")
Victor Stinner6cac1132019-12-08 08:38:16 +0100795 self.assertEqual(stderr.encode(), b"pineapple\npear\n")
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400796
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700797 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200798 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400799 p = subprocess.Popen([sys.executable, "-c",
800 'import sys,os,time;'
801 'sys.stdout.write("a" * (64 * 1024));'
802 'time.sleep(0.2);'
803 'sys.stdout.write("a" * (64 * 1024));'
804 'time.sleep(0.2);'
805 'sys.stdout.write("a" * (64 * 1024));'
806 'time.sleep(0.2);'
807 'sys.stdout.write("a" * (64 * 1024));'],
808 stdout=subprocess.PIPE)
809 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
810 (stdout, _) = p.communicate()
811 self.assertEqual(len(stdout), 4 * 64 * 1024)
812
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000813 # Test for the fd leak reported in http://bugs.python.org/issue2791.
814 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000815 for stdin_pipe in (False, True):
816 for stdout_pipe in (False, True):
817 for stderr_pipe in (False, True):
818 options = {}
819 if stdin_pipe:
820 options['stdin'] = subprocess.PIPE
821 if stdout_pipe:
822 options['stdout'] = subprocess.PIPE
823 if stderr_pipe:
824 options['stderr'] = subprocess.PIPE
825 if not options:
826 continue
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700827 p = subprocess.Popen(ZERO_RETURN_CMD, **options)
Victor Stinner667d4b52010-12-25 22:40:32 +0000828 p.communicate()
829 if p.stdin is not None:
830 self.assertTrue(p.stdin.closed)
831 if p.stdout is not None:
832 self.assertTrue(p.stdout.closed)
833 if p.stderr is not None:
834 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000835
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000836 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000837 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000838 p = subprocess.Popen([sys.executable, "-c",
839 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000840 (stdout, stderr) = p.communicate()
841 self.assertEqual(stdout, None)
842 self.assertEqual(stderr, None)
843
844 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000845 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000846 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000847 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000848 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000849 os.close(x)
850 os.close(y)
851 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000852 'import sys,os;'
853 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200854 'sys.stderr.write("x" * %d);'
855 'sys.stdout.write(sys.stdin.read())' %
856 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000857 stdin=subprocess.PIPE,
858 stdout=subprocess.PIPE,
859 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000860 self.addCleanup(p.stdout.close)
861 self.addCleanup(p.stderr.close)
862 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200863 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000864 (stdout, stderr) = p.communicate(string_to_write)
865 self.assertEqual(stdout, string_to_write)
866
867 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000868 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000869 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000870 'import sys,os;'
871 'sys.stdout.write(sys.stdin.read())'],
872 stdin=subprocess.PIPE,
873 stdout=subprocess.PIPE,
874 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000875 self.addCleanup(p.stdout.close)
876 self.addCleanup(p.stderr.close)
877 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000878 p.stdin.write(b"banana")
879 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000880 self.assertEqual(stdout, b"bananasplit")
Victor Stinner6cac1132019-12-08 08:38:16 +0100881 self.assertEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000882
andyclegg7fed7bd2017-10-23 03:01:19 +0100883 def test_universal_newlines_and_text(self):
884 args = [
885 sys.executable, "-c",
886 'import sys,os;' + SETBINARY +
887 'buf = sys.stdout.buffer;'
888 'buf.write(sys.stdin.readline().encode());'
889 'buf.flush();'
890 'buf.write(b"line2\\n");'
891 'buf.flush();'
892 'buf.write(sys.stdin.read().encode());'
893 'buf.flush();'
894 'buf.write(b"line4\\n");'
895 'buf.flush();'
896 'buf.write(b"line5\\r\\n");'
897 'buf.flush();'
898 'buf.write(b"line6\\r");'
899 'buf.flush();'
900 'buf.write(b"\\nline7");'
901 'buf.flush();'
902 'buf.write(b"\\nline8");']
903
904 for extra_kwarg in ('universal_newlines', 'text'):
905 p = subprocess.Popen(args, **{'stdin': subprocess.PIPE,
906 'stdout': subprocess.PIPE,
907 extra_kwarg: True})
908 with p:
909 p.stdin.write("line1\n")
910 p.stdin.flush()
911 self.assertEqual(p.stdout.readline(), "line1\n")
912 p.stdin.write("line3\n")
913 p.stdin.close()
914 self.addCleanup(p.stdout.close)
915 self.assertEqual(p.stdout.readline(),
916 "line2\n")
917 self.assertEqual(p.stdout.read(6),
918 "line3\n")
919 self.assertEqual(p.stdout.read(),
920 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000921
922 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000923 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000924 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000925 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200926 'buf = sys.stdout.buffer;'
927 'buf.write(b"line2\\n");'
928 'buf.flush();'
929 'buf.write(b"line4\\n");'
930 'buf.flush();'
931 'buf.write(b"line5\\r\\n");'
932 'buf.flush();'
933 'buf.write(b"line6\\r");'
934 'buf.flush();'
935 'buf.write(b"\\nline7");'
936 'buf.flush();'
937 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200938 stderr=subprocess.PIPE,
939 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000940 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000941 self.addCleanup(p.stdout.close)
942 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000943 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200944 self.assertEqual(stdout,
945 "line2\nline4\nline5\nline6\nline7\nline8")
946
947 def test_universal_newlines_communicate_stdin(self):
948 # universal newlines through communicate(), with only stdin
949 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300950 'import sys,os;' + SETBINARY + textwrap.dedent('''
951 s = sys.stdin.readline()
952 assert s == "line1\\n", repr(s)
953 s = sys.stdin.read()
954 assert s == "line3\\n", repr(s)
955 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200956 stdin=subprocess.PIPE,
957 universal_newlines=1)
958 (stdout, stderr) = p.communicate("line1\nline3\n")
959 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000960
Andrew Svetlovf3765072012-08-14 18:35:17 +0300961 def test_universal_newlines_communicate_input_none(self):
962 # Test communicate(input=None) with universal newlines.
963 #
964 # We set stdout to PIPE because, as of this writing, a different
965 # code path is tested when the number of pipes is zero or one.
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700966 p = subprocess.Popen(ZERO_RETURN_CMD,
Andrew Svetlovf3765072012-08-14 18:35:17 +0300967 stdin=subprocess.PIPE,
968 stdout=subprocess.PIPE,
969 universal_newlines=True)
970 p.communicate()
971 self.assertEqual(p.returncode, 0)
972
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300973 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300974 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300975 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300976 'import sys,os;' + SETBINARY + textwrap.dedent('''
977 s = sys.stdin.buffer.readline()
978 sys.stdout.buffer.write(s)
979 sys.stdout.buffer.write(b"line2\\r")
980 sys.stderr.buffer.write(b"eline2\\n")
981 s = sys.stdin.buffer.read()
982 sys.stdout.buffer.write(s)
983 sys.stdout.buffer.write(b"line4\\n")
984 sys.stdout.buffer.write(b"line5\\r\\n")
985 sys.stderr.buffer.write(b"eline6\\r")
986 sys.stderr.buffer.write(b"eline7\\r\\nz")
987 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300988 stdin=subprocess.PIPE,
989 stderr=subprocess.PIPE,
990 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300991 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300992 self.addCleanup(p.stdout.close)
993 self.addCleanup(p.stderr.close)
994 (stdout, stderr) = p.communicate("line1\nline3\n")
995 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300996 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300997 # Python debug build push something like "[42442 refs]\n"
998 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300999 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001000
Andrew Svetlov82860712012-08-19 22:13:41 +03001001 def test_universal_newlines_communicate_encodings(self):
1002 # Check that universal newlines mode works for various encodings,
1003 # in particular for encodings in the UTF-16 and UTF-32 families.
1004 # See issue #15595.
1005 #
1006 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
1007 # without, and UTF-16 and UTF-32.
1008 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +03001009 code = ("import sys; "
1010 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
1011 encoding)
1012 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -07001013 # We set stdin to be non-None because, as of this writing,
1014 # a different code path is used when the number of pipes is
1015 # zero or one.
1016 popen = subprocess.Popen(args,
1017 stdin=subprocess.PIPE,
1018 stdout=subprocess.PIPE,
1019 encoding=encoding)
1020 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +03001021 self.assertEqual(stdout, '1\n2\n3\n4')
1022
Steve Dower050acae2016-09-06 20:16:17 -07001023 def test_communicate_errors(self):
1024 for errors, expected in [
1025 ('ignore', ''),
1026 ('replace', '\ufffd\ufffd'),
1027 ('surrogateescape', '\udc80\udc80'),
1028 ('backslashreplace', '\\x80\\x80'),
1029 ]:
1030 code = ("import sys; "
1031 r"sys.stdout.buffer.write(b'[\x80\x80]')")
1032 args = [sys.executable, '-c', code]
1033 # We set stdin to be non-None because, as of this writing,
1034 # a different code path is used when the number of pipes is
1035 # zero or one.
1036 popen = subprocess.Popen(args,
1037 stdin=subprocess.PIPE,
1038 stdout=subprocess.PIPE,
1039 encoding='utf-8',
1040 errors=errors)
1041 stdout, stderr = popen.communicate(input='')
1042 self.assertEqual(stdout, '[{}]'.format(expected))
1043
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001044 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +00001045 # Make sure we leak no resources
Victor Stinner937ee9e2018-06-26 02:11:06 +02001046 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +00001047 max_handles = 1026 # too much for most UNIX systems
1048 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +00001049 max_handles = 2050 # too much for (at least some) Windows setups
1050 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001051 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +00001052 try:
1053 for i in range(max_handles):
1054 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001055 tmpfile = os.path.join(tmpdir, support.TESTFN)
1056 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +00001057 except OSError as e:
1058 if e.errno != errno.EMFILE:
1059 raise
1060 break
1061 else:
1062 self.skipTest("failed to reach the file descriptor limit "
1063 "(tried %d)" % max_handles)
1064 # Close a couple of them (should be enough for a subprocess)
1065 for i in range(10):
1066 os.close(handles.pop())
1067 # Loop creating some subprocesses. If one of them leaks some fds,
1068 # the next loop iteration will fail by reaching the max fd limit.
1069 for i in range(15):
1070 p = subprocess.Popen([sys.executable, "-c",
1071 "import sys;"
1072 "sys.stdout.write(sys.stdin.read())"],
1073 stdin=subprocess.PIPE,
1074 stdout=subprocess.PIPE,
1075 stderr=subprocess.PIPE)
1076 data = p.communicate(b"lime")[0]
1077 self.assertEqual(data, b"lime")
1078 finally:
1079 for h in handles:
1080 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001081 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001082
1083 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001084 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
1085 '"a b c" d e')
1086 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
1087 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +00001088 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
1089 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001090 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
1091 'a\\\\\\b "de fg" h')
1092 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
1093 'a\\\\\\"b c d')
1094 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
1095 '"a\\\\b c" d e')
1096 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
1097 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001098 self.assertEqual(subprocess.list2cmdline(['ab', '']),
1099 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001100
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001101 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001102 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +02001103 "import os; os.read(0, 1)"],
1104 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001105 self.addCleanup(p.stdin.close)
1106 self.assertIsNone(p.poll())
1107 os.write(p.stdin.fileno(), b'A')
1108 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001109 # Subsequent invocations should just return the returncode
1110 self.assertEqual(p.poll(), 0)
1111
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001112 def test_wait(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001113 p = subprocess.Popen(ZERO_RETURN_CMD)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001114 self.assertEqual(p.wait(), 0)
1115 # Subsequent invocations should just return the returncode
1116 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001117
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001118 def test_wait_timeout(self):
1119 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001120 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001121 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001122 p.wait(timeout=0.0001)
1123 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Victor Stinner0d63bac2019-12-11 11:30:03 +01001124 self.assertEqual(p.wait(timeout=support.SHORT_TIMEOUT), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001125
Peter Astrand738131d2004-11-30 21:04:45 +00001126 def test_invalid_bufsize(self):
1127 # an invalid type of the bufsize argument should raise
1128 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001129 with self.assertRaises(TypeError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001130 subprocess.Popen(ZERO_RETURN_CMD, "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001131
Guido van Rossum46a05a72007-06-07 21:56:45 +00001132 def test_bufsize_is_none(self):
1133 # bufsize=None should be the same as bufsize=0.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001134 p = subprocess.Popen(ZERO_RETURN_CMD, None)
Guido van Rossum46a05a72007-06-07 21:56:45 +00001135 self.assertEqual(p.wait(), 0)
1136 # Again with keyword arg
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001137 p = subprocess.Popen(ZERO_RETURN_CMD, bufsize=None)
Guido van Rossum46a05a72007-06-07 21:56:45 +00001138 self.assertEqual(p.wait(), 0)
1139
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001140 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1141 # subprocess may deadlock with bufsize=1, see issue #21332
1142 with subprocess.Popen([sys.executable, "-c", "import sys;"
1143 "sys.stdout.write(sys.stdin.readline());"
1144 "sys.stdout.flush()"],
1145 stdin=subprocess.PIPE,
1146 stdout=subprocess.PIPE,
1147 stderr=subprocess.DEVNULL,
1148 bufsize=1,
1149 universal_newlines=universal_newlines) as p:
1150 p.stdin.write(line) # expect that it flushes the line in text mode
1151 os.close(p.stdin.fileno()) # close it without flushing the buffer
1152 read_line = p.stdout.readline()
Segev Finer4d385172017-08-18 16:18:13 +03001153 with support.SuppressCrashReport():
1154 try:
1155 p.stdin.close()
1156 except OSError:
1157 pass
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001158 p.stdin = None
1159 self.assertEqual(p.returncode, 0)
1160 self.assertEqual(read_line, expected)
1161
1162 def test_bufsize_equal_one_text_mode(self):
1163 # line is flushed in text mode with bufsize=1.
1164 # we should get the full line in return
1165 line = "line\n"
1166 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1167
1168 def test_bufsize_equal_one_binary_mode(self):
1169 # line is not flushed in binary mode with bufsize=1.
1170 # we should get empty response
1171 line = b'line' + os.linesep.encode() # assume ascii-based locale
Alexey Izbysheva2670562018-10-20 03:22:31 +03001172 with self.assertWarnsRegex(RuntimeWarning, 'line buffering'):
1173 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001174
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001175 def test_leaking_fds_on_error(self):
1176 # see bug #5179: Popen leaks file descriptors to PIPEs if
1177 # the child fails to execute; this will eventually exhaust
1178 # the maximum number of open fds. 1024 seems a very common
1179 # value for that limit, but Windows has 2048, so we loop
1180 # 1024 times (each call leaked two fds).
1181 for i in range(1024):
Victor Stinnerb31206a2018-01-25 19:06:05 +01001182 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02001183 subprocess.Popen(NONEXISTING_CMD,
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001184 stdout=subprocess.PIPE,
1185 stderr=subprocess.PIPE)
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001186
Victor Stinner9a83f652017-08-21 23:51:31 +02001187 def test_nonexisting_with_pipes(self):
1188 # bpo-30121: Popen with pipes must close properly pipes on error.
1189 # Previously, os.close() was called with a Windows handle which is not
1190 # a valid file descriptor.
1191 #
1192 # Run the test in a subprocess to control how the CRT reports errors
1193 # and to get stderr content.
1194 try:
1195 import msvcrt
1196 msvcrt.CrtSetReportMode
1197 except (AttributeError, ImportError):
1198 self.skipTest("need msvcrt.CrtSetReportMode")
1199
1200 code = textwrap.dedent(f"""
1201 import msvcrt
1202 import subprocess
1203
1204 cmd = {NONEXISTING_CMD!r}
1205
1206 for report_type in [msvcrt.CRT_WARN,
1207 msvcrt.CRT_ERROR,
1208 msvcrt.CRT_ASSERT]:
1209 msvcrt.CrtSetReportMode(report_type, msvcrt.CRTDBG_MODE_FILE)
1210 msvcrt.CrtSetReportFile(report_type, msvcrt.CRTDBG_FILE_STDERR)
1211
1212 try:
Zachary Ware55376462018-02-19 14:02:38 -06001213 subprocess.Popen(cmd,
Victor Stinner9a83f652017-08-21 23:51:31 +02001214 stdout=subprocess.PIPE,
1215 stderr=subprocess.PIPE)
1216 except OSError:
1217 pass
1218 """)
1219 cmd = [sys.executable, "-c", code]
1220 proc = subprocess.Popen(cmd,
1221 stderr=subprocess.PIPE,
1222 universal_newlines=True)
1223 with proc:
1224 stderr = proc.communicate()[1]
1225 self.assertEqual(stderr, "")
1226 self.assertEqual(proc.returncode, 0)
1227
Antoine Pitroua8392712013-08-30 23:38:13 +02001228 def test_double_close_on_error(self):
1229 # Issue #18851
1230 fds = []
1231 def open_fds():
1232 for i in range(20):
1233 fds.extend(os.pipe())
1234 time.sleep(0.001)
1235 t = threading.Thread(target=open_fds)
1236 t.start()
1237 try:
1238 with self.assertRaises(EnvironmentError):
Victor Stinner9a83f652017-08-21 23:51:31 +02001239 subprocess.Popen(NONEXISTING_CMD,
Antoine Pitroua8392712013-08-30 23:38:13 +02001240 stdin=subprocess.PIPE,
1241 stdout=subprocess.PIPE,
1242 stderr=subprocess.PIPE)
1243 finally:
1244 t.join()
1245 exc = None
1246 for fd in fds:
1247 # If a double close occurred, some of those fds will
1248 # already have been closed by mistake, and os.close()
1249 # here will raise.
1250 try:
1251 os.close(fd)
1252 except OSError as e:
1253 exc = e
1254 if exc is not None:
1255 raise exc
1256
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001257 def test_threadsafe_wait(self):
1258 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1259 proc = subprocess.Popen([sys.executable, '-c',
1260 'import time; time.sleep(12)'])
1261 self.assertEqual(proc.returncode, None)
1262 results = []
1263
1264 def kill_proc_timer_thread():
1265 results.append(('thread-start-poll-result', proc.poll()))
1266 # terminate it from the thread and wait for the result.
1267 proc.kill()
1268 proc.wait()
1269 results.append(('thread-after-kill-and-wait', proc.returncode))
1270 # this wait should be a no-op given the above.
1271 proc.wait()
1272 results.append(('thread-after-second-wait', proc.returncode))
1273
1274 # This is a timing sensitive test, the failure mode is
1275 # triggered when both the main thread and this thread are in
1276 # the wait() call at once. The delay here is to allow the
1277 # main thread to most likely be blocked in its wait() call.
1278 t = threading.Timer(0.2, kill_proc_timer_thread)
1279 t.start()
1280
Victor Stinner937ee9e2018-06-26 02:11:06 +02001281 if mswindows:
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001282 expected_errorcode = 1
1283 else:
1284 # Should be -9 because of the proc.kill() from the thread.
1285 expected_errorcode = -9
1286
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001287 # Wait for the process to finish; the thread should kill it
1288 # long before it finishes on its own. Supplying a timeout
1289 # triggers a different code path for better coverage.
Victor Stinner0d63bac2019-12-11 11:30:03 +01001290 proc.wait(timeout=support.SHORT_TIMEOUT)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001291 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001292 msg="unexpected result in wait from main thread")
1293
1294 # This should be a no-op with no change in returncode.
1295 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001296 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001297 msg="unexpected result in second main wait.")
1298
1299 t.join()
1300 # Ensure that all of the thread results are as expected.
1301 # When a race condition occurs in wait(), the returncode could
1302 # be set by the wrong thread that doesn't actually have it
1303 # leading to an incorrect value.
1304 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001305 ('thread-after-kill-and-wait', expected_errorcode),
1306 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001307 results)
1308
Victor Stinnerb3693582010-05-21 20:13:12 +00001309 def test_issue8780(self):
1310 # Ensure that stdout is inherited from the parent
1311 # if stdout=PIPE is not used
1312 code = ';'.join((
1313 'import subprocess, sys',
1314 'retcode = subprocess.call('
1315 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1316 'assert retcode == 0'))
1317 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001318 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001319
Tim Goldenaf5ac392010-08-06 13:03:56 +00001320 def test_handles_closed_on_exception(self):
1321 # If CreateProcess exits with an error, ensure the
1322 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001323 ifhandle, ifname = tempfile.mkstemp()
1324 ofhandle, ofname = tempfile.mkstemp()
1325 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001326 try:
1327 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1328 stderr=efhandle)
1329 except OSError:
1330 os.close(ifhandle)
1331 os.remove(ifname)
1332 os.close(ofhandle)
1333 os.remove(ofname)
1334 os.close(efhandle)
1335 os.remove(efname)
1336 self.assertFalse(os.path.exists(ifname))
1337 self.assertFalse(os.path.exists(ofname))
1338 self.assertFalse(os.path.exists(efname))
1339
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001340 def test_communicate_epipe(self):
1341 # Issue 10963: communicate() should hide EPIPE
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001342 p = subprocess.Popen(ZERO_RETURN_CMD,
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001343 stdin=subprocess.PIPE,
1344 stdout=subprocess.PIPE,
1345 stderr=subprocess.PIPE)
1346 self.addCleanup(p.stdout.close)
1347 self.addCleanup(p.stderr.close)
1348 self.addCleanup(p.stdin.close)
1349 p.communicate(b"x" * 2**20)
1350
Andrey Doroschenko645005e2019-11-17 17:08:31 +03001351 def test_repr(self):
1352 # Run a command that waits for user input, to check the repr() of
1353 # a Proc object while and after the sub-process runs.
1354 code = 'import sys; input(); sys.exit(57)'
1355 cmd = [sys.executable, '-c', code]
1356 result = "<Popen: returncode: {}"
1357
1358 with subprocess.Popen(
1359 cmd, stdin=subprocess.PIPE, universal_newlines=True) as proc:
1360 self.assertIsNone(proc.returncode)
1361 self.assertTrue(
1362 repr(proc).startswith(result.format(proc.returncode)) and
1363 repr(proc).endswith('>')
1364 )
1365
1366 proc.communicate(input='exit...\n')
1367 proc.wait()
1368
1369 self.assertIsNotNone(proc.returncode)
1370 self.assertTrue(
1371 repr(proc).startswith(result.format(proc.returncode)) and
1372 repr(proc).endswith('>')
1373 )
1374
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001375 def test_communicate_epipe_only_stdin(self):
1376 # Issue 10963: communicate() should hide EPIPE
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001377 p = subprocess.Popen(ZERO_RETURN_CMD,
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001378 stdin=subprocess.PIPE)
1379 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001380 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001381 p.communicate(b"x" * 2**20)
1382
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001383 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1384 "Requires signal.SIGUSR1")
1385 @unittest.skipUnless(hasattr(os, 'kill'),
1386 "Requires os.kill")
1387 @unittest.skipUnless(hasattr(os, 'getppid'),
1388 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001389 def test_communicate_eintr(self):
1390 # Issue #12493: communicate() should handle EINTR
1391 def handler(signum, frame):
1392 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001393 old_handler = signal.signal(signal.SIGUSR1, handler)
1394 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001395
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001396 args = [sys.executable, "-c",
1397 'import os, signal;'
1398 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001399 for stream in ('stdout', 'stderr'):
1400 kw = {stream: subprocess.PIPE}
1401 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001402 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001403 process.communicate()
1404
Tim Peterse718f612004-10-12 21:51:32 +00001405
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001406 # This test is Linux-ish specific for simplicity to at least have
1407 # some coverage. It is not a platform specific bug.
1408 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1409 "Linux specific")
1410 def test_failed_child_execute_fd_leak(self):
1411 """Test for the fork() failure fd leak reported in issue16327."""
1412 fd_directory = '/proc/%d/fd' % os.getpid()
1413 fds_before_popen = os.listdir(fd_directory)
1414 with self.assertRaises(PopenTestException):
1415 PopenExecuteChildRaises(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001416 ZERO_RETURN_CMD, stdin=subprocess.PIPE,
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001417 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1418
1419 # NOTE: This test doesn't verify that the real _execute_child
1420 # does not close the file descriptors itself on the way out
1421 # during an exception. Code inspection has confirmed that.
1422
1423 fds_after_exception = os.listdir(fd_directory)
1424 self.assertEqual(fds_before_popen, fds_after_exception)
1425
Victor Stinner937ee9e2018-06-26 02:11:06 +02001426 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001427 def test_file_not_found_includes_filename(self):
1428 with self.assertRaises(FileNotFoundError) as c:
1429 subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args'])
1430 self.assertEqual(c.exception.filename, '/opt/nonexistent_binary')
1431
Victor Stinner937ee9e2018-06-26 02:11:06 +02001432 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001433 def test_file_not_found_with_bad_cwd(self):
1434 with self.assertRaises(FileNotFoundError) as c:
1435 subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory')
1436 self.assertEqual(c.exception.filename, '/some/nonexistent/directory')
1437
Gregory P. Smith6e730002015-04-14 16:14:25 -07001438
1439class RunFuncTestCase(BaseTestCase):
1440 def run_python(self, code, **kwargs):
1441 """Run Python code in a subprocess using subprocess.run"""
1442 argv = [sys.executable, "-c", code]
1443 return subprocess.run(argv, **kwargs)
1444
1445 def test_returncode(self):
1446 # call() function with sequence argument
1447 cp = self.run_python("import sys; sys.exit(47)")
1448 self.assertEqual(cp.returncode, 47)
1449 with self.assertRaises(subprocess.CalledProcessError):
1450 cp.check_returncode()
1451
1452 def test_check(self):
1453 with self.assertRaises(subprocess.CalledProcessError) as c:
1454 self.run_python("import sys; sys.exit(47)", check=True)
1455 self.assertEqual(c.exception.returncode, 47)
1456
1457 def test_check_zero(self):
1458 # check_returncode shouldn't raise when returncode is zero
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001459 cp = subprocess.run(ZERO_RETURN_CMD, check=True)
Gregory P. Smith6e730002015-04-14 16:14:25 -07001460 self.assertEqual(cp.returncode, 0)
1461
1462 def test_timeout(self):
1463 # run() function with timeout argument; we want to test that the child
1464 # process gets killed when the timeout expires. If the child isn't
1465 # killed, this call will deadlock since subprocess.run waits for the
1466 # child.
1467 with self.assertRaises(subprocess.TimeoutExpired):
1468 self.run_python("while True: pass", timeout=0.0001)
1469
1470 def test_capture_stdout(self):
1471 # capture stdout with zero return code
1472 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1473 self.assertIn(b'BDFL', cp.stdout)
1474
1475 def test_capture_stderr(self):
1476 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1477 stderr=subprocess.PIPE)
1478 self.assertIn(b'BDFL', cp.stderr)
1479
1480 def test_check_output_stdin_arg(self):
1481 # run() can be called with stdin set to a file
1482 tf = tempfile.TemporaryFile()
1483 self.addCleanup(tf.close)
1484 tf.write(b'pear')
1485 tf.seek(0)
1486 cp = self.run_python(
1487 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1488 stdin=tf, stdout=subprocess.PIPE)
1489 self.assertIn(b'PEAR', cp.stdout)
1490
1491 def test_check_output_input_arg(self):
1492 # check_output() can be called with input set to a string
1493 cp = self.run_python(
1494 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1495 input=b'pear', stdout=subprocess.PIPE)
1496 self.assertIn(b'PEAR', cp.stdout)
1497
1498 def test_check_output_stdin_with_input_arg(self):
1499 # run() refuses to accept 'stdin' with 'input'
1500 tf = tempfile.TemporaryFile()
1501 self.addCleanup(tf.close)
1502 tf.write(b'pear')
1503 tf.seek(0)
1504 with self.assertRaises(ValueError,
1505 msg="Expected ValueError when stdin and input args supplied.") as c:
1506 output = self.run_python("print('will not be run')",
1507 stdin=tf, input=b'hare')
1508 self.assertIn('stdin', c.exception.args[0])
1509 self.assertIn('input', c.exception.args[0])
1510
1511 def test_check_output_timeout(self):
1512 with self.assertRaises(subprocess.TimeoutExpired) as c:
1513 cp = self.run_python((
1514 "import sys, time\n"
1515 "sys.stdout.write('BDFL')\n"
1516 "sys.stdout.flush()\n"
1517 "time.sleep(3600)"),
1518 # Some heavily loaded buildbots (sparc Debian 3.x) require
1519 # this much time to start and print.
1520 timeout=3, stdout=subprocess.PIPE)
1521 self.assertEqual(c.exception.output, b'BDFL')
1522 # output is aliased to stdout
1523 self.assertEqual(c.exception.stdout, b'BDFL')
1524
1525 def test_run_kwargs(self):
1526 newenv = os.environ.copy()
1527 newenv["FRUIT"] = "banana"
1528 cp = self.run_python(('import sys, os;'
1529 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1530 env=newenv)
1531 self.assertEqual(cp.returncode, 33)
1532
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001533 def test_run_with_pathlike_path(self):
1534 # bpo-31961: test run(pathlike_object)
1535 # the name of a command that can be run without
Min ho Kimc4cacc82019-07-31 08:16:13 +10001536 # any arguments that exit fast
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001537 prog = 'tree.com' if mswindows else 'ls'
1538 path = shutil.which(prog)
1539 if path is None:
1540 self.skipTest(f'{prog} required for this test')
1541 path = FakePath(path)
1542 res = subprocess.run(path, stdout=subprocess.DEVNULL)
1543 self.assertEqual(res.returncode, 0)
1544 with self.assertRaises(TypeError):
1545 subprocess.run(path, stdout=subprocess.DEVNULL, shell=True)
1546
1547 def test_run_with_bytes_path_and_arguments(self):
1548 # bpo-31961: test run([bytes_object, b'additional arguments'])
1549 path = os.fsencode(sys.executable)
1550 args = [path, '-c', b'import sys; sys.exit(57)']
1551 res = subprocess.run(args)
1552 self.assertEqual(res.returncode, 57)
1553
1554 def test_run_with_pathlike_path_and_arguments(self):
1555 # bpo-31961: test run([pathlike_object, 'additional arguments'])
1556 path = FakePath(sys.executable)
1557 args = [path, '-c', 'import sys; sys.exit(57)']
1558 res = subprocess.run(args)
1559 self.assertEqual(res.returncode, 57)
1560
Bo Baylesce0f33d2018-01-30 00:40:39 -06001561 def test_capture_output(self):
1562 cp = self.run_python(("import sys;"
1563 "sys.stdout.write('BDFL'); "
1564 "sys.stderr.write('FLUFL')"),
1565 capture_output=True)
1566 self.assertIn(b'BDFL', cp.stdout)
1567 self.assertIn(b'FLUFL', cp.stderr)
1568
1569 def test_stdout_with_capture_output_arg(self):
1570 # run() refuses to accept 'stdout' with 'capture_output'
1571 tf = tempfile.TemporaryFile()
1572 self.addCleanup(tf.close)
1573 with self.assertRaises(ValueError,
1574 msg=("Expected ValueError when stdout and capture_output "
1575 "args supplied.")) as c:
1576 output = self.run_python("print('will not be run')",
1577 capture_output=True, stdout=tf)
1578 self.assertIn('stdout', c.exception.args[0])
1579 self.assertIn('capture_output', c.exception.args[0])
1580
1581 def test_stderr_with_capture_output_arg(self):
1582 # run() refuses to accept 'stderr' with 'capture_output'
1583 tf = tempfile.TemporaryFile()
1584 self.addCleanup(tf.close)
1585 with self.assertRaises(ValueError,
1586 msg=("Expected ValueError when stderr and capture_output "
1587 "args supplied.")) as c:
1588 output = self.run_python("print('will not be run')",
1589 capture_output=True, stderr=tf)
1590 self.assertIn('stderr', c.exception.args[0])
1591 self.assertIn('capture_output', c.exception.args[0])
1592
Gregory P. Smith580d2782019-09-11 04:23:05 -05001593 # This test _might_ wind up a bit fragile on loaded build+test machines
1594 # as it depends on the timing with wide enough margins for normal situations
1595 # but does assert that it happened "soon enough" to believe the right thing
1596 # happened.
1597 @unittest.skipIf(mswindows, "requires posix like 'sleep' shell command")
1598 def test_run_with_shell_timeout_and_capture_output(self):
1599 """Output capturing after a timeout mustn't hang forever on open filehandles."""
1600 before_secs = time.monotonic()
1601 try:
1602 subprocess.run('sleep 3', shell=True, timeout=0.1,
1603 capture_output=True) # New session unspecified.
1604 except subprocess.TimeoutExpired as exc:
1605 after_secs = time.monotonic()
1606 stacks = traceback.format_exc() # assertRaises doesn't give this.
1607 else:
1608 self.fail("TimeoutExpired not raised.")
1609 self.assertLess(after_secs - before_secs, 1.5,
1610 msg="TimeoutExpired was delayed! Bad traceback:\n```\n"
1611 f"{stacks}```")
1612
Gregory P. Smith6e730002015-04-14 16:14:25 -07001613
Gregory P. Smith693aa802019-09-13 14:43:35 +01001614def _get_test_grp_name():
Victor Stinnerfaca8552019-09-25 15:52:49 +02001615 for name_group in ('staff', 'nogroup', 'grp', 'nobody', 'nfsnobody'):
Gregory P. Smith693aa802019-09-13 14:43:35 +01001616 if grp:
1617 try:
1618 grp.getgrnam(name_group)
1619 except KeyError:
1620 continue
1621 return name_group
1622 else:
1623 raise unittest.SkipTest('No identified group name to use for this test on this platform.')
1624
1625
Victor Stinner937ee9e2018-06-26 02:11:06 +02001626@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001627class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001628
Gregory P. Smith5591b022012-10-10 03:34:47 -07001629 def setUp(self):
1630 super().setUp()
1631 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1632
1633 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001634 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001635 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001636 except OSError as e:
1637 # This avoids hard coding the errno value or the OS perror()
1638 # string and instead capture the exception that we want to see
1639 # below for comparison.
1640 desired_exception = e
1641 else:
Martin Pantereb995702016-07-28 01:11:04 +00001642 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001643 self._nonexistent_dir)
1644 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001645
Gregory P. Smith5591b022012-10-10 03:34:47 -07001646 def test_exception_cwd(self):
1647 """Test error in the child raised in the parent for a bad cwd."""
1648 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001649 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001650 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001651 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001652 except OSError as e:
1653 # Test that the child process chdir failure actually makes
1654 # it up to the parent process as the correct exception.
1655 self.assertEqual(desired_exception.errno, e.errno)
1656 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001657 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001658 else:
1659 self.fail("Expected OSError: %s" % desired_exception)
1660
Gregory P. Smith5591b022012-10-10 03:34:47 -07001661 def test_exception_bad_executable(self):
1662 """Test error in the child raised in the parent for a bad executable."""
1663 desired_exception = self._get_chdir_exception()
1664 try:
1665 p = subprocess.Popen([sys.executable, "-c", ""],
1666 executable=self._nonexistent_dir)
1667 except OSError as e:
1668 # Test that the child process exec failure actually makes
1669 # it up to the parent process as the correct exception.
1670 self.assertEqual(desired_exception.errno, e.errno)
1671 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001672 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001673 else:
1674 self.fail("Expected OSError: %s" % desired_exception)
1675
1676 def test_exception_bad_args_0(self):
1677 """Test error in the child raised in the parent for a bad args[0]."""
1678 desired_exception = self._get_chdir_exception()
1679 try:
1680 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1681 except OSError as e:
1682 # Test that the child process exec failure actually makes
1683 # it up to the parent process as the correct exception.
1684 self.assertEqual(desired_exception.errno, e.errno)
1685 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001686 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001687 else:
1688 self.fail("Expected OSError: %s" % desired_exception)
1689
Ammar Askar3fc499b2017-09-06 02:41:30 -04001690 # We mock the __del__ method for Popen in the next two tests
1691 # because it does cleanup based on the pid returned by fork_exec
1692 # along with issuing a resource warning if it still exists. Since
1693 # we don't actually spawn a process in these tests we can forego
1694 # the destructor. An alternative would be to set _child_created to
1695 # False before the destructor is called but there is no easy way
1696 # to do that
1697 class PopenNoDestructor(subprocess.Popen):
1698 def __del__(self):
1699 pass
1700
1701 @mock.patch("subprocess._posixsubprocess.fork_exec")
1702 def test_exception_errpipe_normal(self, fork_exec):
1703 """Test error passing done through errpipe_write in the good case"""
1704 def proper_error(*args):
1705 errpipe_write = args[13]
1706 # Write the hex for the error code EISDIR: 'is a directory'
1707 err_code = '{:x}'.format(errno.EISDIR).encode()
1708 os.write(errpipe_write, b"OSError:" + err_code + b":")
1709 return 0
1710
1711 fork_exec.side_effect = proper_error
1712
Victor Stinner11045c92017-10-05 06:32:53 -07001713 with mock.patch("subprocess.os.waitpid",
1714 side_effect=ChildProcessError):
1715 with self.assertRaises(IsADirectoryError):
1716 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001717
1718 @mock.patch("subprocess._posixsubprocess.fork_exec")
1719 def test_exception_errpipe_bad_data(self, fork_exec):
1720 """Test error passing done through errpipe_write where its not
1721 in the expected format"""
1722 error_data = b"\xFF\x00\xDE\xAD"
1723 def bad_error(*args):
1724 errpipe_write = args[13]
1725 # Anything can be in the pipe, no assumptions should
1726 # be made about its encoding, so we'll write some
1727 # arbitrary hex bytes to test it out
1728 os.write(errpipe_write, error_data)
1729 return 0
1730
1731 fork_exec.side_effect = bad_error
1732
Victor Stinner11045c92017-10-05 06:32:53 -07001733 with mock.patch("subprocess.os.waitpid",
1734 side_effect=ChildProcessError):
1735 with self.assertRaises(subprocess.SubprocessError) as e:
1736 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001737
1738 self.assertIn(repr(error_data), str(e.exception))
1739
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001740 @unittest.skipIf(not os.path.exists('/proc/self/status'),
1741 "need /proc/self/status")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001742 def test_restore_signals(self):
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001743 # Blindly assume that cat exists on systems with /proc/self/status...
1744 default_proc_status = subprocess.check_output(
1745 ['cat', '/proc/self/status'],
1746 restore_signals=False)
1747 for line in default_proc_status.splitlines():
1748 if line.startswith(b'SigIgn'):
1749 default_sig_ign_mask = line
1750 break
1751 else:
1752 self.skipTest("SigIgn not found in /proc/self/status.")
1753 restored_proc_status = subprocess.check_output(
1754 ['cat', '/proc/self/status'],
1755 restore_signals=True)
1756 for line in restored_proc_status.splitlines():
1757 if line.startswith(b'SigIgn'):
1758 restored_sig_ign_mask = line
1759 break
1760 self.assertNotEqual(default_sig_ign_mask, restored_sig_ign_mask,
1761 msg="restore_signals=True should've unblocked "
1762 "SIGPIPE and friends.")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001763
1764 def test_start_new_session(self):
1765 # For code coverage of calling setsid(). We don't care if we get an
1766 # EPERM error from it depending on the test execution environment, that
1767 # still indicates that it was called.
1768 try:
1769 output = subprocess.check_output(
Victor Stinner58840432019-06-14 19:31:43 +02001770 [sys.executable, "-c", "import os; print(os.getsid(0))"],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001771 start_new_session=True)
1772 except OSError as e:
1773 if e.errno != errno.EPERM:
1774 raise
1775 else:
Victor Stinner58840432019-06-14 19:31:43 +02001776 parent_sid = os.getsid(0)
1777 child_sid = int(output)
1778 self.assertNotEqual(parent_sid, child_sid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001779
Patrick McLean2b2ead72019-09-12 10:15:44 -07001780 @unittest.skipUnless(hasattr(os, 'setreuid'), 'no setreuid on platform')
1781 def test_user(self):
1782 # For code coverage of the user parameter. We don't care if we get an
1783 # EPERM error from it depending on the test execution environment, that
1784 # still indicates that it was called.
1785
1786 uid = os.geteuid()
1787 test_users = [65534 if uid != 65534 else 65533, uid]
1788 name_uid = "nobody" if sys.platform != 'darwin' else "unknown"
1789
1790 if pwd is not None:
1791 test_users.append(name_uid)
1792
1793 for user in test_users:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001794 # posix_spawn() may be used with close_fds=False
1795 for close_fds in (False, True):
1796 with self.subTest(user=user, close_fds=close_fds):
1797 try:
1798 output = subprocess.check_output(
1799 [sys.executable, "-c",
1800 "import os; print(os.getuid())"],
1801 user=user,
1802 close_fds=close_fds)
1803 except PermissionError: # (EACCES, EPERM)
1804 pass
1805 except OSError as e:
1806 if e.errno not in (errno.EACCES, errno.EPERM):
1807 raise
Patrick McLean2b2ead72019-09-12 10:15:44 -07001808 else:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001809 if isinstance(user, str):
1810 user_uid = pwd.getpwnam(user).pw_uid
1811 else:
1812 user_uid = user
1813 child_user = int(output)
1814 self.assertEqual(child_user, user_uid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001815
1816 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001817 subprocess.check_call(ZERO_RETURN_CMD, user=-1)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001818
1819 if pwd is None:
1820 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001821 subprocess.check_call(ZERO_RETURN_CMD, user=name_uid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001822
1823 @unittest.skipIf(hasattr(os, 'setreuid'), 'setreuid() available on platform')
1824 def test_user_error(self):
1825 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001826 subprocess.check_call(ZERO_RETURN_CMD, user=65535)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001827
1828 @unittest.skipUnless(hasattr(os, 'setregid'), 'no setregid() on platform')
1829 def test_group(self):
1830 gid = os.getegid()
1831 group_list = [65534 if gid != 65534 else 65533]
Gregory P. Smith693aa802019-09-13 14:43:35 +01001832 name_group = _get_test_grp_name()
Patrick McLean2b2ead72019-09-12 10:15:44 -07001833
1834 if grp is not None:
1835 group_list.append(name_group)
1836
1837 for group in group_list + [gid]:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001838 # posix_spawn() may be used with close_fds=False
1839 for close_fds in (False, True):
1840 with self.subTest(group=group, close_fds=close_fds):
1841 try:
1842 output = subprocess.check_output(
1843 [sys.executable, "-c",
1844 "import os; print(os.getgid())"],
1845 group=group,
1846 close_fds=close_fds)
1847 except PermissionError: # (EACCES, EPERM)
1848 pass
Patrick McLean2b2ead72019-09-12 10:15:44 -07001849 else:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001850 if isinstance(group, str):
1851 group_gid = grp.getgrnam(group).gr_gid
1852 else:
1853 group_gid = group
Patrick McLean2b2ead72019-09-12 10:15:44 -07001854
Victor Stinnerfaca8552019-09-25 15:52:49 +02001855 child_group = int(output)
1856 self.assertEqual(child_group, group_gid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001857
1858 # make sure we bomb on negative values
1859 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001860 subprocess.check_call(ZERO_RETURN_CMD, group=-1)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001861
1862 if grp is None:
1863 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001864 subprocess.check_call(ZERO_RETURN_CMD, group=name_group)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001865
1866 @unittest.skipIf(hasattr(os, 'setregid'), 'setregid() available on platform')
1867 def test_group_error(self):
1868 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001869 subprocess.check_call(ZERO_RETURN_CMD, group=65535)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001870
1871 @unittest.skipUnless(hasattr(os, 'setgroups'), 'no setgroups() on platform')
1872 def test_extra_groups(self):
1873 gid = os.getegid()
1874 group_list = [65534 if gid != 65534 else 65533]
Gregory P. Smith693aa802019-09-13 14:43:35 +01001875 name_group = _get_test_grp_name()
Patrick McLean2b2ead72019-09-12 10:15:44 -07001876 perm_error = False
1877
1878 if grp is not None:
1879 group_list.append(name_group)
1880
1881 try:
1882 output = subprocess.check_output(
1883 [sys.executable, "-c",
1884 "import os, sys, json; json.dump(os.getgroups(), sys.stdout)"],
1885 extra_groups=group_list)
1886 except OSError as ex:
1887 if ex.errno != errno.EPERM:
1888 raise
1889 perm_error = True
1890
1891 else:
1892 parent_groups = os.getgroups()
1893 child_groups = json.loads(output)
1894
1895 if grp is not None:
1896 desired_gids = [grp.getgrnam(g).gr_gid if isinstance(g, str) else g
1897 for g in group_list]
1898 else:
1899 desired_gids = group_list
1900
1901 if perm_error:
1902 self.assertEqual(set(child_groups), set(parent_groups))
1903 else:
1904 self.assertEqual(set(desired_gids), set(child_groups))
1905
1906 # make sure we bomb on negative values
1907 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001908 subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[-1])
Patrick McLean2b2ead72019-09-12 10:15:44 -07001909
1910 if grp is None:
1911 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001912 subprocess.check_call(ZERO_RETURN_CMD,
Patrick McLean2b2ead72019-09-12 10:15:44 -07001913 extra_groups=[name_group])
1914
1915 @unittest.skipIf(hasattr(os, 'setgroups'), 'setgroups() available on platform')
1916 def test_extra_groups_error(self):
1917 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001918 subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[])
Patrick McLean2b2ead72019-09-12 10:15:44 -07001919
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07001920 @unittest.skipIf(mswindows or not hasattr(os, 'umask'),
1921 'POSIX umask() is not available.')
1922 def test_umask(self):
1923 tmpdir = None
1924 try:
1925 tmpdir = tempfile.mkdtemp()
1926 name = os.path.join(tmpdir, "beans")
1927 # We set an unusual umask in the child so as a unique mode
1928 # for us to test the child's touched file for.
1929 subprocess.check_call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001930 [sys.executable, "-c", f"open({name!r}, 'w').close()"],
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07001931 umask=0o053)
1932 # Ignore execute permissions entirely in our test,
1933 # filesystems could be mounted to ignore or force that.
1934 st_mode = os.stat(name).st_mode & 0o666
1935 expected_mode = 0o624
1936 self.assertEqual(expected_mode, st_mode,
1937 msg=f'{oct(expected_mode)} != {oct(st_mode)}')
1938 finally:
1939 if tmpdir is not None:
1940 shutil.rmtree(tmpdir)
1941
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001942 def test_run_abort(self):
1943 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001944 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001945 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001946 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001947 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001948 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001949
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001950 def test_CalledProcessError_str_signal(self):
1951 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
1952 error_string = str(err)
1953 # We're relying on the repr() of the signal.Signals intenum to provide
1954 # the word signal, the signal name and the numeric value.
1955 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00001956 # We're not being specific about the signal name as some signals have
1957 # multiple names and which name is revealed can vary.
1958 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001959 self.assertIn(str(signal.SIGABRT), error_string)
1960
1961 def test_CalledProcessError_str_unknown_signal(self):
1962 err = subprocess.CalledProcessError(-9876543, "fake cmd")
1963 error_string = str(err)
1964 self.assertIn("unknown signal 9876543.", error_string)
1965
1966 def test_CalledProcessError_str_non_zero(self):
1967 err = subprocess.CalledProcessError(2, "fake cmd")
1968 error_string = str(err)
1969 self.assertIn("non-zero exit status 2.", error_string)
1970
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001971 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001972 # DISCLAIMER: Setting environment variables is *not* a good use
1973 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001974 p = subprocess.Popen([sys.executable, "-c",
1975 'import sys,os;'
1976 'sys.stdout.write(os.getenv("FRUIT"))'],
1977 stdout=subprocess.PIPE,
1978 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02001979 with p:
1980 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001981
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001982 def test_preexec_exception(self):
1983 def raise_it():
1984 raise ValueError("What if two swallows carried a coconut?")
1985 try:
1986 p = subprocess.Popen([sys.executable, "-c", ""],
1987 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001988 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001989 self.assertTrue(
1990 subprocess._posixsubprocess,
1991 "Expected a ValueError from the preexec_fn")
1992 except ValueError as e:
1993 self.assertIn("coconut", e.args[0])
1994 else:
1995 self.fail("Exception raised by preexec_fn did not make it "
1996 "to the parent process.")
1997
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001998 class _TestExecuteChildPopen(subprocess.Popen):
1999 """Used to test behavior at the end of _execute_child."""
2000 def __init__(self, testcase, *args, **kwargs):
2001 self._testcase = testcase
2002 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002003
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002004 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08002005 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002006 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002007 finally:
2008 # Open a bunch of file descriptors and verify that
2009 # none of them are the same as the ones the Popen
2010 # instance is using for stdin/stdout/stderr.
2011 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
2012 for _ in range(8)]
2013 try:
2014 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002015 self._testcase.assertNotIn(
2016 fd, (self.stdin.fileno(), self.stdout.fileno(),
2017 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08002018 msg="At least one fd was closed early.")
2019 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01002020 for fd in devzero_fds:
2021 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002022
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002023 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
2024 def test_preexec_errpipe_does_not_double_close_pipes(self):
2025 """Issue16140: Don't double close pipes on preexec error."""
2026
2027 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08002028 raise subprocess.SubprocessError(
2029 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08002030
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08002031 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002032 self._TestExecuteChildPopen(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002033 self, ZERO_RETURN_CMD,
Gregory P. Smith12489d92012-11-11 01:37:02 -08002034 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2035 stderr=subprocess.PIPE, preexec_fn=raise_it)
2036
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00002037 def test_preexec_gc_module_failure(self):
2038 # This tests the code that disables garbage collection if the child
2039 # process will execute any Python.
2040 def raise_runtime_error():
2041 raise RuntimeError("this shouldn't escape")
2042 enabled = gc.isenabled()
2043 orig_gc_disable = gc.disable
2044 orig_gc_isenabled = gc.isenabled
2045 try:
2046 gc.disable()
2047 self.assertFalse(gc.isenabled())
2048 subprocess.call([sys.executable, '-c', ''],
2049 preexec_fn=lambda: None)
2050 self.assertFalse(gc.isenabled(),
2051 "Popen enabled gc when it shouldn't.")
2052
2053 gc.enable()
2054 self.assertTrue(gc.isenabled())
2055 subprocess.call([sys.executable, '-c', ''],
2056 preexec_fn=lambda: None)
2057 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
2058
2059 gc.disable = raise_runtime_error
2060 self.assertRaises(RuntimeError, subprocess.Popen,
2061 [sys.executable, '-c', ''],
2062 preexec_fn=lambda: None)
2063
2064 del gc.isenabled # force an AttributeError
2065 self.assertRaises(AttributeError, subprocess.Popen,
2066 [sys.executable, '-c', ''],
2067 preexec_fn=lambda: None)
2068 finally:
2069 gc.disable = orig_gc_disable
2070 gc.isenabled = orig_gc_isenabled
2071 if not enabled:
2072 gc.disable()
2073
Martin Panterf7fdbda2015-12-05 09:51:52 +00002074 @unittest.skipIf(
2075 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00002076 def test_preexec_fork_failure(self):
2077 # The internal code did not preserve the previous exception when
2078 # re-enabling garbage collection
2079 try:
2080 from resource import getrlimit, setrlimit, RLIMIT_NPROC
2081 except ImportError as err:
2082 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
2083 limits = getrlimit(RLIMIT_NPROC)
2084 [_, hard] = limits
2085 setrlimit(RLIMIT_NPROC, (0, hard))
2086 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00002087 try:
Martin Panterafdd5132015-11-30 02:21:41 +00002088 subprocess.call([sys.executable, '-c', ''],
2089 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00002090 except BlockingIOError:
2091 # Forking should raise EAGAIN, translated to BlockingIOError
2092 pass
2093 else:
2094 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00002095
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002096 def test_args_string(self):
2097 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03002098 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002099 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002100 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002101 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002102 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2103 sys.executable)
2104 os.chmod(fname, 0o700)
2105 p = subprocess.Popen(fname)
2106 p.wait()
2107 os.remove(fname)
2108 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002109
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002110 def test_invalid_args(self):
2111 # invalid arguments should raise ValueError
2112 self.assertRaises(ValueError, subprocess.call,
2113 [sys.executable, "-c",
2114 "import sys; sys.exit(47)"],
2115 startupinfo=47)
2116 self.assertRaises(ValueError, subprocess.call,
2117 [sys.executable, "-c",
2118 "import sys; sys.exit(47)"],
2119 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002120
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002121 def test_shell_sequence(self):
2122 # Run command through the shell (sequence)
2123 newenv = os.environ.copy()
2124 newenv["FRUIT"] = "apple"
2125 p = subprocess.Popen(["echo $FRUIT"], shell=1,
2126 stdout=subprocess.PIPE,
2127 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002128 with p:
2129 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002130
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002131 def test_shell_string(self):
2132 # Run command through the shell (string)
2133 newenv = os.environ.copy()
2134 newenv["FRUIT"] = "apple"
2135 p = subprocess.Popen("echo $FRUIT", shell=1,
2136 stdout=subprocess.PIPE,
2137 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002138 with p:
2139 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00002140
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002141 def test_call_string(self):
2142 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03002143 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002144 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002145 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002146 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002147 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2148 sys.executable)
2149 os.chmod(fname, 0o700)
2150 rc = subprocess.call(fname)
2151 os.remove(fname)
2152 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00002153
Stefan Krah9542cc62010-07-19 14:20:53 +00002154 def test_specific_shell(self):
2155 # Issue #9265: Incorrect name passed as arg[0].
2156 shells = []
2157 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
2158 for name in ['bash', 'ksh']:
2159 sh = os.path.join(prefix, name)
2160 if os.path.isfile(sh):
2161 shells.append(sh)
2162 if not shells: # Will probably work for any shell but csh.
2163 self.skipTest("bash or ksh required for this test")
2164 sh = '/bin/sh'
2165 if os.path.isfile(sh) and not os.path.islink(sh):
2166 # Test will fail if /bin/sh is a symlink to csh.
2167 shells.append(sh)
2168 for sh in shells:
2169 p = subprocess.Popen("echo $0", executable=sh, shell=True,
2170 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002171 with p:
2172 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00002173
Florent Xicluna4886d242010-03-08 13:27:26 +00002174 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00002175 # Do not inherit file handles from the parent.
2176 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07002177 # Also set the SIGINT handler to the default to make sure it's not
2178 # being ignored (some tests rely on that.)
2179 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
2180 try:
2181 p = subprocess.Popen([sys.executable, "-c", """if 1:
2182 import sys, time
2183 sys.stdout.write('x\\n')
2184 sys.stdout.flush()
2185 time.sleep(30)
2186 """],
2187 close_fds=True,
2188 stdin=subprocess.PIPE,
2189 stdout=subprocess.PIPE,
2190 stderr=subprocess.PIPE)
2191 finally:
2192 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00002193 # Wait for the interpreter to be completely initialized before
2194 # sending any signal.
2195 p.stdout.read(1)
2196 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00002197 return p
2198
Charles-François Natali53221e32013-01-12 16:52:20 +01002199 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
2200 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002201 def _kill_dead_process(self, method, *args):
2202 # Do not inherit file handles from the parent.
2203 # It should fix failures on some platforms.
2204 p = subprocess.Popen([sys.executable, "-c", """if 1:
2205 import sys, time
2206 sys.stdout.write('x\\n')
2207 sys.stdout.flush()
2208 """],
2209 close_fds=True,
2210 stdin=subprocess.PIPE,
2211 stdout=subprocess.PIPE,
2212 stderr=subprocess.PIPE)
2213 # Wait for the interpreter to be completely initialized before
2214 # sending any signal.
2215 p.stdout.read(1)
2216 # The process should end after this
2217 time.sleep(1)
2218 # This shouldn't raise even though the child is now dead
2219 getattr(p, method)(*args)
2220 p.communicate()
2221
Florent Xicluna4886d242010-03-08 13:27:26 +00002222 def test_send_signal(self):
2223 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00002224 _, stderr = p.communicate()
2225 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002226 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00002227
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002228 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002229 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00002230 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002231 self.assertEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002232 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00002233
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002234 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002235 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00002236 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002237 self.assertEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002238 self.assertEqual(p.wait(), -signal.SIGTERM)
2239
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002240 def test_send_signal_dead(self):
2241 # Sending a signal to a dead process
2242 self._kill_dead_process('send_signal', signal.SIGINT)
2243
2244 def test_kill_dead(self):
2245 # Killing a dead process
2246 self._kill_dead_process('kill')
2247
2248 def test_terminate_dead(self):
2249 # Terminating a dead process
2250 self._kill_dead_process('terminate')
2251
Victor Stinnerdaf45552013-08-28 00:53:59 +02002252 def _save_fds(self, save_fds):
2253 fds = []
2254 for fd in save_fds:
2255 inheritable = os.get_inheritable(fd)
2256 saved = os.dup(fd)
2257 fds.append((fd, saved, inheritable))
2258 return fds
2259
2260 def _restore_fds(self, fds):
2261 for fd, saved, inheritable in fds:
2262 os.dup2(saved, fd, inheritable=inheritable)
2263 os.close(saved)
2264
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002265 def check_close_std_fds(self, fds):
2266 # Issue #9905: test that subprocess pipes still work properly with
2267 # some standard fds closed
2268 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02002269 saved_fds = self._save_fds(fds)
2270 for fd, saved, inheritable in saved_fds:
2271 if fd == 0:
2272 stdin = saved
2273 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002274 try:
2275 for fd in fds:
2276 os.close(fd)
2277 out, err = subprocess.Popen([sys.executable, "-c",
2278 'import sys;'
2279 'sys.stdout.write("apple");'
2280 'sys.stdout.flush();'
2281 'sys.stderr.write("orange")'],
2282 stdin=stdin,
2283 stdout=subprocess.PIPE,
2284 stderr=subprocess.PIPE).communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002285 self.assertEqual(out, b'apple')
2286 self.assertEqual(err, b'orange')
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002287 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002288 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002289
2290 def test_close_fd_0(self):
2291 self.check_close_std_fds([0])
2292
2293 def test_close_fd_1(self):
2294 self.check_close_std_fds([1])
2295
2296 def test_close_fd_2(self):
2297 self.check_close_std_fds([2])
2298
2299 def test_close_fds_0_1(self):
2300 self.check_close_std_fds([0, 1])
2301
2302 def test_close_fds_0_2(self):
2303 self.check_close_std_fds([0, 2])
2304
2305 def test_close_fds_1_2(self):
2306 self.check_close_std_fds([1, 2])
2307
2308 def test_close_fds_0_1_2(self):
2309 # Issue #10806: test that subprocess pipes still work properly with
2310 # all standard fds closed.
2311 self.check_close_std_fds([0, 1, 2])
2312
Gregory P. Smith53dd8162013-12-01 16:03:24 -08002313 def test_small_errpipe_write_fd(self):
2314 """Issue #15798: Popen should work when stdio fds are available."""
2315 new_stdin = os.dup(0)
2316 new_stdout = os.dup(1)
2317 try:
2318 os.close(0)
2319 os.close(1)
2320
2321 # Side test: if errpipe_write fails to have its CLOEXEC
2322 # flag set this should cause the parent to think the exec
2323 # failed. Extremely unlikely: everyone supports CLOEXEC.
2324 subprocess.Popen([
2325 sys.executable, "-c",
2326 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
2327 finally:
2328 # Restore original stdin and stdout
2329 os.dup2(new_stdin, 0)
2330 os.dup2(new_stdout, 1)
2331 os.close(new_stdin)
2332 os.close(new_stdout)
2333
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002334 def test_remapping_std_fds(self):
2335 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002336 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002337 try:
2338 temp_fds = [fd for fd, fname in temps]
2339
2340 # unlink the files -- we won't need to reopen them
2341 for fd, fname in temps:
2342 os.unlink(fname)
2343
2344 # write some data to what will become stdin, and rewind
2345 os.write(temp_fds[1], b"STDIN")
2346 os.lseek(temp_fds[1], 0, 0)
2347
2348 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02002349 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002350 try:
2351 # duplicate the file objects over the standard fd's
2352 for fd, temp_fd in enumerate(temp_fds):
2353 os.dup2(temp_fd, fd)
2354
2355 # now use those files in the "wrong" order, so that subprocess
2356 # has to rearrange them in the child
2357 p = subprocess.Popen([sys.executable, "-c",
2358 'import sys; got = sys.stdin.read();'
2359 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2360 stdin=temp_fds[1],
2361 stdout=temp_fds[2],
2362 stderr=temp_fds[0])
2363 p.wait()
2364 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002365 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002366
2367 for fd in temp_fds:
2368 os.lseek(fd, 0, 0)
2369
2370 out = os.read(temp_fds[2], 1024)
Victor Stinner6cac1132019-12-08 08:38:16 +01002371 err = os.read(temp_fds[0], 1024).strip()
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002372 self.assertEqual(out, b"got STDIN")
2373 self.assertEqual(err, b"err")
2374
2375 finally:
2376 for fd in temp_fds:
2377 os.close(fd)
2378
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002379 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
2380 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002381 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002382 temp_fds = [fd for fd, fname in temps]
2383 try:
2384 # unlink the files -- we won't need to reopen them
2385 for fd, fname in temps:
2386 os.unlink(fname)
2387
2388 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02002389 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002390 try:
2391 # duplicate the temp files over the standard fd's 0, 1, 2
2392 for fd, temp_fd in enumerate(temp_fds):
2393 os.dup2(temp_fd, fd)
2394
2395 # write some data to what will become stdin, and rewind
2396 os.write(stdin_no, b"STDIN")
2397 os.lseek(stdin_no, 0, 0)
2398
2399 # now use those files in the given order, so that subprocess
2400 # has to rearrange them in the child
2401 p = subprocess.Popen([sys.executable, "-c",
2402 'import sys; got = sys.stdin.read();'
2403 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2404 stdin=stdin_no,
2405 stdout=stdout_no,
2406 stderr=stderr_no)
2407 p.wait()
2408
2409 for fd in temp_fds:
2410 os.lseek(fd, 0, 0)
2411
2412 out = os.read(stdout_no, 1024)
Victor Stinner6cac1132019-12-08 08:38:16 +01002413 err = os.read(stderr_no, 1024).strip()
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002414 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002415 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002416
2417 self.assertEqual(out, b"got STDIN")
2418 self.assertEqual(err, b"err")
2419
2420 finally:
2421 for fd in temp_fds:
2422 os.close(fd)
2423
2424 # When duping fds, if there arises a situation where one of the fds is
2425 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
2426 # This tests all combinations of this.
2427 def test_swap_fds(self):
2428 self.check_swap_fds(0, 1, 2)
2429 self.check_swap_fds(0, 2, 1)
2430 self.check_swap_fds(1, 0, 2)
2431 self.check_swap_fds(1, 2, 0)
2432 self.check_swap_fds(2, 0, 1)
2433 self.check_swap_fds(2, 1, 0)
2434
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +03002435 def _check_swap_std_fds_with_one_closed(self, from_fds, to_fds):
2436 saved_fds = self._save_fds(range(3))
2437 try:
2438 for from_fd in from_fds:
2439 with tempfile.TemporaryFile() as f:
2440 os.dup2(f.fileno(), from_fd)
2441
2442 fd_to_close = (set(range(3)) - set(from_fds)).pop()
2443 os.close(fd_to_close)
2444
2445 arg_names = ['stdin', 'stdout', 'stderr']
2446 kwargs = {}
2447 for from_fd, to_fd in zip(from_fds, to_fds):
2448 kwargs[arg_names[to_fd]] = from_fd
2449
2450 code = textwrap.dedent(r'''
2451 import os, sys
2452 skipped_fd = int(sys.argv[1])
2453 for fd in range(3):
2454 if fd != skipped_fd:
2455 os.write(fd, str(fd).encode('ascii'))
2456 ''')
2457
2458 skipped_fd = (set(range(3)) - set(to_fds)).pop()
2459
2460 rc = subprocess.call([sys.executable, '-c', code, str(skipped_fd)],
2461 **kwargs)
2462 self.assertEqual(rc, 0)
2463
2464 for from_fd, to_fd in zip(from_fds, to_fds):
2465 os.lseek(from_fd, 0, os.SEEK_SET)
2466 read_bytes = os.read(from_fd, 1024)
2467 read_fds = list(map(int, read_bytes.decode('ascii')))
2468 msg = textwrap.dedent(f"""
2469 When testing {from_fds} to {to_fds} redirection,
2470 parent descriptor {from_fd} got redirected
2471 to descriptor(s) {read_fds} instead of descriptor {to_fd}.
2472 """)
2473 self.assertEqual([to_fd], read_fds, msg)
2474 finally:
2475 self._restore_fds(saved_fds)
2476
2477 # Check that subprocess can remap std fds correctly even
2478 # if one of them is closed (#32844).
2479 def test_swap_std_fds_with_one_closed(self):
2480 for from_fds in itertools.combinations(range(3), 2):
2481 for to_fds in itertools.permutations(range(3), 2):
2482 self._check_swap_std_fds_with_one_closed(from_fds, to_fds)
2483
Victor Stinner13bb71c2010-04-23 21:41:56 +00002484 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00002485 def prepare():
2486 raise ValueError("surrogate:\uDCff")
2487
2488 try:
2489 subprocess.call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002490 ZERO_RETURN_CMD,
Victor Stinner4d078042010-04-23 19:28:32 +00002491 preexec_fn=prepare)
2492 except ValueError as err:
2493 # Pure Python implementations keeps the message
2494 self.assertIsNone(subprocess._posixsubprocess)
2495 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002496 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00002497 # _posixsubprocess uses a default message
2498 self.assertIsNotNone(subprocess._posixsubprocess)
2499 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
2500 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002501 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00002502
Victor Stinner13bb71c2010-04-23 21:41:56 +00002503 def test_undecodable_env(self):
2504 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01002505 encoded_value = value.encode("ascii", "surrogateescape")
2506
Victor Stinner13bb71c2010-04-23 21:41:56 +00002507 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002508 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002509 env = os.environ.copy()
2510 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01002511 # Use C locale to get ASCII for the locale encoding to force
Michael Felt89d79b12018-08-26 19:29:36 +02002512 # surrogate-escaping of \xFF in the child process
Victor Stinnerebc78d22010-10-14 10:38:17 +00002513 env['LC_ALL'] = 'C'
Michael Felt89d79b12018-08-26 19:29:36 +02002514 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002515 stdout = subprocess.check_output(
2516 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002517 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002518 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002519 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002520
2521 # test bytes
2522 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002523 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002524 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01002525 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002526 stdout = subprocess.check_output(
2527 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002528 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002529 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002530 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002531
Victor Stinnerb745a742010-05-18 17:17:23 +00002532 def test_bytes_program(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002533 abs_program = os.fsencode(ZERO_RETURN_CMD[0])
2534 args = list(ZERO_RETURN_CMD[1:])
2535 path, program = os.path.split(ZERO_RETURN_CMD[0])
Victor Stinnerb745a742010-05-18 17:17:23 +00002536 program = os.fsencode(program)
2537
2538 # absolute bytes path
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002539 exitcode = subprocess.call([abs_program]+args)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002540 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002541
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002542 # absolute bytes path as a string
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002543 cmd = b"'%s' %s" % (abs_program, " ".join(args).encode("utf-8"))
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002544 exitcode = subprocess.call(cmd, shell=True)
2545 self.assertEqual(exitcode, 0)
2546
Victor Stinnerb745a742010-05-18 17:17:23 +00002547 # bytes program, unicode PATH
2548 env = os.environ.copy()
2549 env["PATH"] = path
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002550 exitcode = subprocess.call([program]+args, env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002551 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002552
2553 # bytes program, bytes PATH
2554 envb = os.environb.copy()
2555 envb[b"PATH"] = os.fsencode(path)
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002556 exitcode = subprocess.call([program]+args, env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002557 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002558
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002559 def test_pipe_cloexec(self):
2560 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2561 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2562
2563 p1 = subprocess.Popen([sys.executable, sleeper],
2564 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2565 stderr=subprocess.PIPE, close_fds=False)
2566
2567 self.addCleanup(p1.communicate, b'')
2568
2569 p2 = subprocess.Popen([sys.executable, fd_status],
2570 stdout=subprocess.PIPE, close_fds=False)
2571
2572 output, error = p2.communicate()
2573 result_fds = set(map(int, output.split(b',')))
2574 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2575 p1.stderr.fileno()])
2576
2577 self.assertFalse(result_fds & unwanted_fds,
2578 "Expected no fds from %r to be open in child, "
2579 "found %r" %
2580 (unwanted_fds, result_fds & unwanted_fds))
2581
2582 def test_pipe_cloexec_real_tools(self):
2583 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2584 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2585
2586 subdata = b'zxcvbn'
2587 data = subdata * 4 + b'\n'
2588
2589 p1 = subprocess.Popen([sys.executable, qcat],
2590 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2591 close_fds=False)
2592
2593 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2594 stdin=p1.stdout, stdout=subprocess.PIPE,
2595 close_fds=False)
2596
2597 self.addCleanup(p1.wait)
2598 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002599 def kill_p1():
2600 try:
2601 p1.terminate()
2602 except ProcessLookupError:
2603 pass
2604 def kill_p2():
2605 try:
2606 p2.terminate()
2607 except ProcessLookupError:
2608 pass
2609 self.addCleanup(kill_p1)
2610 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002611
2612 p1.stdin.write(data)
2613 p1.stdin.close()
2614
2615 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2616
2617 self.assertTrue(readfiles, "The child hung")
2618 self.assertEqual(p2.stdout.read(), data)
2619
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002620 p1.stdout.close()
2621 p2.stdout.close()
2622
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002623 def test_close_fds(self):
2624 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2625
2626 fds = os.pipe()
2627 self.addCleanup(os.close, fds[0])
2628 self.addCleanup(os.close, fds[1])
2629
2630 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002631 # add a bunch more fds
2632 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002633 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002634 self.addCleanup(os.close, fd)
2635 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002636
Victor Stinnerdaf45552013-08-28 00:53:59 +02002637 for fd in open_fds:
2638 os.set_inheritable(fd, True)
2639
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002640 p = subprocess.Popen([sys.executable, fd_status],
2641 stdout=subprocess.PIPE, close_fds=False)
2642 output, ignored = p.communicate()
2643 remaining_fds = set(map(int, output.split(b',')))
2644
2645 self.assertEqual(remaining_fds & open_fds, open_fds,
2646 "Some fds were closed")
2647
2648 p = subprocess.Popen([sys.executable, fd_status],
2649 stdout=subprocess.PIPE, close_fds=True)
2650 output, ignored = p.communicate()
2651 remaining_fds = set(map(int, output.split(b',')))
2652
2653 self.assertFalse(remaining_fds & open_fds,
2654 "Some fds were left open")
2655 self.assertIn(1, remaining_fds, "Subprocess failed")
2656
Gregory P. Smith8facece2012-01-21 14:01:08 -08002657 # Keep some of the fd's we opened open in the subprocess.
2658 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2659 fds_to_keep = set(open_fds.pop() for _ in range(8))
2660 p = subprocess.Popen([sys.executable, fd_status],
2661 stdout=subprocess.PIPE, close_fds=True,
izbyshev2d8f0632017-12-19 03:26:49 +07002662 pass_fds=fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002663 output, ignored = p.communicate()
2664 remaining_fds = set(map(int, output.split(b',')))
2665
izbyshev2d8f0632017-12-19 03:26:49 +07002666 self.assertFalse((remaining_fds - fds_to_keep) & open_fds,
Gregory P. Smith8facece2012-01-21 14:01:08 -08002667 "Some fds not in pass_fds were left open")
2668 self.assertIn(1, remaining_fds, "Subprocess failed")
2669
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002670
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002671 @unittest.skipIf(sys.platform.startswith("freebsd") and
2672 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2673 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002674 def test_close_fds_when_max_fd_is_lowered(self):
2675 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2676 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2677
Gregory P. Smith634aa682014-06-15 17:51:04 -07002678 # This launches the meat of the test in a child process to
2679 # avoid messing with the larger unittest processes maximum
2680 # number of file descriptors.
2681 # This process launches:
2682 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2683 # a bunch of high open fds above the new lower rlimit.
2684 # Those are reported via stdout before launching a new
2685 # process with close_fds=False to run the actual test:
2686 # +--> The TEST: This one launches a fd_status.py
2687 # subprocess with close_fds=True so we can find out if
2688 # any of the fds above the lowered rlimit are still open.
2689 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2690 '''
2691 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002692 open_fds = set()
2693 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002694 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002695 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002696 open_fds.add(fd)
2697
2698 # Leave a two pairs of low ones available for use by the
2699 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002700 # We also leave 10 more open as some Python buildbots run into
2701 # "too many open files" errors during the test if we do not.
2702 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002703 os.close(fd)
2704 open_fds.remove(fd)
2705
2706 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002707 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002708 os.set_inheritable(fd, True)
2709
2710 max_fd_open = max(open_fds)
2711
Gregory P. Smith634aa682014-06-15 17:51:04 -07002712 # Communicate the open_fds to the parent unittest.TestCase process.
2713 print(','.join(map(str, sorted(open_fds))))
2714 sys.stdout.flush()
2715
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002716 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2717 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002718 # 29 is lower than the highest fds we are leaving open.
2719 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002720 # Launch a new Python interpreter with our low fd rlim_cur that
2721 # inherits open fds above that limit. It then uses subprocess
2722 # with close_fds=True to get a report of open fds in the child.
2723 # An explicit list of fds to check is passed to fd_status.py as
2724 # letting fd_status rely on its default logic would miss the
2725 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002726 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002727 [sys.executable, '-c',
2728 textwrap.dedent("""
2729 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002730 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002731 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002732 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002733 """.format(max_fd=max_fd_open+1))],
2734 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002735 finally:
2736 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002737 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002738
2739 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002740 output_lines = output.splitlines()
2741 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002742 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002743 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2744 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002745
Gregory P. Smith634aa682014-06-15 17:51:04 -07002746 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002747 msg="Some fds were left open.")
2748
2749
Victor Stinner88701e22011-06-01 13:13:04 +02002750 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2751 # descriptor of a pipe closed in the parent process is valid in the
2752 # child process according to fstat(), but the mode of the file
2753 # descriptor is invalid, and read or write raise an error.
2754 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002755 def test_pass_fds(self):
2756 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2757
2758 open_fds = set()
2759
2760 for x in range(5):
2761 fds = os.pipe()
2762 self.addCleanup(os.close, fds[0])
2763 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002764 os.set_inheritable(fds[0], True)
2765 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002766 open_fds.update(fds)
2767
2768 for fd in open_fds:
2769 p = subprocess.Popen([sys.executable, fd_status],
2770 stdout=subprocess.PIPE, close_fds=True,
2771 pass_fds=(fd, ))
2772 output, ignored = p.communicate()
2773
2774 remaining_fds = set(map(int, output.split(b',')))
2775 to_be_closed = open_fds - {fd}
2776
2777 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2778 self.assertFalse(remaining_fds & to_be_closed,
2779 "fd to be closed passed")
2780
2781 # pass_fds overrides close_fds with a warning.
2782 with self.assertWarns(RuntimeWarning) as context:
2783 self.assertFalse(subprocess.call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002784 ZERO_RETURN_CMD,
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002785 close_fds=False, pass_fds=(fd, )))
2786 self.assertIn('overriding close_fds', str(context.warning))
2787
Victor Stinnerdaf45552013-08-28 00:53:59 +02002788 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002789 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002790
2791 inheritable, non_inheritable = os.pipe()
2792 self.addCleanup(os.close, inheritable)
2793 self.addCleanup(os.close, non_inheritable)
2794 os.set_inheritable(inheritable, True)
2795 os.set_inheritable(non_inheritable, False)
2796 pass_fds = (inheritable, non_inheritable)
2797 args = [sys.executable, script]
2798 args += list(map(str, pass_fds))
2799
2800 p = subprocess.Popen(args,
2801 stdout=subprocess.PIPE, close_fds=True,
2802 pass_fds=pass_fds)
2803 output, ignored = p.communicate()
2804 fds = set(map(int, output.split(b',')))
2805
2806 # the inheritable file descriptor must be inherited, so its inheritable
2807 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002808 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002809
2810 # inheritable flag must not be changed in the parent process
2811 self.assertEqual(os.get_inheritable(inheritable), True)
2812 self.assertEqual(os.get_inheritable(non_inheritable), False)
2813
Gregory P. Smithce344102018-09-10 17:46:22 -07002814
2815 # bpo-32270: Ensure that descriptors specified in pass_fds
2816 # are inherited even if they are used in redirections.
2817 # Contributed by @izbyshev.
2818 def test_pass_fds_redirected(self):
2819 """Regression test for https://bugs.python.org/issue32270."""
2820 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2821 pass_fds = []
2822 for _ in range(2):
2823 fd = os.open(os.devnull, os.O_RDWR)
2824 self.addCleanup(os.close, fd)
2825 pass_fds.append(fd)
2826
2827 stdout_r, stdout_w = os.pipe()
2828 self.addCleanup(os.close, stdout_r)
2829 self.addCleanup(os.close, stdout_w)
2830 pass_fds.insert(1, stdout_w)
2831
2832 with subprocess.Popen([sys.executable, fd_status],
2833 stdin=pass_fds[0],
2834 stdout=pass_fds[1],
2835 stderr=pass_fds[2],
2836 close_fds=True,
2837 pass_fds=pass_fds):
2838 output = os.read(stdout_r, 1024)
2839 fds = {int(num) for num in output.split(b',')}
2840
2841 self.assertEqual(fds, {0, 1, 2} | frozenset(pass_fds), f"output={output!a}")
2842
2843
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002844 def test_stdout_stdin_are_single_inout_fd(self):
2845 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002846 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002847 stdout=inout, stdin=inout)
2848 p.wait()
2849
2850 def test_stdout_stderr_are_single_inout_fd(self):
2851 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002852 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002853 stdout=inout, stderr=inout)
2854 p.wait()
2855
2856 def test_stderr_stdin_are_single_inout_fd(self):
2857 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002858 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002859 stderr=inout, stdin=inout)
2860 p.wait()
2861
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002862 def test_wait_when_sigchild_ignored(self):
2863 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2864 sigchild_ignore = support.findfile("sigchild_ignore.py",
2865 subdir="subprocessdata")
2866 p = subprocess.Popen([sys.executable, sigchild_ignore],
2867 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2868 stdout, stderr = p.communicate()
2869 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002870 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002871 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002872
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002873 def test_select_unbuffered(self):
2874 # Issue #11459: bufsize=0 should really set the pipes as
2875 # unbuffered (and therefore let select() work properly).
2876 select = support.import_module("select")
2877 p = subprocess.Popen([sys.executable, "-c",
2878 'import sys;'
2879 'sys.stdout.write("apple")'],
2880 stdout=subprocess.PIPE,
2881 bufsize=0)
2882 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002883 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002884 try:
2885 self.assertEqual(f.read(4), b"appl")
2886 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2887 finally:
2888 p.wait()
2889
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002890 def test_zombie_fast_process_del(self):
2891 # Issue #12650: on Unix, if Popen.__del__() was called before the
2892 # process exited, it wouldn't be added to subprocess._active, and would
2893 # remain a zombie.
2894 # spawn a Popen, and delete its reference before it exits
2895 p = subprocess.Popen([sys.executable, "-c",
2896 'import sys, time;'
2897 'time.sleep(0.2)'],
2898 stdout=subprocess.PIPE,
2899 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002900 self.addCleanup(p.stdout.close)
2901 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002902 ident = id(p)
2903 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002904 with support.check_warnings(('', ResourceWarning)):
2905 p = None
2906
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002907 if mswindows:
2908 # subprocess._active is not used on Windows and is set to None.
2909 self.assertIsNone(subprocess._active)
2910 else:
2911 # check that p is in the active processes list
2912 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002913
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002914 def test_leak_fast_process_del_killed(self):
2915 # Issue #12650: on Unix, if Popen.__del__() was called before the
2916 # process exited, and the process got killed by a signal, it would never
2917 # be removed from subprocess._active, which triggered a FD and memory
2918 # leak.
2919 # spawn a Popen, delete its reference and kill it
2920 p = subprocess.Popen([sys.executable, "-c",
2921 'import time;'
2922 'time.sleep(3)'],
2923 stdout=subprocess.PIPE,
2924 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002925 self.addCleanup(p.stdout.close)
2926 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002927 ident = id(p)
2928 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002929 with support.check_warnings(('', ResourceWarning)):
2930 p = None
2931
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002932 os.kill(pid, signal.SIGKILL)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002933 if mswindows:
2934 # subprocess._active is not used on Windows and is set to None.
2935 self.assertIsNone(subprocess._active)
2936 else:
2937 # check that p is in the active processes list
2938 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002939
2940 # let some time for the process to exit, and create a new Popen: this
2941 # should trigger the wait() of p
2942 time.sleep(0.2)
Victor Stinnerb31206a2018-01-25 19:06:05 +01002943 with self.assertRaises(OSError):
Victor Stinner9a83f652017-08-21 23:51:31 +02002944 with subprocess.Popen(NONEXISTING_CMD,
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002945 stdout=subprocess.PIPE,
2946 stderr=subprocess.PIPE) as proc:
2947 pass
2948 # p should have been wait()ed on, and removed from the _active list
2949 self.assertRaises(OSError, os.waitpid, pid, 0)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002950 if mswindows:
2951 # subprocess._active is not used on Windows and is set to None.
2952 self.assertIsNone(subprocess._active)
2953 else:
2954 self.assertNotIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002955
Charles-François Natali249cdc32013-08-25 18:24:45 +02002956 def test_close_fds_after_preexec(self):
2957 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2958
2959 # this FD is used as dup2() target by preexec_fn, and should be closed
2960 # in the child process
2961 fd = os.dup(1)
2962 self.addCleanup(os.close, fd)
2963
2964 p = subprocess.Popen([sys.executable, fd_status],
2965 stdout=subprocess.PIPE, close_fds=True,
2966 preexec_fn=lambda: os.dup2(1, fd))
2967 output, ignored = p.communicate()
2968
2969 remaining_fds = set(map(int, output.split(b',')))
2970
2971 self.assertNotIn(fd, remaining_fds)
2972
Victor Stinner8f437aa2014-10-05 17:25:19 +02002973 @support.cpython_only
2974 def test_fork_exec(self):
2975 # Issue #22290: fork_exec() must not crash on memory allocation failure
2976 # or other errors
2977 import _posixsubprocess
2978 gc_enabled = gc.isenabled()
2979 try:
2980 # Use a preexec function and enable the garbage collector
2981 # to force fork_exec() to re-enable the garbage collector
2982 # on error.
2983 func = lambda: None
2984 gc.enable()
2985
Victor Stinner8f437aa2014-10-05 17:25:19 +02002986 for args, exe_list, cwd, env_list in (
2987 (123, [b"exe"], None, [b"env"]),
2988 ([b"arg"], 123, None, [b"env"]),
2989 ([b"arg"], [b"exe"], 123, [b"env"]),
2990 ([b"arg"], [b"exe"], None, 123),
2991 ):
Patrick McLean2b2ead72019-09-12 10:15:44 -07002992 with self.assertRaises(TypeError) as err:
Victor Stinner8f437aa2014-10-05 17:25:19 +02002993 _posixsubprocess.fork_exec(
2994 args, exe_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002995 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02002996 -1, -1, -1, -1,
2997 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07002998 True, True,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07002999 False, [], 0, -1,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003000 func)
3001 # Attempt to prevent
3002 # "TypeError: fork_exec() takes exactly N arguments (M given)"
3003 # from passing the test. More refactoring to have us start
3004 # with a valid *args list, confirm a good call with that works
3005 # before mutating it in various ways to ensure that bad calls
3006 # with individual arg type errors raise a typeerror would be
3007 # ideal. Saving that for a future PR...
3008 self.assertNotIn('takes exactly', str(err.exception))
Victor Stinner8f437aa2014-10-05 17:25:19 +02003009 finally:
3010 if not gc_enabled:
3011 gc.disable()
3012
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003013 @support.cpython_only
3014 def test_fork_exec_sorted_fd_sanity_check(self):
3015 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
3016 import _posixsubprocess
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003017 class BadInt:
3018 first = True
3019 def __init__(self, value):
3020 self.value = value
3021 def __int__(self):
3022 if self.first:
3023 self.first = False
3024 return self.value
3025 raise ValueError
3026
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003027 gc_enabled = gc.isenabled()
3028 try:
3029 gc.enable()
3030
3031 for fds_to_keep in (
3032 (-1, 2, 3, 4, 5), # Negative number.
3033 ('str', 4), # Not an int.
3034 (18, 23, 42, 2**63), # Out of range.
3035 (5, 4), # Not sorted.
3036 (6, 7, 7, 8), # Duplicate.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003037 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003038 ):
3039 with self.assertRaises(
3040 ValueError,
3041 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
3042 _posixsubprocess.fork_exec(
3043 [b"false"], [b"false"],
3044 True, fds_to_keep, None, [b"env"],
3045 -1, -1, -1, -1,
3046 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003047 True, True,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07003048 None, None, None, -1,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003049 None)
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003050 self.assertIn('fds_to_keep', str(c.exception))
3051 finally:
3052 if not gc_enabled:
3053 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02003054
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003055 def test_communicate_BrokenPipeError_stdin_close(self):
3056 # By not setting stdout or stderr or a timeout we force the fast path
3057 # that just calls _stdin_write() internally due to our mock.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003058 proc = subprocess.Popen(ZERO_RETURN_CMD)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003059 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3060 mock_proc_stdin.close.side_effect = BrokenPipeError
3061 proc.communicate() # Should swallow BrokenPipeError from close.
3062 mock_proc_stdin.close.assert_called_with()
3063
3064 def test_communicate_BrokenPipeError_stdin_write(self):
3065 # By not setting stdout or stderr or a timeout we force the fast path
3066 # that just calls _stdin_write() internally due to our mock.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003067 proc = subprocess.Popen(ZERO_RETURN_CMD)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003068 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3069 mock_proc_stdin.write.side_effect = BrokenPipeError
3070 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
3071 mock_proc_stdin.write.assert_called_once_with(b'stuff')
3072 mock_proc_stdin.close.assert_called_once_with()
3073
3074 def test_communicate_BrokenPipeError_stdin_flush(self):
3075 # Setting stdin and stdout forces the ._communicate() code path.
3076 # python -h exits faster than python -c pass (but spams stdout).
3077 proc = subprocess.Popen([sys.executable, '-h'],
3078 stdin=subprocess.PIPE,
3079 stdout=subprocess.PIPE)
3080 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
3081 open(os.devnull, 'wb') as dev_null:
3082 mock_proc_stdin.flush.side_effect = BrokenPipeError
3083 # because _communicate registers a selector using proc.stdin...
3084 mock_proc_stdin.fileno.return_value = dev_null.fileno()
3085 # _communicate() should swallow BrokenPipeError from flush.
3086 proc.communicate(b'stuff')
3087 mock_proc_stdin.flush.assert_called_once_with()
3088
3089 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
3090 # Setting stdin and stdout forces the ._communicate() code path.
3091 # python -h exits faster than python -c pass (but spams stdout).
3092 proc = subprocess.Popen([sys.executable, '-h'],
3093 stdin=subprocess.PIPE,
3094 stdout=subprocess.PIPE)
3095 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3096 mock_proc_stdin.close.side_effect = BrokenPipeError
3097 # _communicate() should swallow BrokenPipeError from close.
3098 proc.communicate(timeout=999)
3099 mock_proc_stdin.close.assert_called_once_with()
3100
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003101 @unittest.skipUnless(_testcapi is not None
3102 and hasattr(_testcapi, 'W_STOPCODE'),
3103 'need _testcapi.W_STOPCODE')
3104 def test_stopped(self):
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003105 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003106 args = ZERO_RETURN_CMD
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003107 proc = subprocess.Popen(args)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003108
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003109 # Wait until the real process completes to avoid zombie process
3110 pid = proc.pid
3111 pid, status = os.waitpid(pid, 0)
3112 self.assertEqual(status, 0)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003113
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003114 status = _testcapi.W_STOPCODE(3)
3115 with mock.patch('subprocess.os.waitpid', return_value=(pid, status)):
3116 returncode = proc.wait()
Victor Stinnercdee3f12017-06-26 17:23:03 +02003117
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003118 self.assertEqual(returncode, -3)
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003119
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003120
Victor Stinner937ee9e2018-06-26 02:11:06 +02003121@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00003122class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00003123
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003124 def test_startupinfo(self):
3125 # startupinfo argument
3126 # We uses hardcoded constants, because we do not want to
3127 # depend on win32all.
3128 STARTF_USESHOWWINDOW = 1
3129 SW_MAXIMIZE = 3
3130 startupinfo = subprocess.STARTUPINFO()
3131 startupinfo.dwFlags = STARTF_USESHOWWINDOW
3132 startupinfo.wShowWindow = SW_MAXIMIZE
3133 # Since Python is a console process, it won't be affected
3134 # by wShowWindow, but the argument should be silently
3135 # ignored
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003136 subprocess.call(ZERO_RETURN_CMD,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003137 startupinfo=startupinfo)
3138
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05303139 def test_startupinfo_keywords(self):
3140 # startupinfo argument
3141 # We use hardcoded constants, because we do not want to
3142 # depend on win32all.
3143 STARTF_USERSHOWWINDOW = 1
3144 SW_MAXIMIZE = 3
3145 startupinfo = subprocess.STARTUPINFO(
3146 dwFlags=STARTF_USERSHOWWINDOW,
3147 wShowWindow=SW_MAXIMIZE
3148 )
3149 # Since Python is a console process, it won't be affected
3150 # by wShowWindow, but the argument should be silently
3151 # ignored
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003152 subprocess.call(ZERO_RETURN_CMD,
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05303153 startupinfo=startupinfo)
3154
Victor Stinner483422f2018-07-05 22:54:17 +02003155 def test_startupinfo_copy(self):
3156 # bpo-34044: Popen must not modify input STARTUPINFO structure
3157 startupinfo = subprocess.STARTUPINFO()
3158 startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
3159 startupinfo.wShowWindow = subprocess.SW_HIDE
3160
3161 # Call Popen() twice with the same startupinfo object to make sure
3162 # that it's not modified
3163 for _ in range(2):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003164 cmd = ZERO_RETURN_CMD
Victor Stinner483422f2018-07-05 22:54:17 +02003165 with open(os.devnull, 'w') as null:
3166 proc = subprocess.Popen(cmd,
3167 stdout=null,
3168 stderr=subprocess.STDOUT,
3169 startupinfo=startupinfo)
3170 with proc:
3171 proc.communicate()
3172 self.assertEqual(proc.returncode, 0)
3173
3174 self.assertEqual(startupinfo.dwFlags,
3175 subprocess.STARTF_USESHOWWINDOW)
3176 self.assertIsNone(startupinfo.hStdInput)
3177 self.assertIsNone(startupinfo.hStdOutput)
3178 self.assertIsNone(startupinfo.hStdError)
3179 self.assertEqual(startupinfo.wShowWindow, subprocess.SW_HIDE)
3180 self.assertEqual(startupinfo.lpAttributeList, {"handle_list": []})
3181
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003182 def test_creationflags(self):
3183 # creationflags argument
3184 CREATE_NEW_CONSOLE = 16
3185 sys.stderr.write(" a DOS box should flash briefly ...\n")
3186 subprocess.call(sys.executable +
3187 ' -c "import time; time.sleep(0.25)"',
3188 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003189
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003190 def test_invalid_args(self):
3191 # invalid arguments should raise ValueError
3192 self.assertRaises(ValueError, subprocess.call,
3193 [sys.executable, "-c",
3194 "import sys; sys.exit(47)"],
3195 preexec_fn=lambda: 1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003196
Oren Milman0b3a87e2017-09-14 22:30:28 +03003197 @support.cpython_only
3198 def test_issue31471(self):
3199 # There shouldn't be an assertion failure in Popen() in case the env
3200 # argument has a bad keys() method.
3201 class BadEnv(dict):
3202 keys = None
3203 with self.assertRaises(TypeError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003204 subprocess.Popen(ZERO_RETURN_CMD, env=BadEnv())
Oren Milman0b3a87e2017-09-14 22:30:28 +03003205
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003206 def test_close_fds(self):
3207 # close file descriptors
3208 rc = subprocess.call([sys.executable, "-c",
3209 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003210 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003211 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003212
Segev Finerb2a60832017-12-18 11:28:19 +02003213 def test_close_fds_with_stdio(self):
3214 import msvcrt
3215
3216 fds = os.pipe()
3217 self.addCleanup(os.close, fds[0])
3218 self.addCleanup(os.close, fds[1])
3219
3220 handles = []
3221 for fd in fds:
3222 os.set_inheritable(fd, True)
3223 handles.append(msvcrt.get_osfhandle(fd))
3224
3225 p = subprocess.Popen([sys.executable, "-c",
3226 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3227 stdout=subprocess.PIPE, close_fds=False)
3228 stdout, stderr = p.communicate()
3229 self.assertEqual(p.returncode, 0)
3230 int(stdout.strip()) # Check that stdout is an integer
3231
3232 p = subprocess.Popen([sys.executable, "-c",
3233 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3234 stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
3235 stdout, stderr = p.communicate()
3236 self.assertEqual(p.returncode, 1)
3237 self.assertIn(b"OSError", stderr)
3238
3239 # The same as the previous call, but with an empty handle_list
3240 handle_list = []
3241 startupinfo = subprocess.STARTUPINFO()
3242 startupinfo.lpAttributeList = {"handle_list": handle_list}
3243 p = subprocess.Popen([sys.executable, "-c",
3244 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3245 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3246 startupinfo=startupinfo, close_fds=True)
3247 stdout, stderr = p.communicate()
3248 self.assertEqual(p.returncode, 1)
3249 self.assertIn(b"OSError", stderr)
3250
3251 # Check for a warning due to using handle_list and close_fds=False
3252 with support.check_warnings((".*overriding close_fds", RuntimeWarning)):
3253 startupinfo = subprocess.STARTUPINFO()
3254 startupinfo.lpAttributeList = {"handle_list": handles[:]}
3255 p = subprocess.Popen([sys.executable, "-c",
3256 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3257 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3258 startupinfo=startupinfo, close_fds=False)
3259 stdout, stderr = p.communicate()
3260 self.assertEqual(p.returncode, 0)
3261
3262 def test_empty_attribute_list(self):
3263 startupinfo = subprocess.STARTUPINFO()
3264 startupinfo.lpAttributeList = {}
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003265 subprocess.call(ZERO_RETURN_CMD,
Segev Finerb2a60832017-12-18 11:28:19 +02003266 startupinfo=startupinfo)
3267
3268 def test_empty_handle_list(self):
3269 startupinfo = subprocess.STARTUPINFO()
3270 startupinfo.lpAttributeList = {"handle_list": []}
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003271 subprocess.call(ZERO_RETURN_CMD,
Segev Finerb2a60832017-12-18 11:28:19 +02003272 startupinfo=startupinfo)
3273
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003274 def test_shell_sequence(self):
3275 # Run command through the shell (sequence)
3276 newenv = os.environ.copy()
3277 newenv["FRUIT"] = "physalis"
3278 p = subprocess.Popen(["set"], shell=1,
3279 stdout=subprocess.PIPE,
3280 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003281 with p:
3282 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00003283
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003284 def test_shell_string(self):
3285 # Run command through the shell (string)
3286 newenv = os.environ.copy()
3287 newenv["FRUIT"] = "physalis"
3288 p = subprocess.Popen("set", shell=1,
3289 stdout=subprocess.PIPE,
3290 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003291 with p:
3292 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003293
Steve Dower050acae2016-09-06 20:16:17 -07003294 def test_shell_encodings(self):
3295 # Run command through the shell (string)
3296 for enc in ['ansi', 'oem']:
3297 newenv = os.environ.copy()
3298 newenv["FRUIT"] = "physalis"
3299 p = subprocess.Popen("set", shell=1,
3300 stdout=subprocess.PIPE,
3301 env=newenv,
3302 encoding=enc)
3303 with p:
3304 self.assertIn("physalis", p.stdout.read(), enc)
3305
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003306 def test_call_string(self):
3307 # call() function with string argument on Windows
3308 rc = subprocess.call(sys.executable +
3309 ' -c "import sys; sys.exit(47)"')
3310 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003311
Florent Xicluna4886d242010-03-08 13:27:26 +00003312 def _kill_process(self, method, *args):
3313 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00003314 p = subprocess.Popen([sys.executable, "-c", """if 1:
3315 import sys, time
3316 sys.stdout.write('x\\n')
3317 sys.stdout.flush()
3318 time.sleep(30)
3319 """],
3320 stdin=subprocess.PIPE,
3321 stdout=subprocess.PIPE,
3322 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003323 with p:
3324 # Wait for the interpreter to be completely initialized before
3325 # sending any signal.
3326 p.stdout.read(1)
3327 getattr(p, method)(*args)
3328 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01003329 self.assertEqual(stderr, b'')
Victor Stinner7438c612016-05-20 12:43:15 +02003330 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00003331 self.assertNotEqual(returncode, 0)
3332
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003333 def _kill_dead_process(self, method, *args):
3334 p = subprocess.Popen([sys.executable, "-c", """if 1:
3335 import sys, time
3336 sys.stdout.write('x\\n')
3337 sys.stdout.flush()
3338 sys.exit(42)
3339 """],
3340 stdin=subprocess.PIPE,
3341 stdout=subprocess.PIPE,
3342 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003343 with p:
3344 # Wait for the interpreter to be completely initialized before
3345 # sending any signal.
3346 p.stdout.read(1)
3347 # The process should end after this
3348 time.sleep(1)
3349 # This shouldn't raise even though the child is now dead
3350 getattr(p, method)(*args)
3351 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01003352 self.assertEqual(stderr, b'')
Victor Stinner7438c612016-05-20 12:43:15 +02003353 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003354 self.assertEqual(rc, 42)
3355
Florent Xicluna4886d242010-03-08 13:27:26 +00003356 def test_send_signal(self):
3357 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00003358
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003359 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003360 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00003361
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003362 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003363 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00003364
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003365 def test_send_signal_dead(self):
3366 self._kill_dead_process('send_signal', signal.SIGTERM)
3367
3368 def test_kill_dead(self):
3369 self._kill_dead_process('kill')
3370
3371 def test_terminate_dead(self):
3372 self._kill_dead_process('terminate')
3373
Martin Panter23172bd2016-04-16 11:28:10 +00003374class MiscTests(unittest.TestCase):
Gregory P. Smithf4d644f2018-01-29 21:27:39 -08003375
3376 class RecordingPopen(subprocess.Popen):
3377 """A Popen that saves a reference to each instance for testing."""
3378 instances_created = []
3379
3380 def __init__(self, *args, **kwargs):
3381 super().__init__(*args, **kwargs)
3382 self.instances_created.append(self)
3383
3384 @mock.patch.object(subprocess.Popen, "_communicate")
3385 def _test_keyboardinterrupt_no_kill(self, popener, mock__communicate,
3386 **kwargs):
3387 """Fake a SIGINT happening during Popen._communicate() and ._wait().
3388
3389 This avoids the need to actually try and get test environments to send
3390 and receive signals reliably across platforms. The net effect of a ^C
3391 happening during a blocking subprocess execution which we want to clean
3392 up from is a KeyboardInterrupt coming out of communicate() or wait().
3393 """
3394
3395 mock__communicate.side_effect = KeyboardInterrupt
3396 try:
3397 with mock.patch.object(subprocess.Popen, "_wait") as mock__wait:
3398 # We patch out _wait() as no signal was involved so the
3399 # child process isn't actually going to exit rapidly.
3400 mock__wait.side_effect = KeyboardInterrupt
3401 with mock.patch.object(subprocess, "Popen",
3402 self.RecordingPopen):
3403 with self.assertRaises(KeyboardInterrupt):
3404 popener([sys.executable, "-c",
3405 "import time\ntime.sleep(9)\nimport sys\n"
3406 "sys.stderr.write('\\n!runaway child!\\n')"],
3407 stdout=subprocess.DEVNULL, **kwargs)
3408 for call in mock__wait.call_args_list[1:]:
3409 self.assertNotEqual(
3410 call, mock.call(timeout=None),
3411 "no open-ended wait() after the first allowed: "
3412 f"{mock__wait.call_args_list}")
3413 sigint_calls = []
3414 for call in mock__wait.call_args_list:
3415 if call == mock.call(timeout=0.25): # from Popen.__init__
3416 sigint_calls.append(call)
3417 self.assertLessEqual(mock__wait.call_count, 2,
3418 msg=mock__wait.call_args_list)
3419 self.assertEqual(len(sigint_calls), 1,
3420 msg=mock__wait.call_args_list)
3421 finally:
3422 # cleanup the forgotten (due to our mocks) child process
3423 process = self.RecordingPopen.instances_created.pop()
3424 process.kill()
3425 process.wait()
3426 self.assertEqual([], self.RecordingPopen.instances_created)
3427
3428 def test_call_keyboardinterrupt_no_kill(self):
3429 self._test_keyboardinterrupt_no_kill(subprocess.call, timeout=6.282)
3430
3431 def test_run_keyboardinterrupt_no_kill(self):
3432 self._test_keyboardinterrupt_no_kill(subprocess.run, timeout=6.282)
3433
3434 def test_context_manager_keyboardinterrupt_no_kill(self):
3435 def popen_via_context_manager(*args, **kwargs):
3436 with subprocess.Popen(*args, **kwargs) as unused_process:
3437 raise KeyboardInterrupt # Test how __exit__ handles ^C.
3438 self._test_keyboardinterrupt_no_kill(popen_via_context_manager)
3439
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003440 def test_getoutput(self):
3441 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
3442 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
3443 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00003444
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003445 # we use mkdtemp in the next line to create an empty directory
3446 # under our exclusive control; from that, we can invent a pathname
3447 # that we _know_ won't exist. This is guaranteed to fail.
3448 dir = None
3449 try:
3450 dir = tempfile.mkdtemp()
3451 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00003452 status, output = subprocess.getstatusoutput(
Victor Stinner937ee9e2018-06-26 02:11:06 +02003453 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003454 self.assertNotEqual(status, 0)
3455 finally:
3456 if dir is not None:
3457 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00003458
Gregory P. Smithace55862015-04-07 15:57:54 -07003459 def test__all__(self):
3460 """Ensure that __all__ is populated properly."""
Patrick McLean2b2ead72019-09-12 10:15:44 -07003461 intentionally_excluded = {"list2cmdline", "Handle", "pwd", "grp"}
Gregory P. Smithace55862015-04-07 15:57:54 -07003462 exported = set(subprocess.__all__)
3463 possible_exports = set()
3464 import types
3465 for name, value in subprocess.__dict__.items():
3466 if name.startswith('_'):
3467 continue
3468 if isinstance(value, (types.ModuleType,)):
3469 continue
3470 possible_exports.add(name)
3471 self.assertEqual(exported, possible_exports - intentionally_excluded)
3472
3473
Martin Panter23172bd2016-04-16 11:28:10 +00003474@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
3475 "Test needs selectors.PollSelector")
3476class ProcessTestCaseNoPoll(ProcessTestCase):
3477 def setUp(self):
3478 self.orig_selector = subprocess._PopenSelector
3479 subprocess._PopenSelector = selectors.SelectSelector
3480 ProcessTestCase.setUp(self)
3481
3482 def tearDown(self):
3483 subprocess._PopenSelector = self.orig_selector
3484 ProcessTestCase.tearDown(self)
3485
Gregory P. Smithd06fa472009-07-04 02:46:54 +00003486
Victor Stinner937ee9e2018-06-26 02:11:06 +02003487@unittest.skipUnless(mswindows, "Windows-specific tests")
Tim Golden126c2962010-08-11 14:20:40 +00003488class CommandsWithSpaces (BaseTestCase):
3489
3490 def setUp(self):
3491 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03003492 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00003493 self.fname = fname.lower ()
3494 os.write(f, b"import sys;"
3495 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
3496 )
3497 os.close(f)
3498
3499 def tearDown(self):
3500 os.remove(self.fname)
3501 super().tearDown()
3502
3503 def with_spaces(self, *args, **kwargs):
3504 kwargs['stdout'] = subprocess.PIPE
3505 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02003506 with p:
3507 self.assertEqual(
3508 p.stdout.read ().decode("mbcs"),
3509 "2 [%r, 'ab cd']" % self.fname
3510 )
Tim Golden126c2962010-08-11 14:20:40 +00003511
3512 def test_shell_string_with_spaces(self):
3513 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003514 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3515 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003516
3517 def test_shell_sequence_with_spaces(self):
3518 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003519 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003520
3521 def test_noshell_string_with_spaces(self):
3522 # call() function with string argument with spaces on Windows
3523 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3524 "ab cd"))
3525
3526 def test_noshell_sequence_with_spaces(self):
3527 # call() function with sequence argument with spaces on Windows
3528 self.with_spaces([sys.executable, self.fname, "ab cd"])
3529
Brian Curtin79cdb662010-12-03 02:46:02 +00003530
Georg Brandla86b2622012-02-20 21:34:57 +01003531class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00003532
3533 def test_pipe(self):
3534 with subprocess.Popen([sys.executable, "-c",
3535 "import sys;"
3536 "sys.stdout.write('stdout');"
3537 "sys.stderr.write('stderr');"],
3538 stdout=subprocess.PIPE,
3539 stderr=subprocess.PIPE) as proc:
3540 self.assertEqual(proc.stdout.read(), b"stdout")
Victor Stinner6cac1132019-12-08 08:38:16 +01003541 self.assertEqual(proc.stderr.read(), b"stderr")
Brian Curtin79cdb662010-12-03 02:46:02 +00003542
3543 self.assertTrue(proc.stdout.closed)
3544 self.assertTrue(proc.stderr.closed)
3545
3546 def test_returncode(self):
3547 with subprocess.Popen([sys.executable, "-c",
3548 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07003549 pass
3550 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00003551 self.assertEqual(proc.returncode, 100)
3552
3553 def test_communicate_stdin(self):
3554 with subprocess.Popen([sys.executable, "-c",
3555 "import sys;"
3556 "sys.exit(sys.stdin.read() == 'context')"],
3557 stdin=subprocess.PIPE) as proc:
3558 proc.communicate(b"context")
3559 self.assertEqual(proc.returncode, 1)
3560
3561 def test_invalid_args(self):
Victor Stinnerb31206a2018-01-25 19:06:05 +01003562 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02003563 with subprocess.Popen(NONEXISTING_CMD,
Brian Curtin79cdb662010-12-03 02:46:02 +00003564 stdout=subprocess.PIPE,
3565 stderr=subprocess.PIPE) as proc:
3566 pass
3567
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003568 def test_broken_pipe_cleanup(self):
3569 """Broken pipe error should not prevent wait() (Issue 21619)"""
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003570 proc = subprocess.Popen(ZERO_RETURN_CMD,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003571 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003572 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003573 proc = proc.__enter__()
3574 # Prepare to send enough data to overflow any OS pipe buffering and
3575 # guarantee a broken pipe error. Data is held in BufferedWriter
3576 # buffer until closed.
3577 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003578 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003579 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02003580 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003581 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003582 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003583
Brian Curtin79cdb662010-12-03 02:46:02 +00003584
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003585if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04003586 unittest.main()