blob: 434ba567db0a5604d8824e1cab7b55c51fabe8cf [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
Hai Shi0c4f0f32020-06-30 21:46:31 +08004from test.support import import_helper
5from test.support import os_helper
6from test.support import warnings_helper
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00007import subprocess
8import sys
9import signal
Gregory P. Smith112bb3a2011-03-15 14:55:17 -040010import io
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +030011import itertools
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000012import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +000013import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000014import tempfile
15import time
Gregory P. Smith580d2782019-09-11 04:23:05 -050016import traceback
Guido van Rossum48b069a2020-04-07 09:50:06 -070017import types
Charles-François Natali3a4586a2013-11-08 19:56:59 +010018import selectors
Ezio Melotti184bdfb2010-02-18 09:37:05 +000019import sysconfig
Gregory P. Smith51ee2702010-12-13 07:59:39 +000020import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040021import shutil
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020022import threading
Benjamin Petersonb870aa12011-12-10 12:44:25 -050023import gc
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030024import textwrap
Patrick McLean2b2ead72019-09-12 10:15:44 -070025import json
Hai Shi0c4f0f32020-06-30 21:46:31 +080026from test.support.os_helper import FakePath
Benjamin Peterson964561b2011-12-10 12:31:42 -050027
28try:
Victor Stinner7b7c6dc2017-08-10 12:37:39 +020029 import _testcapi
30except ImportError:
31 _testcapi = None
32
Patrick McLean2b2ead72019-09-12 10:15:44 -070033try:
34 import pwd
35except ImportError:
36 pwd = None
37try:
38 import grp
39except ImportError:
40 grp = None
Victor Stinner8f4ef3b2019-07-01 18:28:25 +020041
Steve Dower22d06982016-09-06 19:38:15 -070042if support.PGO:
43 raise unittest.SkipTest("test is not helpful for PGO")
44
Victor Stinner937ee9e2018-06-26 02:11:06 +020045mswindows = (sys.platform == "win32")
46
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000047#
48# Depends on the following external programs: Python
49#
50
Victor Stinner937ee9e2018-06-26 02:11:06 +020051if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000052 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
53 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000054else:
55 SETBINARY = ''
56
Victor Stinner9a83f652017-08-21 23:51:31 +020057NONEXISTING_CMD = ('nonexisting_i_hope',)
Victor Stinnerb31206a2018-01-25 19:06:05 +010058# Ignore errors that indicate the command was not found
59NONEXISTING_ERRORS = (FileNotFoundError, NotADirectoryError, PermissionError)
Victor Stinner9a83f652017-08-21 23:51:31 +020060
Gregory P. Smith67b93f82019-10-12 16:35:53 -070061ZERO_RETURN_CMD = (sys.executable, '-c', 'pass')
62
63
64def setUpModule():
65 shell_true = shutil.which('true')
Pablo Galindo46113e02019-10-13 02:40:24 +010066 if shell_true is None:
67 return
Gregory P. Smith67b93f82019-10-12 16:35:53 -070068 if (os.access(shell_true, os.X_OK) and
69 subprocess.run([shell_true]).returncode == 0):
70 global ZERO_RETURN_CMD
71 ZERO_RETURN_CMD = (shell_true,) # Faster than Python startup.
72
Florent Xiclunab1e94e82010-02-27 22:12:37 +000073
Florent Xiclunac049d872010-03-27 22:47:23 +000074class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000075 def setUp(self):
76 # Try to minimize the number of children we have so this test
77 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000078 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000079
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000080 def tearDown(self):
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +030081 if not mswindows:
82 # subprocess._active is not used on Windows and is set to None.
83 for inst in subprocess._active:
84 inst.wait()
85 subprocess._cleanup()
86 self.assertFalse(
87 subprocess._active, "subprocess._active not empty"
88 )
Victor Stinnercc42c122017-07-28 18:00:22 +020089 self.doCleanups()
90 support.reap_children()
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000091
Florent Xiclunac049d872010-03-27 22:47:23 +000092
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080093class PopenTestException(Exception):
94 pass
95
96
97class PopenExecuteChildRaises(subprocess.Popen):
98 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
99 _execute_child fails.
100 """
101 def _execute_child(self, *args, **kwargs):
102 raise PopenTestException("Forced Exception for Test")
103
104
Florent Xiclunac049d872010-03-27 22:47:23 +0000105class ProcessTestCase(BaseTestCase):
106
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700107 def test_io_buffered_by_default(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700108 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700109 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
110 stderr=subprocess.PIPE)
111 try:
112 self.assertIsInstance(p.stdin, io.BufferedIOBase)
113 self.assertIsInstance(p.stdout, io.BufferedIOBase)
114 self.assertIsInstance(p.stderr, io.BufferedIOBase)
115 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700116 p.stdin.close()
117 p.stdout.close()
118 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700119 p.wait()
120
121 def test_io_unbuffered_works(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700122 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700123 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
124 stderr=subprocess.PIPE, bufsize=0)
125 try:
126 self.assertIsInstance(p.stdin, io.RawIOBase)
127 self.assertIsInstance(p.stdout, io.RawIOBase)
128 self.assertIsInstance(p.stderr, io.RawIOBase)
129 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700130 p.stdin.close()
131 p.stdout.close()
132 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700133 p.wait()
134
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000135 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000136 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000137 rc = subprocess.call([sys.executable, "-c",
138 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000139 self.assertEqual(rc, 47)
140
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400141 def test_call_timeout(self):
142 # call() function with timeout argument; we want to test that the child
143 # process gets killed when the timeout expires. If the child isn't
144 # killed, this call will deadlock since subprocess.call waits for the
145 # child.
146 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
147 [sys.executable, "-c", "while True: pass"],
148 timeout=0.1)
149
Peter Astrand454f7672005-01-01 09:36:35 +0000150 def test_check_call_zero(self):
151 # check_call() function with zero return code
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700152 rc = subprocess.check_call(ZERO_RETURN_CMD)
Peter Astrand454f7672005-01-01 09:36:35 +0000153 self.assertEqual(rc, 0)
154
155 def test_check_call_nonzero(self):
156 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000157 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000158 subprocess.check_call([sys.executable, "-c",
159 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000160 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000161
Georg Brandlf9734072008-12-07 15:30:06 +0000162 def test_check_output(self):
163 # check_output() function with zero return code
164 output = subprocess.check_output(
165 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000166 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000167
168 def test_check_output_nonzero(self):
169 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000170 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000171 subprocess.check_output(
172 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000173 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000174
175 def test_check_output_stderr(self):
176 # check_output() function stderr redirected to stdout
177 output = subprocess.check_output(
178 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
179 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000180 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000181
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300182 def test_check_output_stdin_arg(self):
183 # check_output() can be called with stdin set to a file
184 tf = tempfile.TemporaryFile()
185 self.addCleanup(tf.close)
186 tf.write(b'pear')
187 tf.seek(0)
188 output = subprocess.check_output(
189 [sys.executable, "-c",
190 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
191 stdin=tf)
192 self.assertIn(b'PEAR', output)
193
194 def test_check_output_input_arg(self):
195 # check_output() can be called with input set to a string
196 output = subprocess.check_output(
197 [sys.executable, "-c",
198 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
199 input=b'pear')
200 self.assertIn(b'PEAR', output)
201
Georg Brandlf9734072008-12-07 15:30:06 +0000202 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300203 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000204 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000205 output = subprocess.check_output(
206 [sys.executable, "-c", "print('will not be run')"],
207 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000208 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000209 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000210
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300211 def test_check_output_stdin_with_input_arg(self):
212 # check_output() refuses to accept 'stdin' with 'input'
213 tf = tempfile.TemporaryFile()
214 self.addCleanup(tf.close)
215 tf.write(b'pear')
216 tf.seek(0)
217 with self.assertRaises(ValueError) as c:
218 output = subprocess.check_output(
219 [sys.executable, "-c", "print('will not be run')"],
220 stdin=tf, input=b'hare')
221 self.fail("Expected ValueError when stdin and input args supplied.")
222 self.assertIn('stdin', c.exception.args[0])
223 self.assertIn('input', c.exception.args[0])
224
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400225 def test_check_output_timeout(self):
226 # check_output() function with timeout arg
227 with self.assertRaises(subprocess.TimeoutExpired) as c:
228 output = subprocess.check_output(
229 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200230 "import sys, time\n"
231 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400232 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200233 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400234 # Some heavily loaded buildbots (sparc Debian 3.x) require
235 # this much time to start and print.
236 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400237 self.fail("Expected TimeoutExpired.")
238 self.assertEqual(c.exception.output, b'BDFL')
239
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000240 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000241 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000242 newenv = os.environ.copy()
243 newenv["FRUIT"] = "banana"
244 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000245 'import sys, os;'
246 'sys.exit(os.getenv("FRUIT")=="banana")'],
247 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000248 self.assertEqual(rc, 1)
249
Victor Stinner87b9bc32011-06-01 00:57:47 +0200250 def test_invalid_args(self):
251 # Popen() called with invalid arguments should raise TypeError
252 # but Popen.__del__ should not complain (issue #12085)
253 with support.captured_stderr() as s:
254 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
255 argcount = subprocess.Popen.__init__.__code__.co_argcount
256 too_many_args = [0] * (argcount + 1)
257 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
258 self.assertEqual(s.getvalue(), '')
259
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000260 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000261 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000262 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000263 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000264 self.addCleanup(p.stdout.close)
265 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000266 p.wait()
267 self.assertEqual(p.stdin, None)
268
269 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200270 # .stdout is None when not redirected, and the child's stdout will
271 # be inherited from the parent. In order to test this we run a
272 # subprocess in a subprocess:
273 # this_test
274 # \-- subprocess created by this test (parent)
275 # \-- subprocess created by the parent subprocess (child)
276 # The parent doesn't specify stdout, so the child will use the
277 # parent's stdout. This test checks that the message printed by the
278 # child goes to the parent stdout. The parent also checks that the
279 # child's stdout is None. See #11963.
280 code = ('import sys; from subprocess import Popen, PIPE;'
281 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
282 ' stdin=PIPE, stderr=PIPE);'
283 'p.wait(); assert p.stdout is None;')
284 p = subprocess.Popen([sys.executable, "-c", code],
285 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
286 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000287 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200288 out, err = p.communicate()
289 self.assertEqual(p.returncode, 0, err)
290 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000291
292 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000293 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000294 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000295 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000296 self.addCleanup(p.stdout.close)
297 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000298 p.wait()
299 self.assertEqual(p.stderr, None)
300
Chris Jerdonek776cb192012-10-08 15:56:43 -0700301 def _assert_python(self, pre_args, **kwargs):
302 # We include sys.exit() to prevent the test runner from hanging
303 # whenever python is found.
304 args = pre_args + ["import sys; sys.exit(47)"]
305 p = subprocess.Popen(args, **kwargs)
306 p.wait()
307 self.assertEqual(47, p.returncode)
308
309 def test_executable(self):
310 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700311 #
312 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
313 # determine where its standard library is, so we need the directory
314 # of args[0] to be valid for the Popen() call to Python to succeed.
315 # See also issue #16170 and issue #7774.
316 doesnotexist = os.path.join(os.path.dirname(sys.executable),
317 "doesnotexist")
318 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700319
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300320 def test_bytes_executable(self):
321 doesnotexist = os.path.join(os.path.dirname(sys.executable),
322 "doesnotexist")
323 self._assert_python([doesnotexist, "-c"],
324 executable=os.fsencode(sys.executable))
325
326 def test_pathlike_executable(self):
327 doesnotexist = os.path.join(os.path.dirname(sys.executable),
328 "doesnotexist")
329 self._assert_python([doesnotexist, "-c"],
330 executable=FakePath(sys.executable))
331
Chris Jerdonek776cb192012-10-08 15:56:43 -0700332 def test_executable_takes_precedence(self):
333 # Check that the executable argument takes precedence over args[0].
334 #
335 # Verify first that the call succeeds without the executable arg.
336 pre_args = [sys.executable, "-c"]
337 self._assert_python(pre_args)
Victor Stinnerb31206a2018-01-25 19:06:05 +0100338 self.assertRaises(NONEXISTING_ERRORS,
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +0100339 self._assert_python, pre_args,
Victor Stinnerb31206a2018-01-25 19:06:05 +0100340 executable=NONEXISTING_CMD[0])
Chris Jerdonek776cb192012-10-08 15:56:43 -0700341
Victor Stinner937ee9e2018-06-26 02:11:06 +0200342 @unittest.skipIf(mswindows, "executable argument replaces shell")
Chris Jerdonek776cb192012-10-08 15:56:43 -0700343 def test_executable_replaces_shell(self):
344 # Check that the executable argument replaces the default shell
345 # when shell=True.
346 self._assert_python([], executable=sys.executable, shell=True)
347
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300348 @unittest.skipIf(mswindows, "executable argument replaces shell")
349 def test_bytes_executable_replaces_shell(self):
350 self._assert_python([], executable=os.fsencode(sys.executable),
351 shell=True)
352
353 @unittest.skipIf(mswindows, "executable argument replaces shell")
354 def test_pathlike_executable_replaces_shell(self):
355 self._assert_python([], executable=FakePath(sys.executable),
356 shell=True)
357
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700358 # For use in the test_cwd* tests below.
359 def _normalize_cwd(self, cwd):
360 # Normalize an expected cwd (for Tru64 support).
361 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
362 # strings. See bug #1063571.
Hai Shi0c4f0f32020-06-30 21:46:31 +0800363 with os_helper.change_cwd(cwd):
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300364 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700365
366 # For use in the test_cwd* tests below.
367 def _split_python_path(self):
368 # Return normalized (python_dir, python_base).
369 python_path = os.path.realpath(sys.executable)
370 return os.path.split(python_path)
371
372 # For use in the test_cwd* tests below.
373 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
374 # Invoke Python via Popen, and assert that (1) the call succeeds,
375 # and that (2) the current working directory of the child process
376 # matches *expected_cwd*.
377 p = subprocess.Popen([python_arg, "-c",
378 "import os, sys; "
Serhiy Storchakab1a87302020-07-26 10:21:39 +0300379 "buf = sys.stdout.buffer; "
380 "buf.write(os.getcwd().encode()); "
381 "buf.flush(); "
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700382 "sys.exit(47)"],
383 stdout=subprocess.PIPE,
384 **kwargs)
385 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000386 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700387 self.assertEqual(47, p.returncode)
388 normcase = os.path.normcase
389 self.assertEqual(normcase(expected_cwd),
Serhiy Storchakab1a87302020-07-26 10:21:39 +0300390 normcase(p.stdout.read().decode()))
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700391
392 def test_cwd(self):
393 # Check that cwd changes the cwd for the child process.
394 temp_dir = tempfile.gettempdir()
395 temp_dir = self._normalize_cwd(temp_dir)
396 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
397
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300398 def test_cwd_with_bytes(self):
399 temp_dir = tempfile.gettempdir()
400 temp_dir = self._normalize_cwd(temp_dir)
401 self._assert_cwd(temp_dir, sys.executable, cwd=os.fsencode(temp_dir))
402
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530403 def test_cwd_with_pathlike(self):
404 temp_dir = tempfile.gettempdir()
405 temp_dir = self._normalize_cwd(temp_dir)
Serhiy Storchakab21d1552018-03-02 11:53:51 +0200406 self._assert_cwd(temp_dir, sys.executable, cwd=FakePath(temp_dir))
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530407
Victor Stinner937ee9e2018-06-26 02:11:06 +0200408 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700409 def test_cwd_with_relative_arg(self):
410 # Check that Popen looks for args[0] relative to cwd if args[0]
411 # is relative.
412 python_dir, python_base = self._split_python_path()
413 rel_python = os.path.join(os.curdir, python_base)
Hai Shi0c4f0f32020-06-30 21:46:31 +0800414 with os_helper.temp_cwd() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700415 # Before calling with the correct cwd, confirm that the call fails
416 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700417 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700418 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700419 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700420 [rel_python], cwd=wrong_dir)
421 python_dir = self._normalize_cwd(python_dir)
422 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
423
Victor Stinner937ee9e2018-06-26 02:11:06 +0200424 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700425 def test_cwd_with_relative_executable(self):
426 # Check that Popen looks for executable relative to cwd if executable
427 # is relative (and that executable takes precedence over args[0]).
428 python_dir, python_base = self._split_python_path()
429 rel_python = os.path.join(os.curdir, python_base)
430 doesntexist = "somethingyoudonthave"
Hai Shi0c4f0f32020-06-30 21:46:31 +0800431 with os_helper.temp_cwd() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700432 # Before calling with the correct cwd, confirm that the call fails
433 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700434 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700435 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700436 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700437 [doesntexist], executable=rel_python,
438 cwd=wrong_dir)
439 python_dir = self._normalize_cwd(python_dir)
440 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
441 cwd=python_dir)
442
443 def test_cwd_with_absolute_arg(self):
444 # Check that Popen can find the executable when the cwd is wrong
445 # if args[0] is an absolute path.
446 python_dir, python_base = self._split_python_path()
447 abs_python = os.path.join(python_dir, python_base)
448 rel_python = os.path.join(os.curdir, python_base)
Hai Shi0c4f0f32020-06-30 21:46:31 +0800449 with os_helper.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700450 # Before calling with an absolute path, confirm that using a
451 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700452 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700453 [rel_python], cwd=wrong_dir)
454 wrong_dir = self._normalize_cwd(wrong_dir)
455 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
456
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100457 @unittest.skipIf(sys.base_prefix != sys.prefix,
458 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000459 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700460 python_dir, python_base = self._split_python_path()
461 python_dir = self._normalize_cwd(python_dir)
462 self._assert_cwd(python_dir, "somethingyoudonthave",
463 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000464
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100465 @unittest.skipIf(sys.base_prefix != sys.prefix,
466 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000467 @unittest.skipIf(sysconfig.is_python_build(),
468 "need an installed Python. See #7774")
469 def test_executable_without_cwd(self):
470 # For a normal installation, it should work without 'cwd'
471 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700472 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
473 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000474
475 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000476 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000477 p = subprocess.Popen([sys.executable, "-c",
478 'import sys; sys.exit(sys.stdin.read() == "pear")'],
479 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000480 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000481 p.stdin.close()
482 p.wait()
483 self.assertEqual(p.returncode, 1)
484
485 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000486 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000487 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000488 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000489 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000490 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000491 os.lseek(d, 0, 0)
492 p = subprocess.Popen([sys.executable, "-c",
493 'import sys; sys.exit(sys.stdin.read() == "pear")'],
494 stdin=d)
495 p.wait()
496 self.assertEqual(p.returncode, 1)
497
498 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000499 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000500 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000501 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000502 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000503 tf.seek(0)
504 p = subprocess.Popen([sys.executable, "-c",
505 'import sys; sys.exit(sys.stdin.read() == "pear")'],
506 stdin=tf)
507 p.wait()
508 self.assertEqual(p.returncode, 1)
509
510 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000511 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000512 p = subprocess.Popen([sys.executable, "-c",
513 'import sys; sys.stdout.write("orange")'],
514 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200515 with p:
516 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000517
518 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000519 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000520 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000521 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000522 d = tf.fileno()
523 p = subprocess.Popen([sys.executable, "-c",
524 'import sys; sys.stdout.write("orange")'],
525 stdout=d)
526 p.wait()
527 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000528 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000529
530 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000531 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000532 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000533 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000534 p = subprocess.Popen([sys.executable, "-c",
535 'import sys; sys.stdout.write("orange")'],
536 stdout=tf)
537 p.wait()
538 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000539 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000540
541 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000542 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000543 p = subprocess.Popen([sys.executable, "-c",
544 'import sys; sys.stderr.write("strawberry")'],
545 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200546 with p:
Victor Stinner6cac1132019-12-08 08:38:16 +0100547 self.assertEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000548
549 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000550 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000551 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000552 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000553 d = tf.fileno()
554 p = subprocess.Popen([sys.executable, "-c",
555 'import sys; sys.stderr.write("strawberry")'],
556 stderr=d)
557 p.wait()
558 os.lseek(d, 0, 0)
Victor Stinner6cac1132019-12-08 08:38:16 +0100559 self.assertEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000560
561 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000562 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000563 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000564 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000565 p = subprocess.Popen([sys.executable, "-c",
566 'import sys; sys.stderr.write("strawberry")'],
567 stderr=tf)
568 p.wait()
569 tf.seek(0)
Victor Stinner6cac1132019-12-08 08:38:16 +0100570 self.assertEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000571
Martin Panterc7635892016-05-13 01:54:44 +0000572 def test_stderr_redirect_with_no_stdout_redirect(self):
573 # test stderr=STDOUT while stdout=None (not set)
574
575 # - grandchild prints to stderr
576 # - child redirects grandchild's stderr to its stdout
577 # - the parent should get grandchild's stderr in child's stdout
578 p = subprocess.Popen([sys.executable, "-c",
579 'import sys, subprocess;'
580 'rc = subprocess.call([sys.executable, "-c",'
581 ' "import sys;"'
582 ' "sys.stderr.write(\'42\')"],'
583 ' stderr=subprocess.STDOUT);'
584 'sys.exit(rc)'],
585 stdout=subprocess.PIPE,
586 stderr=subprocess.PIPE)
587 stdout, stderr = p.communicate()
588 #NOTE: stdout should get stderr from grandchild
Victor Stinner6cac1132019-12-08 08:38:16 +0100589 self.assertEqual(stdout, b'42')
590 self.assertEqual(stderr, b'') # should be empty
Martin Panterc7635892016-05-13 01:54:44 +0000591 self.assertEqual(p.returncode, 0)
592
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000593 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000594 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000595 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000596 'import sys;'
597 'sys.stdout.write("apple");'
598 'sys.stdout.flush();'
599 'sys.stderr.write("orange")'],
600 stdout=subprocess.PIPE,
601 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200602 with p:
Victor Stinner6cac1132019-12-08 08:38:16 +0100603 self.assertEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000604
605 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000606 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000607 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000608 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000609 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000610 'import sys;'
611 'sys.stdout.write("apple");'
612 'sys.stdout.flush();'
613 'sys.stderr.write("orange")'],
614 stdout=tf,
615 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000616 p.wait()
617 tf.seek(0)
Victor Stinner6cac1132019-12-08 08:38:16 +0100618 self.assertEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000619
Thomas Wouters89f507f2006-12-13 04:49:30 +0000620 def test_stdout_filedes_of_stdout(self):
621 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200622 # To avoid printing the text on stdout, we do something similar to
623 # test_stdout_none (see above). The parent subprocess calls the child
624 # subprocess passing stdout=1, and this test uses stdout=PIPE in
625 # order to capture and check the output of the parent. See #11963.
626 code = ('import sys, subprocess; '
627 'rc = subprocess.call([sys.executable, "-c", '
628 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
629 'b\'test with stdout=1\'))"], stdout=1); '
630 'assert rc == 18')
631 p = subprocess.Popen([sys.executable, "-c", code],
632 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
633 self.addCleanup(p.stdout.close)
634 self.addCleanup(p.stderr.close)
635 out, err = p.communicate()
636 self.assertEqual(p.returncode, 0, err)
637 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000638
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200639 def test_stdout_devnull(self):
640 p = subprocess.Popen([sys.executable, "-c",
641 'for i in range(10240):'
642 'print("x" * 1024)'],
643 stdout=subprocess.DEVNULL)
644 p.wait()
645 self.assertEqual(p.stdout, None)
646
647 def test_stderr_devnull(self):
648 p = subprocess.Popen([sys.executable, "-c",
649 'import sys\n'
650 'for i in range(10240):'
651 'sys.stderr.write("x" * 1024)'],
652 stderr=subprocess.DEVNULL)
653 p.wait()
654 self.assertEqual(p.stderr, None)
655
656 def test_stdin_devnull(self):
657 p = subprocess.Popen([sys.executable, "-c",
658 'import sys;'
659 'sys.stdin.read(1)'],
660 stdin=subprocess.DEVNULL)
661 p.wait()
662 self.assertEqual(p.stdin, None)
663
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000664 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000665 newenv = os.environ.copy()
666 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200667 with subprocess.Popen([sys.executable, "-c",
668 'import sys,os;'
669 'sys.stdout.write(os.getenv("FRUIT"))'],
670 stdout=subprocess.PIPE,
671 env=newenv) as p:
672 stdout, stderr = p.communicate()
673 self.assertEqual(stdout, b"orange")
674
Victor Stinner62d51182011-06-23 01:02:25 +0200675 # Windows requires at least the SYSTEMROOT environment variable to start
676 # Python
677 @unittest.skipIf(sys.platform == 'win32',
678 'cannot test an empty env on Windows')
Gregory P. Smithb3512482017-05-30 14:40:37 -0700679 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
680 'The Python shared library cannot be loaded '
681 'with an empty environment.')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200682 def test_empty_env(self):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700683 """Verify that env={} is as empty as possible."""
684
Gregory P. Smith85aba232017-05-30 16:21:47 -0700685 def is_env_var_to_ignore(n):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700686 """Determine if an environment variable is under our control."""
687 # This excludes some __CF_* and VERSIONER_* keys MacOS insists
688 # on adding even when the environment in exec is empty.
689 # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist.
Gregory P. Smith85aba232017-05-30 16:21:47 -0700690 return ('VERSIONER' in n or '__CF' in n or # MacOS
Nick Coghlan6ea41862017-06-11 13:16:15 +1000691 n == 'LD_PRELOAD' or n.startswith('SANDBOX') or # Gentoo
692 n == 'LC_CTYPE') # Locale coercion triggered
Gregory P. Smithb3512482017-05-30 14:40:37 -0700693
Victor Stinnerf1512a22011-06-21 17:18:38 +0200694 with subprocess.Popen([sys.executable, "-c",
Gregory P. Smithb3512482017-05-30 14:40:37 -0700695 'import os; print(list(os.environ.keys()))'],
696 stdout=subprocess.PIPE, env={}) as p:
Victor Stinnerf1512a22011-06-21 17:18:38 +0200697 stdout, stderr = p.communicate()
Gregory P. Smithb3512482017-05-30 14:40:37 -0700698 child_env_names = eval(stdout.strip())
699 self.assertIsInstance(child_env_names, list)
700 child_env_names = [k for k in child_env_names
701 if not is_env_var_to_ignore(k)]
702 self.assertEqual(child_env_names, [])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000703
Serhiy Storchakad174d242017-06-23 19:39:27 +0300704 def test_invalid_cmd(self):
705 # null character in the command name
706 cmd = sys.executable + '\0'
707 with self.assertRaises(ValueError):
708 subprocess.Popen([cmd, "-c", "pass"])
709
710 # null character in the command argument
711 with self.assertRaises(ValueError):
712 subprocess.Popen([sys.executable, "-c", "pass#\0"])
713
714 def test_invalid_env(self):
Ville Skyttä49b27342017-08-03 09:00:59 +0300715 # null character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300716 newenv = os.environ.copy()
717 newenv["FRUIT\0VEGETABLE"] = "cabbage"
718 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700719 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300720
Ville Skyttä49b27342017-08-03 09:00:59 +0300721 # null character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300722 newenv = os.environ.copy()
723 newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
724 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700725 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300726
Ville Skyttä49b27342017-08-03 09:00:59 +0300727 # equal character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300728 newenv = os.environ.copy()
729 newenv["FRUIT=ORANGE"] = "lemon"
730 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700731 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300732
Ville Skyttä49b27342017-08-03 09:00:59 +0300733 # equal character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300734 newenv = os.environ.copy()
735 newenv["FRUIT"] = "orange=lemon"
736 with subprocess.Popen([sys.executable, "-c",
737 'import sys, os;'
738 'sys.stdout.write(os.getenv("FRUIT"))'],
739 stdout=subprocess.PIPE,
740 env=newenv) as p:
741 stdout, stderr = p.communicate()
742 self.assertEqual(stdout, b"orange=lemon")
743
Peter Astrandcbac93c2005-03-03 20:24:28 +0000744 def test_communicate_stdin(self):
745 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000746 'import sys;'
747 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000748 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000749 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000750 self.assertEqual(p.returncode, 1)
751
752 def test_communicate_stdout(self):
753 p = subprocess.Popen([sys.executable, "-c",
754 'import sys; sys.stdout.write("pineapple")'],
755 stdout=subprocess.PIPE)
756 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000757 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000758 self.assertEqual(stderr, None)
759
760 def test_communicate_stderr(self):
761 p = subprocess.Popen([sys.executable, "-c",
762 'import sys; sys.stderr.write("pineapple")'],
763 stderr=subprocess.PIPE)
764 (stdout, stderr) = p.communicate()
765 self.assertEqual(stdout, None)
Victor Stinner6cac1132019-12-08 08:38:16 +0100766 self.assertEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000767
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000768 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000769 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000770 'import sys,os;'
771 'sys.stderr.write("pineapple");'
772 'sys.stdout.write(sys.stdin.read())'],
773 stdin=subprocess.PIPE,
774 stdout=subprocess.PIPE,
775 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000776 self.addCleanup(p.stdout.close)
777 self.addCleanup(p.stderr.close)
778 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000779 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000780 self.assertEqual(stdout, b"banana")
Victor Stinner6cac1132019-12-08 08:38:16 +0100781 self.assertEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000782
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400783 def test_communicate_timeout(self):
784 p = subprocess.Popen([sys.executable, "-c",
785 'import sys,os,time;'
786 'sys.stderr.write("pineapple\\n");'
787 'time.sleep(1);'
788 'sys.stderr.write("pear\\n");'
789 'sys.stdout.write(sys.stdin.read())'],
790 universal_newlines=True,
791 stdin=subprocess.PIPE,
792 stdout=subprocess.PIPE,
793 stderr=subprocess.PIPE)
794 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
795 timeout=0.3)
796 # Make sure we can keep waiting for it, and that we get the whole output
797 # after it completes.
798 (stdout, stderr) = p.communicate()
799 self.assertEqual(stdout, "banana")
Victor Stinner6cac1132019-12-08 08:38:16 +0100800 self.assertEqual(stderr.encode(), b"pineapple\npear\n")
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400801
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700802 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200803 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400804 p = subprocess.Popen([sys.executable, "-c",
805 'import sys,os,time;'
806 'sys.stdout.write("a" * (64 * 1024));'
807 'time.sleep(0.2);'
808 'sys.stdout.write("a" * (64 * 1024));'
809 'time.sleep(0.2);'
810 'sys.stdout.write("a" * (64 * 1024));'
811 'time.sleep(0.2);'
812 'sys.stdout.write("a" * (64 * 1024));'],
813 stdout=subprocess.PIPE)
814 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
815 (stdout, _) = p.communicate()
816 self.assertEqual(len(stdout), 4 * 64 * 1024)
817
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000818 # Test for the fd leak reported in http://bugs.python.org/issue2791.
819 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000820 for stdin_pipe in (False, True):
821 for stdout_pipe in (False, True):
822 for stderr_pipe in (False, True):
823 options = {}
824 if stdin_pipe:
825 options['stdin'] = subprocess.PIPE
826 if stdout_pipe:
827 options['stdout'] = subprocess.PIPE
828 if stderr_pipe:
829 options['stderr'] = subprocess.PIPE
830 if not options:
831 continue
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700832 p = subprocess.Popen(ZERO_RETURN_CMD, **options)
Victor Stinner667d4b52010-12-25 22:40:32 +0000833 p.communicate()
834 if p.stdin is not None:
835 self.assertTrue(p.stdin.closed)
836 if p.stdout is not None:
837 self.assertTrue(p.stdout.closed)
838 if p.stderr is not None:
839 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000840
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000841 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000842 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000843 p = subprocess.Popen([sys.executable, "-c",
844 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000845 (stdout, stderr) = p.communicate()
846 self.assertEqual(stdout, None)
847 self.assertEqual(stderr, None)
848
849 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000850 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000851 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000852 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000853 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000854 os.close(x)
855 os.close(y)
856 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000857 'import sys,os;'
858 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200859 'sys.stderr.write("x" * %d);'
860 'sys.stdout.write(sys.stdin.read())' %
861 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000862 stdin=subprocess.PIPE,
863 stdout=subprocess.PIPE,
864 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000865 self.addCleanup(p.stdout.close)
866 self.addCleanup(p.stderr.close)
867 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200868 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000869 (stdout, stderr) = p.communicate(string_to_write)
870 self.assertEqual(stdout, string_to_write)
871
872 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000873 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000874 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000875 'import sys,os;'
876 'sys.stdout.write(sys.stdin.read())'],
877 stdin=subprocess.PIPE,
878 stdout=subprocess.PIPE,
879 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000880 self.addCleanup(p.stdout.close)
881 self.addCleanup(p.stderr.close)
882 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000883 p.stdin.write(b"banana")
884 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000885 self.assertEqual(stdout, b"bananasplit")
Victor Stinner6cac1132019-12-08 08:38:16 +0100886 self.assertEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000887
andyclegg7fed7bd2017-10-23 03:01:19 +0100888 def test_universal_newlines_and_text(self):
889 args = [
890 sys.executable, "-c",
891 'import sys,os;' + SETBINARY +
892 'buf = sys.stdout.buffer;'
893 'buf.write(sys.stdin.readline().encode());'
894 'buf.flush();'
895 'buf.write(b"line2\\n");'
896 'buf.flush();'
897 'buf.write(sys.stdin.read().encode());'
898 'buf.flush();'
899 'buf.write(b"line4\\n");'
900 'buf.flush();'
901 'buf.write(b"line5\\r\\n");'
902 'buf.flush();'
903 'buf.write(b"line6\\r");'
904 'buf.flush();'
905 'buf.write(b"\\nline7");'
906 'buf.flush();'
907 'buf.write(b"\\nline8");']
908
909 for extra_kwarg in ('universal_newlines', 'text'):
910 p = subprocess.Popen(args, **{'stdin': subprocess.PIPE,
911 'stdout': subprocess.PIPE,
912 extra_kwarg: True})
913 with p:
914 p.stdin.write("line1\n")
915 p.stdin.flush()
916 self.assertEqual(p.stdout.readline(), "line1\n")
917 p.stdin.write("line3\n")
918 p.stdin.close()
919 self.addCleanup(p.stdout.close)
920 self.assertEqual(p.stdout.readline(),
921 "line2\n")
922 self.assertEqual(p.stdout.read(6),
923 "line3\n")
924 self.assertEqual(p.stdout.read(),
925 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000926
927 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000928 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000929 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000930 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200931 'buf = sys.stdout.buffer;'
932 'buf.write(b"line2\\n");'
933 'buf.flush();'
934 'buf.write(b"line4\\n");'
935 'buf.flush();'
936 'buf.write(b"line5\\r\\n");'
937 'buf.flush();'
938 'buf.write(b"line6\\r");'
939 'buf.flush();'
940 'buf.write(b"\\nline7");'
941 'buf.flush();'
942 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200943 stderr=subprocess.PIPE,
944 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000945 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000946 self.addCleanup(p.stdout.close)
947 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000948 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200949 self.assertEqual(stdout,
950 "line2\nline4\nline5\nline6\nline7\nline8")
951
952 def test_universal_newlines_communicate_stdin(self):
953 # universal newlines through communicate(), with only stdin
954 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300955 'import sys,os;' + SETBINARY + textwrap.dedent('''
956 s = sys.stdin.readline()
957 assert s == "line1\\n", repr(s)
958 s = sys.stdin.read()
959 assert s == "line3\\n", repr(s)
960 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200961 stdin=subprocess.PIPE,
962 universal_newlines=1)
963 (stdout, stderr) = p.communicate("line1\nline3\n")
964 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000965
Andrew Svetlovf3765072012-08-14 18:35:17 +0300966 def test_universal_newlines_communicate_input_none(self):
967 # Test communicate(input=None) with universal newlines.
968 #
969 # We set stdout to PIPE because, as of this writing, a different
970 # code path is tested when the number of pipes is zero or one.
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700971 p = subprocess.Popen(ZERO_RETURN_CMD,
Andrew Svetlovf3765072012-08-14 18:35:17 +0300972 stdin=subprocess.PIPE,
973 stdout=subprocess.PIPE,
974 universal_newlines=True)
975 p.communicate()
976 self.assertEqual(p.returncode, 0)
977
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300978 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300979 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300980 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300981 'import sys,os;' + SETBINARY + textwrap.dedent('''
982 s = sys.stdin.buffer.readline()
983 sys.stdout.buffer.write(s)
984 sys.stdout.buffer.write(b"line2\\r")
985 sys.stderr.buffer.write(b"eline2\\n")
986 s = sys.stdin.buffer.read()
987 sys.stdout.buffer.write(s)
988 sys.stdout.buffer.write(b"line4\\n")
989 sys.stdout.buffer.write(b"line5\\r\\n")
990 sys.stderr.buffer.write(b"eline6\\r")
991 sys.stderr.buffer.write(b"eline7\\r\\nz")
992 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300993 stdin=subprocess.PIPE,
994 stderr=subprocess.PIPE,
995 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300996 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300997 self.addCleanup(p.stdout.close)
998 self.addCleanup(p.stderr.close)
999 (stdout, stderr) = p.communicate("line1\nline3\n")
1000 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +03001001 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001002 # Python debug build push something like "[42442 refs]\n"
1003 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +03001004 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001005
Andrew Svetlov82860712012-08-19 22:13:41 +03001006 def test_universal_newlines_communicate_encodings(self):
1007 # Check that universal newlines mode works for various encodings,
1008 # in particular for encodings in the UTF-16 and UTF-32 families.
1009 # See issue #15595.
1010 #
1011 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
1012 # without, and UTF-16 and UTF-32.
1013 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +03001014 code = ("import sys; "
1015 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
1016 encoding)
1017 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -07001018 # We set stdin to be non-None because, as of this writing,
1019 # a different code path is used when the number of pipes is
1020 # zero or one.
1021 popen = subprocess.Popen(args,
1022 stdin=subprocess.PIPE,
1023 stdout=subprocess.PIPE,
1024 encoding=encoding)
1025 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +03001026 self.assertEqual(stdout, '1\n2\n3\n4')
1027
Steve Dower050acae2016-09-06 20:16:17 -07001028 def test_communicate_errors(self):
1029 for errors, expected in [
1030 ('ignore', ''),
1031 ('replace', '\ufffd\ufffd'),
1032 ('surrogateescape', '\udc80\udc80'),
1033 ('backslashreplace', '\\x80\\x80'),
1034 ]:
1035 code = ("import sys; "
1036 r"sys.stdout.buffer.write(b'[\x80\x80]')")
1037 args = [sys.executable, '-c', code]
1038 # We set stdin to be non-None because, as of this writing,
1039 # a different code path is used when the number of pipes is
1040 # zero or one.
1041 popen = subprocess.Popen(args,
1042 stdin=subprocess.PIPE,
1043 stdout=subprocess.PIPE,
1044 encoding='utf-8',
1045 errors=errors)
1046 stdout, stderr = popen.communicate(input='')
1047 self.assertEqual(stdout, '[{}]'.format(expected))
1048
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001049 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +00001050 # Make sure we leak no resources
Victor Stinner937ee9e2018-06-26 02:11:06 +02001051 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +00001052 max_handles = 1026 # too much for most UNIX systems
1053 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +00001054 max_handles = 2050 # too much for (at least some) Windows setups
1055 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001056 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +00001057 try:
1058 for i in range(max_handles):
1059 try:
Hai Shi0c4f0f32020-06-30 21:46:31 +08001060 tmpfile = os.path.join(tmpdir, os_helper.TESTFN)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001061 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +00001062 except OSError as e:
1063 if e.errno != errno.EMFILE:
1064 raise
1065 break
1066 else:
1067 self.skipTest("failed to reach the file descriptor limit "
1068 "(tried %d)" % max_handles)
1069 # Close a couple of them (should be enough for a subprocess)
1070 for i in range(10):
1071 os.close(handles.pop())
1072 # Loop creating some subprocesses. If one of them leaks some fds,
1073 # the next loop iteration will fail by reaching the max fd limit.
1074 for i in range(15):
1075 p = subprocess.Popen([sys.executable, "-c",
1076 "import sys;"
1077 "sys.stdout.write(sys.stdin.read())"],
1078 stdin=subprocess.PIPE,
1079 stdout=subprocess.PIPE,
1080 stderr=subprocess.PIPE)
1081 data = p.communicate(b"lime")[0]
1082 self.assertEqual(data, b"lime")
1083 finally:
1084 for h in handles:
1085 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001086 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001087
1088 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001089 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
1090 '"a b c" d e')
1091 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
1092 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +00001093 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
1094 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001095 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
1096 'a\\\\\\b "de fg" h')
1097 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
1098 'a\\\\\\"b c d')
1099 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
1100 '"a\\\\b c" d e')
1101 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
1102 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001103 self.assertEqual(subprocess.list2cmdline(['ab', '']),
1104 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001105
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001106 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001107 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +02001108 "import os; os.read(0, 1)"],
1109 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001110 self.addCleanup(p.stdin.close)
1111 self.assertIsNone(p.poll())
1112 os.write(p.stdin.fileno(), b'A')
1113 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001114 # Subsequent invocations should just return the returncode
1115 self.assertEqual(p.poll(), 0)
1116
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001117 def test_wait(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001118 p = subprocess.Popen(ZERO_RETURN_CMD)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001119 self.assertEqual(p.wait(), 0)
1120 # Subsequent invocations should just return the returncode
1121 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001122
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001123 def test_wait_timeout(self):
1124 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001125 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001126 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001127 p.wait(timeout=0.0001)
1128 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Victor Stinner0d63bac2019-12-11 11:30:03 +01001129 self.assertEqual(p.wait(timeout=support.SHORT_TIMEOUT), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001130
Peter Astrand738131d2004-11-30 21:04:45 +00001131 def test_invalid_bufsize(self):
1132 # an invalid type of the bufsize argument should raise
1133 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001134 with self.assertRaises(TypeError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001135 subprocess.Popen(ZERO_RETURN_CMD, "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001136
Guido van Rossum46a05a72007-06-07 21:56:45 +00001137 def test_bufsize_is_none(self):
1138 # bufsize=None should be the same as bufsize=0.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001139 p = subprocess.Popen(ZERO_RETURN_CMD, None)
Guido van Rossum46a05a72007-06-07 21:56:45 +00001140 self.assertEqual(p.wait(), 0)
1141 # Again with keyword arg
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001142 p = subprocess.Popen(ZERO_RETURN_CMD, bufsize=None)
Guido van Rossum46a05a72007-06-07 21:56:45 +00001143 self.assertEqual(p.wait(), 0)
1144
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001145 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1146 # subprocess may deadlock with bufsize=1, see issue #21332
1147 with subprocess.Popen([sys.executable, "-c", "import sys;"
1148 "sys.stdout.write(sys.stdin.readline());"
1149 "sys.stdout.flush()"],
1150 stdin=subprocess.PIPE,
1151 stdout=subprocess.PIPE,
1152 stderr=subprocess.DEVNULL,
1153 bufsize=1,
1154 universal_newlines=universal_newlines) as p:
1155 p.stdin.write(line) # expect that it flushes the line in text mode
1156 os.close(p.stdin.fileno()) # close it without flushing the buffer
1157 read_line = p.stdout.readline()
Segev Finer4d385172017-08-18 16:18:13 +03001158 with support.SuppressCrashReport():
1159 try:
1160 p.stdin.close()
1161 except OSError:
1162 pass
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001163 p.stdin = None
1164 self.assertEqual(p.returncode, 0)
1165 self.assertEqual(read_line, expected)
1166
1167 def test_bufsize_equal_one_text_mode(self):
1168 # line is flushed in text mode with bufsize=1.
1169 # we should get the full line in return
1170 line = "line\n"
1171 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1172
1173 def test_bufsize_equal_one_binary_mode(self):
1174 # line is not flushed in binary mode with bufsize=1.
1175 # we should get empty response
1176 line = b'line' + os.linesep.encode() # assume ascii-based locale
Alexey Izbysheva2670562018-10-20 03:22:31 +03001177 with self.assertWarnsRegex(RuntimeWarning, 'line buffering'):
1178 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001179
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001180 def test_leaking_fds_on_error(self):
1181 # see bug #5179: Popen leaks file descriptors to PIPEs if
1182 # the child fails to execute; this will eventually exhaust
1183 # the maximum number of open fds. 1024 seems a very common
1184 # value for that limit, but Windows has 2048, so we loop
1185 # 1024 times (each call leaked two fds).
1186 for i in range(1024):
Victor Stinnerb31206a2018-01-25 19:06:05 +01001187 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02001188 subprocess.Popen(NONEXISTING_CMD,
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001189 stdout=subprocess.PIPE,
1190 stderr=subprocess.PIPE)
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001191
Victor Stinner9a83f652017-08-21 23:51:31 +02001192 def test_nonexisting_with_pipes(self):
1193 # bpo-30121: Popen with pipes must close properly pipes on error.
1194 # Previously, os.close() was called with a Windows handle which is not
1195 # a valid file descriptor.
1196 #
1197 # Run the test in a subprocess to control how the CRT reports errors
1198 # and to get stderr content.
1199 try:
1200 import msvcrt
1201 msvcrt.CrtSetReportMode
1202 except (AttributeError, ImportError):
1203 self.skipTest("need msvcrt.CrtSetReportMode")
1204
1205 code = textwrap.dedent(f"""
1206 import msvcrt
1207 import subprocess
1208
1209 cmd = {NONEXISTING_CMD!r}
1210
1211 for report_type in [msvcrt.CRT_WARN,
1212 msvcrt.CRT_ERROR,
1213 msvcrt.CRT_ASSERT]:
1214 msvcrt.CrtSetReportMode(report_type, msvcrt.CRTDBG_MODE_FILE)
1215 msvcrt.CrtSetReportFile(report_type, msvcrt.CRTDBG_FILE_STDERR)
1216
1217 try:
Zachary Ware55376462018-02-19 14:02:38 -06001218 subprocess.Popen(cmd,
Victor Stinner9a83f652017-08-21 23:51:31 +02001219 stdout=subprocess.PIPE,
1220 stderr=subprocess.PIPE)
1221 except OSError:
1222 pass
1223 """)
1224 cmd = [sys.executable, "-c", code]
1225 proc = subprocess.Popen(cmd,
1226 stderr=subprocess.PIPE,
1227 universal_newlines=True)
1228 with proc:
1229 stderr = proc.communicate()[1]
1230 self.assertEqual(stderr, "")
1231 self.assertEqual(proc.returncode, 0)
1232
Antoine Pitroua8392712013-08-30 23:38:13 +02001233 def test_double_close_on_error(self):
1234 # Issue #18851
1235 fds = []
1236 def open_fds():
1237 for i in range(20):
1238 fds.extend(os.pipe())
1239 time.sleep(0.001)
1240 t = threading.Thread(target=open_fds)
1241 t.start()
1242 try:
1243 with self.assertRaises(EnvironmentError):
Victor Stinner9a83f652017-08-21 23:51:31 +02001244 subprocess.Popen(NONEXISTING_CMD,
Antoine Pitroua8392712013-08-30 23:38:13 +02001245 stdin=subprocess.PIPE,
1246 stdout=subprocess.PIPE,
1247 stderr=subprocess.PIPE)
1248 finally:
1249 t.join()
1250 exc = None
1251 for fd in fds:
1252 # If a double close occurred, some of those fds will
1253 # already have been closed by mistake, and os.close()
1254 # here will raise.
1255 try:
1256 os.close(fd)
1257 except OSError as e:
1258 exc = e
1259 if exc is not None:
1260 raise exc
1261
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001262 def test_threadsafe_wait(self):
1263 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1264 proc = subprocess.Popen([sys.executable, '-c',
1265 'import time; time.sleep(12)'])
1266 self.assertEqual(proc.returncode, None)
1267 results = []
1268
1269 def kill_proc_timer_thread():
1270 results.append(('thread-start-poll-result', proc.poll()))
1271 # terminate it from the thread and wait for the result.
1272 proc.kill()
1273 proc.wait()
1274 results.append(('thread-after-kill-and-wait', proc.returncode))
1275 # this wait should be a no-op given the above.
1276 proc.wait()
1277 results.append(('thread-after-second-wait', proc.returncode))
1278
1279 # This is a timing sensitive test, the failure mode is
1280 # triggered when both the main thread and this thread are in
1281 # the wait() call at once. The delay here is to allow the
1282 # main thread to most likely be blocked in its wait() call.
1283 t = threading.Timer(0.2, kill_proc_timer_thread)
1284 t.start()
1285
Victor Stinner937ee9e2018-06-26 02:11:06 +02001286 if mswindows:
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001287 expected_errorcode = 1
1288 else:
1289 # Should be -9 because of the proc.kill() from the thread.
1290 expected_errorcode = -9
1291
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001292 # Wait for the process to finish; the thread should kill it
1293 # long before it finishes on its own. Supplying a timeout
1294 # triggers a different code path for better coverage.
Victor Stinner0d63bac2019-12-11 11:30:03 +01001295 proc.wait(timeout=support.SHORT_TIMEOUT)
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 wait from main thread")
1298
1299 # This should be a no-op with no change in returncode.
1300 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001301 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001302 msg="unexpected result in second main wait.")
1303
1304 t.join()
1305 # Ensure that all of the thread results are as expected.
1306 # When a race condition occurs in wait(), the returncode could
1307 # be set by the wrong thread that doesn't actually have it
1308 # leading to an incorrect value.
1309 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001310 ('thread-after-kill-and-wait', expected_errorcode),
1311 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001312 results)
1313
Victor Stinnerb3693582010-05-21 20:13:12 +00001314 def test_issue8780(self):
1315 # Ensure that stdout is inherited from the parent
1316 # if stdout=PIPE is not used
1317 code = ';'.join((
1318 'import subprocess, sys',
1319 'retcode = subprocess.call('
1320 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1321 'assert retcode == 0'))
1322 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001323 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001324
Tim Goldenaf5ac392010-08-06 13:03:56 +00001325 def test_handles_closed_on_exception(self):
1326 # If CreateProcess exits with an error, ensure the
1327 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001328 ifhandle, ifname = tempfile.mkstemp()
1329 ofhandle, ofname = tempfile.mkstemp()
1330 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001331 try:
1332 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1333 stderr=efhandle)
1334 except OSError:
1335 os.close(ifhandle)
1336 os.remove(ifname)
1337 os.close(ofhandle)
1338 os.remove(ofname)
1339 os.close(efhandle)
1340 os.remove(efname)
1341 self.assertFalse(os.path.exists(ifname))
1342 self.assertFalse(os.path.exists(ofname))
1343 self.assertFalse(os.path.exists(efname))
1344
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001345 def test_communicate_epipe(self):
1346 # Issue 10963: communicate() should hide EPIPE
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001347 p = subprocess.Popen(ZERO_RETURN_CMD,
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001348 stdin=subprocess.PIPE,
1349 stdout=subprocess.PIPE,
1350 stderr=subprocess.PIPE)
1351 self.addCleanup(p.stdout.close)
1352 self.addCleanup(p.stderr.close)
1353 self.addCleanup(p.stdin.close)
1354 p.communicate(b"x" * 2**20)
1355
Andrey Doroschenko645005e2019-11-17 17:08:31 +03001356 def test_repr(self):
1357 # Run a command that waits for user input, to check the repr() of
1358 # a Proc object while and after the sub-process runs.
1359 code = 'import sys; input(); sys.exit(57)'
1360 cmd = [sys.executable, '-c', code]
1361 result = "<Popen: returncode: {}"
1362
1363 with subprocess.Popen(
1364 cmd, stdin=subprocess.PIPE, universal_newlines=True) as proc:
1365 self.assertIsNone(proc.returncode)
1366 self.assertTrue(
1367 repr(proc).startswith(result.format(proc.returncode)) and
1368 repr(proc).endswith('>')
1369 )
1370
1371 proc.communicate(input='exit...\n')
1372 proc.wait()
1373
1374 self.assertIsNotNone(proc.returncode)
1375 self.assertTrue(
1376 repr(proc).startswith(result.format(proc.returncode)) and
1377 repr(proc).endswith('>')
1378 )
1379
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001380 def test_communicate_epipe_only_stdin(self):
1381 # Issue 10963: communicate() should hide EPIPE
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001382 p = subprocess.Popen(ZERO_RETURN_CMD,
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001383 stdin=subprocess.PIPE)
1384 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001385 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001386 p.communicate(b"x" * 2**20)
1387
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001388 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1389 "Requires signal.SIGUSR1")
1390 @unittest.skipUnless(hasattr(os, 'kill'),
1391 "Requires os.kill")
1392 @unittest.skipUnless(hasattr(os, 'getppid'),
1393 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001394 def test_communicate_eintr(self):
1395 # Issue #12493: communicate() should handle EINTR
1396 def handler(signum, frame):
1397 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001398 old_handler = signal.signal(signal.SIGUSR1, handler)
1399 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001400
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001401 args = [sys.executable, "-c",
1402 'import os, signal;'
1403 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001404 for stream in ('stdout', 'stderr'):
1405 kw = {stream: subprocess.PIPE}
1406 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001407 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001408 process.communicate()
1409
Tim Peterse718f612004-10-12 21:51:32 +00001410
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001411 # This test is Linux-ish specific for simplicity to at least have
1412 # some coverage. It is not a platform specific bug.
1413 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1414 "Linux specific")
1415 def test_failed_child_execute_fd_leak(self):
1416 """Test for the fork() failure fd leak reported in issue16327."""
1417 fd_directory = '/proc/%d/fd' % os.getpid()
1418 fds_before_popen = os.listdir(fd_directory)
1419 with self.assertRaises(PopenTestException):
1420 PopenExecuteChildRaises(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001421 ZERO_RETURN_CMD, stdin=subprocess.PIPE,
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001422 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1423
1424 # NOTE: This test doesn't verify that the real _execute_child
1425 # does not close the file descriptors itself on the way out
1426 # during an exception. Code inspection has confirmed that.
1427
1428 fds_after_exception = os.listdir(fd_directory)
1429 self.assertEqual(fds_before_popen, fds_after_exception)
1430
Victor Stinner937ee9e2018-06-26 02:11:06 +02001431 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001432 def test_file_not_found_includes_filename(self):
1433 with self.assertRaises(FileNotFoundError) as c:
1434 subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args'])
1435 self.assertEqual(c.exception.filename, '/opt/nonexistent_binary')
1436
Victor Stinner937ee9e2018-06-26 02:11:06 +02001437 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001438 def test_file_not_found_with_bad_cwd(self):
1439 with self.assertRaises(FileNotFoundError) as c:
1440 subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory')
1441 self.assertEqual(c.exception.filename, '/some/nonexistent/directory')
1442
Batuhan Taşkaya4dc5a9d2019-12-30 19:02:04 +03001443 def test_class_getitems(self):
Guido van Rossum48b069a2020-04-07 09:50:06 -07001444 self.assertIsInstance(subprocess.Popen[bytes], types.GenericAlias)
1445 self.assertIsInstance(subprocess.CompletedProcess[str], types.GenericAlias)
Gregory P. Smith6e730002015-04-14 16:14:25 -07001446
1447class RunFuncTestCase(BaseTestCase):
1448 def run_python(self, code, **kwargs):
1449 """Run Python code in a subprocess using subprocess.run"""
1450 argv = [sys.executable, "-c", code]
1451 return subprocess.run(argv, **kwargs)
1452
1453 def test_returncode(self):
1454 # call() function with sequence argument
1455 cp = self.run_python("import sys; sys.exit(47)")
1456 self.assertEqual(cp.returncode, 47)
1457 with self.assertRaises(subprocess.CalledProcessError):
1458 cp.check_returncode()
1459
1460 def test_check(self):
1461 with self.assertRaises(subprocess.CalledProcessError) as c:
1462 self.run_python("import sys; sys.exit(47)", check=True)
1463 self.assertEqual(c.exception.returncode, 47)
1464
1465 def test_check_zero(self):
1466 # check_returncode shouldn't raise when returncode is zero
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001467 cp = subprocess.run(ZERO_RETURN_CMD, check=True)
Gregory P. Smith6e730002015-04-14 16:14:25 -07001468 self.assertEqual(cp.returncode, 0)
1469
1470 def test_timeout(self):
1471 # run() function with timeout argument; we want to test that the child
1472 # process gets killed when the timeout expires. If the child isn't
1473 # killed, this call will deadlock since subprocess.run waits for the
1474 # child.
1475 with self.assertRaises(subprocess.TimeoutExpired):
1476 self.run_python("while True: pass", timeout=0.0001)
1477
1478 def test_capture_stdout(self):
1479 # capture stdout with zero return code
1480 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1481 self.assertIn(b'BDFL', cp.stdout)
1482
1483 def test_capture_stderr(self):
1484 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1485 stderr=subprocess.PIPE)
1486 self.assertIn(b'BDFL', cp.stderr)
1487
1488 def test_check_output_stdin_arg(self):
1489 # run() can be called with stdin set to a file
1490 tf = tempfile.TemporaryFile()
1491 self.addCleanup(tf.close)
1492 tf.write(b'pear')
1493 tf.seek(0)
1494 cp = self.run_python(
1495 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1496 stdin=tf, stdout=subprocess.PIPE)
1497 self.assertIn(b'PEAR', cp.stdout)
1498
1499 def test_check_output_input_arg(self):
1500 # check_output() can be called with input set to a string
1501 cp = self.run_python(
1502 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1503 input=b'pear', stdout=subprocess.PIPE)
1504 self.assertIn(b'PEAR', cp.stdout)
1505
1506 def test_check_output_stdin_with_input_arg(self):
1507 # run() refuses to accept 'stdin' with 'input'
1508 tf = tempfile.TemporaryFile()
1509 self.addCleanup(tf.close)
1510 tf.write(b'pear')
1511 tf.seek(0)
1512 with self.assertRaises(ValueError,
1513 msg="Expected ValueError when stdin and input args supplied.") as c:
1514 output = self.run_python("print('will not be run')",
1515 stdin=tf, input=b'hare')
1516 self.assertIn('stdin', c.exception.args[0])
1517 self.assertIn('input', c.exception.args[0])
1518
1519 def test_check_output_timeout(self):
1520 with self.assertRaises(subprocess.TimeoutExpired) as c:
1521 cp = self.run_python((
1522 "import sys, time\n"
1523 "sys.stdout.write('BDFL')\n"
1524 "sys.stdout.flush()\n"
1525 "time.sleep(3600)"),
1526 # Some heavily loaded buildbots (sparc Debian 3.x) require
1527 # this much time to start and print.
1528 timeout=3, stdout=subprocess.PIPE)
1529 self.assertEqual(c.exception.output, b'BDFL')
1530 # output is aliased to stdout
1531 self.assertEqual(c.exception.stdout, b'BDFL')
1532
1533 def test_run_kwargs(self):
1534 newenv = os.environ.copy()
1535 newenv["FRUIT"] = "banana"
1536 cp = self.run_python(('import sys, os;'
1537 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1538 env=newenv)
1539 self.assertEqual(cp.returncode, 33)
1540
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001541 def test_run_with_pathlike_path(self):
1542 # bpo-31961: test run(pathlike_object)
1543 # the name of a command that can be run without
Min ho Kimc4cacc82019-07-31 08:16:13 +10001544 # any arguments that exit fast
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001545 prog = 'tree.com' if mswindows else 'ls'
1546 path = shutil.which(prog)
1547 if path is None:
1548 self.skipTest(f'{prog} required for this test')
1549 path = FakePath(path)
1550 res = subprocess.run(path, stdout=subprocess.DEVNULL)
1551 self.assertEqual(res.returncode, 0)
1552 with self.assertRaises(TypeError):
1553 subprocess.run(path, stdout=subprocess.DEVNULL, shell=True)
1554
1555 def test_run_with_bytes_path_and_arguments(self):
1556 # bpo-31961: test run([bytes_object, b'additional arguments'])
1557 path = os.fsencode(sys.executable)
1558 args = [path, '-c', b'import sys; sys.exit(57)']
1559 res = subprocess.run(args)
1560 self.assertEqual(res.returncode, 57)
1561
1562 def test_run_with_pathlike_path_and_arguments(self):
1563 # bpo-31961: test run([pathlike_object, 'additional arguments'])
1564 path = FakePath(sys.executable)
1565 args = [path, '-c', 'import sys; sys.exit(57)']
1566 res = subprocess.run(args)
1567 self.assertEqual(res.returncode, 57)
1568
Bo Baylesce0f33d2018-01-30 00:40:39 -06001569 def test_capture_output(self):
1570 cp = self.run_python(("import sys;"
1571 "sys.stdout.write('BDFL'); "
1572 "sys.stderr.write('FLUFL')"),
1573 capture_output=True)
1574 self.assertIn(b'BDFL', cp.stdout)
1575 self.assertIn(b'FLUFL', cp.stderr)
1576
1577 def test_stdout_with_capture_output_arg(self):
1578 # run() refuses to accept 'stdout' with 'capture_output'
1579 tf = tempfile.TemporaryFile()
1580 self.addCleanup(tf.close)
1581 with self.assertRaises(ValueError,
1582 msg=("Expected ValueError when stdout and capture_output "
1583 "args supplied.")) as c:
1584 output = self.run_python("print('will not be run')",
1585 capture_output=True, stdout=tf)
1586 self.assertIn('stdout', c.exception.args[0])
1587 self.assertIn('capture_output', c.exception.args[0])
1588
1589 def test_stderr_with_capture_output_arg(self):
1590 # run() refuses to accept 'stderr' with 'capture_output'
1591 tf = tempfile.TemporaryFile()
1592 self.addCleanup(tf.close)
1593 with self.assertRaises(ValueError,
1594 msg=("Expected ValueError when stderr and capture_output "
1595 "args supplied.")) as c:
1596 output = self.run_python("print('will not be run')",
1597 capture_output=True, stderr=tf)
1598 self.assertIn('stderr', c.exception.args[0])
1599 self.assertIn('capture_output', c.exception.args[0])
1600
Gregory P. Smith580d2782019-09-11 04:23:05 -05001601 # This test _might_ wind up a bit fragile on loaded build+test machines
1602 # as it depends on the timing with wide enough margins for normal situations
1603 # but does assert that it happened "soon enough" to believe the right thing
1604 # happened.
1605 @unittest.skipIf(mswindows, "requires posix like 'sleep' shell command")
1606 def test_run_with_shell_timeout_and_capture_output(self):
1607 """Output capturing after a timeout mustn't hang forever on open filehandles."""
1608 before_secs = time.monotonic()
1609 try:
1610 subprocess.run('sleep 3', shell=True, timeout=0.1,
1611 capture_output=True) # New session unspecified.
1612 except subprocess.TimeoutExpired as exc:
1613 after_secs = time.monotonic()
1614 stacks = traceback.format_exc() # assertRaises doesn't give this.
1615 else:
1616 self.fail("TimeoutExpired not raised.")
1617 self.assertLess(after_secs - before_secs, 1.5,
1618 msg="TimeoutExpired was delayed! Bad traceback:\n```\n"
1619 f"{stacks}```")
1620
Gregory P. Smith6e730002015-04-14 16:14:25 -07001621
Gregory P. Smith693aa802019-09-13 14:43:35 +01001622def _get_test_grp_name():
Victor Stinnerfaca8552019-09-25 15:52:49 +02001623 for name_group in ('staff', 'nogroup', 'grp', 'nobody', 'nfsnobody'):
Gregory P. Smith693aa802019-09-13 14:43:35 +01001624 if grp:
1625 try:
1626 grp.getgrnam(name_group)
1627 except KeyError:
1628 continue
1629 return name_group
1630 else:
1631 raise unittest.SkipTest('No identified group name to use for this test on this platform.')
1632
1633
Victor Stinner937ee9e2018-06-26 02:11:06 +02001634@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001635class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001636
Gregory P. Smith5591b022012-10-10 03:34:47 -07001637 def setUp(self):
1638 super().setUp()
1639 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1640
1641 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001642 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001643 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001644 except OSError as e:
1645 # This avoids hard coding the errno value or the OS perror()
1646 # string and instead capture the exception that we want to see
1647 # below for comparison.
1648 desired_exception = e
1649 else:
Martin Pantereb995702016-07-28 01:11:04 +00001650 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001651 self._nonexistent_dir)
1652 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001653
Gregory P. Smith5591b022012-10-10 03:34:47 -07001654 def test_exception_cwd(self):
1655 """Test error in the child raised in the parent for a bad cwd."""
1656 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001657 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001658 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001659 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001660 except OSError as e:
1661 # Test that the child process chdir failure actually makes
1662 # it up to the parent process as the correct exception.
1663 self.assertEqual(desired_exception.errno, e.errno)
1664 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001665 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001666 else:
1667 self.fail("Expected OSError: %s" % desired_exception)
1668
Gregory P. Smith5591b022012-10-10 03:34:47 -07001669 def test_exception_bad_executable(self):
1670 """Test error in the child raised in the parent for a bad executable."""
1671 desired_exception = self._get_chdir_exception()
1672 try:
1673 p = subprocess.Popen([sys.executable, "-c", ""],
1674 executable=self._nonexistent_dir)
1675 except OSError as e:
1676 # Test that the child process exec failure actually makes
1677 # it up to the parent process as the correct exception.
1678 self.assertEqual(desired_exception.errno, e.errno)
1679 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001680 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001681 else:
1682 self.fail("Expected OSError: %s" % desired_exception)
1683
1684 def test_exception_bad_args_0(self):
1685 """Test error in the child raised in the parent for a bad args[0]."""
1686 desired_exception = self._get_chdir_exception()
1687 try:
1688 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1689 except OSError as e:
1690 # Test that the child process exec failure actually makes
1691 # it up to the parent process as the correct exception.
1692 self.assertEqual(desired_exception.errno, e.errno)
1693 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001694 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001695 else:
1696 self.fail("Expected OSError: %s" % desired_exception)
1697
Ammar Askar3fc499b2017-09-06 02:41:30 -04001698 # We mock the __del__ method for Popen in the next two tests
1699 # because it does cleanup based on the pid returned by fork_exec
1700 # along with issuing a resource warning if it still exists. Since
1701 # we don't actually spawn a process in these tests we can forego
1702 # the destructor. An alternative would be to set _child_created to
1703 # False before the destructor is called but there is no easy way
1704 # to do that
1705 class PopenNoDestructor(subprocess.Popen):
1706 def __del__(self):
1707 pass
1708
1709 @mock.patch("subprocess._posixsubprocess.fork_exec")
1710 def test_exception_errpipe_normal(self, fork_exec):
1711 """Test error passing done through errpipe_write in the good case"""
1712 def proper_error(*args):
1713 errpipe_write = args[13]
1714 # Write the hex for the error code EISDIR: 'is a directory'
1715 err_code = '{:x}'.format(errno.EISDIR).encode()
1716 os.write(errpipe_write, b"OSError:" + err_code + b":")
1717 return 0
1718
1719 fork_exec.side_effect = proper_error
1720
Victor Stinner11045c92017-10-05 06:32:53 -07001721 with mock.patch("subprocess.os.waitpid",
1722 side_effect=ChildProcessError):
1723 with self.assertRaises(IsADirectoryError):
1724 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001725
1726 @mock.patch("subprocess._posixsubprocess.fork_exec")
1727 def test_exception_errpipe_bad_data(self, fork_exec):
1728 """Test error passing done through errpipe_write where its not
1729 in the expected format"""
1730 error_data = b"\xFF\x00\xDE\xAD"
1731 def bad_error(*args):
1732 errpipe_write = args[13]
1733 # Anything can be in the pipe, no assumptions should
1734 # be made about its encoding, so we'll write some
1735 # arbitrary hex bytes to test it out
1736 os.write(errpipe_write, error_data)
1737 return 0
1738
1739 fork_exec.side_effect = bad_error
1740
Victor Stinner11045c92017-10-05 06:32:53 -07001741 with mock.patch("subprocess.os.waitpid",
1742 side_effect=ChildProcessError):
1743 with self.assertRaises(subprocess.SubprocessError) as e:
1744 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001745
1746 self.assertIn(repr(error_data), str(e.exception))
1747
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001748 @unittest.skipIf(not os.path.exists('/proc/self/status'),
1749 "need /proc/self/status")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001750 def test_restore_signals(self):
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001751 # Blindly assume that cat exists on systems with /proc/self/status...
1752 default_proc_status = subprocess.check_output(
1753 ['cat', '/proc/self/status'],
1754 restore_signals=False)
1755 for line in default_proc_status.splitlines():
1756 if line.startswith(b'SigIgn'):
1757 default_sig_ign_mask = line
1758 break
1759 else:
1760 self.skipTest("SigIgn not found in /proc/self/status.")
1761 restored_proc_status = subprocess.check_output(
1762 ['cat', '/proc/self/status'],
1763 restore_signals=True)
1764 for line in restored_proc_status.splitlines():
1765 if line.startswith(b'SigIgn'):
1766 restored_sig_ign_mask = line
1767 break
1768 self.assertNotEqual(default_sig_ign_mask, restored_sig_ign_mask,
1769 msg="restore_signals=True should've unblocked "
1770 "SIGPIPE and friends.")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001771
1772 def test_start_new_session(self):
1773 # For code coverage of calling setsid(). We don't care if we get an
1774 # EPERM error from it depending on the test execution environment, that
1775 # still indicates that it was called.
1776 try:
1777 output = subprocess.check_output(
Victor Stinner58840432019-06-14 19:31:43 +02001778 [sys.executable, "-c", "import os; print(os.getsid(0))"],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001779 start_new_session=True)
1780 except OSError as e:
1781 if e.errno != errno.EPERM:
1782 raise
1783 else:
Victor Stinner58840432019-06-14 19:31:43 +02001784 parent_sid = os.getsid(0)
1785 child_sid = int(output)
1786 self.assertNotEqual(parent_sid, child_sid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001787
Patrick McLean2b2ead72019-09-12 10:15:44 -07001788 @unittest.skipUnless(hasattr(os, 'setreuid'), 'no setreuid on platform')
1789 def test_user(self):
1790 # For code coverage of the user parameter. We don't care if we get an
1791 # EPERM error from it depending on the test execution environment, that
1792 # still indicates that it was called.
1793
1794 uid = os.geteuid()
1795 test_users = [65534 if uid != 65534 else 65533, uid]
1796 name_uid = "nobody" if sys.platform != 'darwin' else "unknown"
1797
1798 if pwd is not None:
Victor Stinnerf7b5d412020-03-05 14:28:40 +01001799 try:
1800 pwd.getpwnam(name_uid)
1801 test_users.append(name_uid)
1802 except KeyError:
1803 # unknown user name
1804 name_uid = None
Patrick McLean2b2ead72019-09-12 10:15:44 -07001805
1806 for user in test_users:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001807 # posix_spawn() may be used with close_fds=False
1808 for close_fds in (False, True):
1809 with self.subTest(user=user, close_fds=close_fds):
1810 try:
1811 output = subprocess.check_output(
1812 [sys.executable, "-c",
1813 "import os; print(os.getuid())"],
1814 user=user,
1815 close_fds=close_fds)
1816 except PermissionError: # (EACCES, EPERM)
1817 pass
1818 except OSError as e:
1819 if e.errno not in (errno.EACCES, errno.EPERM):
1820 raise
Patrick McLean2b2ead72019-09-12 10:15:44 -07001821 else:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001822 if isinstance(user, str):
1823 user_uid = pwd.getpwnam(user).pw_uid
1824 else:
1825 user_uid = user
1826 child_user = int(output)
1827 self.assertEqual(child_user, user_uid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001828
1829 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001830 subprocess.check_call(ZERO_RETURN_CMD, user=-1)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001831
Victor Stinnerf7b5d412020-03-05 14:28:40 +01001832 if pwd is None and name_uid is not None:
Patrick McLean2b2ead72019-09-12 10:15:44 -07001833 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001834 subprocess.check_call(ZERO_RETURN_CMD, user=name_uid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001835
1836 @unittest.skipIf(hasattr(os, 'setreuid'), 'setreuid() available on platform')
1837 def test_user_error(self):
1838 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001839 subprocess.check_call(ZERO_RETURN_CMD, user=65535)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001840
1841 @unittest.skipUnless(hasattr(os, 'setregid'), 'no setregid() on platform')
1842 def test_group(self):
1843 gid = os.getegid()
1844 group_list = [65534 if gid != 65534 else 65533]
Gregory P. Smith693aa802019-09-13 14:43:35 +01001845 name_group = _get_test_grp_name()
Patrick McLean2b2ead72019-09-12 10:15:44 -07001846
1847 if grp is not None:
1848 group_list.append(name_group)
1849
1850 for group in group_list + [gid]:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001851 # posix_spawn() may be used with close_fds=False
1852 for close_fds in (False, True):
1853 with self.subTest(group=group, close_fds=close_fds):
1854 try:
1855 output = subprocess.check_output(
1856 [sys.executable, "-c",
1857 "import os; print(os.getgid())"],
1858 group=group,
1859 close_fds=close_fds)
1860 except PermissionError: # (EACCES, EPERM)
1861 pass
Patrick McLean2b2ead72019-09-12 10:15:44 -07001862 else:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001863 if isinstance(group, str):
1864 group_gid = grp.getgrnam(group).gr_gid
1865 else:
1866 group_gid = group
Patrick McLean2b2ead72019-09-12 10:15:44 -07001867
Victor Stinnerfaca8552019-09-25 15:52:49 +02001868 child_group = int(output)
1869 self.assertEqual(child_group, group_gid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001870
1871 # make sure we bomb on negative values
1872 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001873 subprocess.check_call(ZERO_RETURN_CMD, group=-1)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001874
1875 if grp is None:
1876 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001877 subprocess.check_call(ZERO_RETURN_CMD, group=name_group)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001878
1879 @unittest.skipIf(hasattr(os, 'setregid'), 'setregid() available on platform')
1880 def test_group_error(self):
1881 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001882 subprocess.check_call(ZERO_RETURN_CMD, group=65535)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001883
1884 @unittest.skipUnless(hasattr(os, 'setgroups'), 'no setgroups() on platform')
1885 def test_extra_groups(self):
1886 gid = os.getegid()
1887 group_list = [65534 if gid != 65534 else 65533]
Gregory P. Smith693aa802019-09-13 14:43:35 +01001888 name_group = _get_test_grp_name()
Patrick McLean2b2ead72019-09-12 10:15:44 -07001889 perm_error = False
1890
1891 if grp is not None:
1892 group_list.append(name_group)
1893
1894 try:
1895 output = subprocess.check_output(
1896 [sys.executable, "-c",
1897 "import os, sys, json; json.dump(os.getgroups(), sys.stdout)"],
1898 extra_groups=group_list)
1899 except OSError as ex:
1900 if ex.errno != errno.EPERM:
1901 raise
1902 perm_error = True
1903
1904 else:
1905 parent_groups = os.getgroups()
1906 child_groups = json.loads(output)
1907
1908 if grp is not None:
1909 desired_gids = [grp.getgrnam(g).gr_gid if isinstance(g, str) else g
1910 for g in group_list]
1911 else:
1912 desired_gids = group_list
1913
1914 if perm_error:
1915 self.assertEqual(set(child_groups), set(parent_groups))
1916 else:
1917 self.assertEqual(set(desired_gids), set(child_groups))
1918
1919 # make sure we bomb on negative values
1920 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001921 subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[-1])
Patrick McLean2b2ead72019-09-12 10:15:44 -07001922
1923 if grp is None:
1924 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001925 subprocess.check_call(ZERO_RETURN_CMD,
Patrick McLean2b2ead72019-09-12 10:15:44 -07001926 extra_groups=[name_group])
1927
1928 @unittest.skipIf(hasattr(os, 'setgroups'), 'setgroups() available on platform')
1929 def test_extra_groups_error(self):
1930 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001931 subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[])
Patrick McLean2b2ead72019-09-12 10:15:44 -07001932
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07001933 @unittest.skipIf(mswindows or not hasattr(os, 'umask'),
1934 'POSIX umask() is not available.')
1935 def test_umask(self):
1936 tmpdir = None
1937 try:
1938 tmpdir = tempfile.mkdtemp()
1939 name = os.path.join(tmpdir, "beans")
1940 # We set an unusual umask in the child so as a unique mode
1941 # for us to test the child's touched file for.
1942 subprocess.check_call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001943 [sys.executable, "-c", f"open({name!r}, 'w').close()"],
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07001944 umask=0o053)
1945 # Ignore execute permissions entirely in our test,
1946 # filesystems could be mounted to ignore or force that.
1947 st_mode = os.stat(name).st_mode & 0o666
1948 expected_mode = 0o624
1949 self.assertEqual(expected_mode, st_mode,
1950 msg=f'{oct(expected_mode)} != {oct(st_mode)}')
1951 finally:
1952 if tmpdir is not None:
1953 shutil.rmtree(tmpdir)
1954
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001955 def test_run_abort(self):
1956 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001957 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001958 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001959 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001960 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001961 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001962
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001963 def test_CalledProcessError_str_signal(self):
1964 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
1965 error_string = str(err)
1966 # We're relying on the repr() of the signal.Signals intenum to provide
1967 # the word signal, the signal name and the numeric value.
1968 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00001969 # We're not being specific about the signal name as some signals have
1970 # multiple names and which name is revealed can vary.
1971 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001972 self.assertIn(str(signal.SIGABRT), error_string)
1973
1974 def test_CalledProcessError_str_unknown_signal(self):
1975 err = subprocess.CalledProcessError(-9876543, "fake cmd")
1976 error_string = str(err)
1977 self.assertIn("unknown signal 9876543.", error_string)
1978
1979 def test_CalledProcessError_str_non_zero(self):
1980 err = subprocess.CalledProcessError(2, "fake cmd")
1981 error_string = str(err)
1982 self.assertIn("non-zero exit status 2.", error_string)
1983
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001984 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001985 # DISCLAIMER: Setting environment variables is *not* a good use
1986 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001987 p = subprocess.Popen([sys.executable, "-c",
1988 'import sys,os;'
1989 'sys.stdout.write(os.getenv("FRUIT"))'],
1990 stdout=subprocess.PIPE,
1991 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02001992 with p:
1993 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001994
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001995 def test_preexec_exception(self):
1996 def raise_it():
1997 raise ValueError("What if two swallows carried a coconut?")
1998 try:
1999 p = subprocess.Popen([sys.executable, "-c", ""],
2000 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002001 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002002 self.assertTrue(
2003 subprocess._posixsubprocess,
2004 "Expected a ValueError from the preexec_fn")
2005 except ValueError as e:
2006 self.assertIn("coconut", e.args[0])
2007 else:
2008 self.fail("Exception raised by preexec_fn did not make it "
2009 "to the parent process.")
2010
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002011 class _TestExecuteChildPopen(subprocess.Popen):
2012 """Used to test behavior at the end of _execute_child."""
2013 def __init__(self, testcase, *args, **kwargs):
2014 self._testcase = testcase
2015 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002016
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002017 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08002018 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002019 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002020 finally:
2021 # Open a bunch of file descriptors and verify that
2022 # none of them are the same as the ones the Popen
2023 # instance is using for stdin/stdout/stderr.
2024 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
2025 for _ in range(8)]
2026 try:
2027 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002028 self._testcase.assertNotIn(
2029 fd, (self.stdin.fileno(), self.stdout.fileno(),
2030 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08002031 msg="At least one fd was closed early.")
2032 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01002033 for fd in devzero_fds:
2034 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002035
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002036 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
2037 def test_preexec_errpipe_does_not_double_close_pipes(self):
2038 """Issue16140: Don't double close pipes on preexec error."""
2039
2040 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08002041 raise subprocess.SubprocessError(
2042 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08002043
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08002044 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002045 self._TestExecuteChildPopen(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002046 self, ZERO_RETURN_CMD,
Gregory P. Smith12489d92012-11-11 01:37:02 -08002047 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2048 stderr=subprocess.PIPE, preexec_fn=raise_it)
2049
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00002050 def test_preexec_gc_module_failure(self):
2051 # This tests the code that disables garbage collection if the child
2052 # process will execute any Python.
2053 def raise_runtime_error():
2054 raise RuntimeError("this shouldn't escape")
2055 enabled = gc.isenabled()
2056 orig_gc_disable = gc.disable
2057 orig_gc_isenabled = gc.isenabled
2058 try:
2059 gc.disable()
2060 self.assertFalse(gc.isenabled())
2061 subprocess.call([sys.executable, '-c', ''],
2062 preexec_fn=lambda: None)
2063 self.assertFalse(gc.isenabled(),
2064 "Popen enabled gc when it shouldn't.")
2065
2066 gc.enable()
2067 self.assertTrue(gc.isenabled())
2068 subprocess.call([sys.executable, '-c', ''],
2069 preexec_fn=lambda: None)
2070 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
2071
2072 gc.disable = raise_runtime_error
2073 self.assertRaises(RuntimeError, subprocess.Popen,
2074 [sys.executable, '-c', ''],
2075 preexec_fn=lambda: None)
2076
2077 del gc.isenabled # force an AttributeError
2078 self.assertRaises(AttributeError, subprocess.Popen,
2079 [sys.executable, '-c', ''],
2080 preexec_fn=lambda: None)
2081 finally:
2082 gc.disable = orig_gc_disable
2083 gc.isenabled = orig_gc_isenabled
2084 if not enabled:
2085 gc.disable()
2086
Martin Panterf7fdbda2015-12-05 09:51:52 +00002087 @unittest.skipIf(
2088 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00002089 def test_preexec_fork_failure(self):
2090 # The internal code did not preserve the previous exception when
2091 # re-enabling garbage collection
2092 try:
2093 from resource import getrlimit, setrlimit, RLIMIT_NPROC
2094 except ImportError as err:
2095 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
2096 limits = getrlimit(RLIMIT_NPROC)
2097 [_, hard] = limits
2098 setrlimit(RLIMIT_NPROC, (0, hard))
2099 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00002100 try:
Martin Panterafdd5132015-11-30 02:21:41 +00002101 subprocess.call([sys.executable, '-c', ''],
2102 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00002103 except BlockingIOError:
2104 # Forking should raise EAGAIN, translated to BlockingIOError
2105 pass
2106 else:
2107 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00002108
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002109 def test_args_string(self):
2110 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03002111 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002112 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002113 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002114 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002115 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2116 sys.executable)
2117 os.chmod(fname, 0o700)
2118 p = subprocess.Popen(fname)
2119 p.wait()
2120 os.remove(fname)
2121 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002122
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002123 def test_invalid_args(self):
2124 # invalid arguments should raise ValueError
2125 self.assertRaises(ValueError, subprocess.call,
2126 [sys.executable, "-c",
2127 "import sys; sys.exit(47)"],
2128 startupinfo=47)
2129 self.assertRaises(ValueError, subprocess.call,
2130 [sys.executable, "-c",
2131 "import sys; sys.exit(47)"],
2132 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002133
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002134 def test_shell_sequence(self):
2135 # Run command through the shell (sequence)
2136 newenv = os.environ.copy()
2137 newenv["FRUIT"] = "apple"
2138 p = subprocess.Popen(["echo $FRUIT"], shell=1,
2139 stdout=subprocess.PIPE,
2140 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002141 with p:
2142 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002143
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002144 def test_shell_string(self):
2145 # Run command through the shell (string)
2146 newenv = os.environ.copy()
2147 newenv["FRUIT"] = "apple"
2148 p = subprocess.Popen("echo $FRUIT", shell=1,
2149 stdout=subprocess.PIPE,
2150 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002151 with p:
2152 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00002153
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002154 def test_call_string(self):
2155 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03002156 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002157 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002158 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002159 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002160 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2161 sys.executable)
2162 os.chmod(fname, 0o700)
2163 rc = subprocess.call(fname)
2164 os.remove(fname)
2165 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00002166
Stefan Krah9542cc62010-07-19 14:20:53 +00002167 def test_specific_shell(self):
2168 # Issue #9265: Incorrect name passed as arg[0].
2169 shells = []
2170 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
2171 for name in ['bash', 'ksh']:
2172 sh = os.path.join(prefix, name)
2173 if os.path.isfile(sh):
2174 shells.append(sh)
2175 if not shells: # Will probably work for any shell but csh.
2176 self.skipTest("bash or ksh required for this test")
2177 sh = '/bin/sh'
2178 if os.path.isfile(sh) and not os.path.islink(sh):
2179 # Test will fail if /bin/sh is a symlink to csh.
2180 shells.append(sh)
2181 for sh in shells:
2182 p = subprocess.Popen("echo $0", executable=sh, shell=True,
2183 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002184 with p:
2185 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00002186
Florent Xicluna4886d242010-03-08 13:27:26 +00002187 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00002188 # Do not inherit file handles from the parent.
2189 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07002190 # Also set the SIGINT handler to the default to make sure it's not
2191 # being ignored (some tests rely on that.)
2192 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
2193 try:
2194 p = subprocess.Popen([sys.executable, "-c", """if 1:
2195 import sys, time
2196 sys.stdout.write('x\\n')
2197 sys.stdout.flush()
2198 time.sleep(30)
2199 """],
2200 close_fds=True,
2201 stdin=subprocess.PIPE,
2202 stdout=subprocess.PIPE,
2203 stderr=subprocess.PIPE)
2204 finally:
2205 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00002206 # Wait for the interpreter to be completely initialized before
2207 # sending any signal.
2208 p.stdout.read(1)
2209 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00002210 return p
2211
Charles-François Natali53221e32013-01-12 16:52:20 +01002212 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
2213 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002214 def _kill_dead_process(self, method, *args):
2215 # Do not inherit file handles from the parent.
2216 # It should fix failures on some platforms.
2217 p = subprocess.Popen([sys.executable, "-c", """if 1:
2218 import sys, time
2219 sys.stdout.write('x\\n')
2220 sys.stdout.flush()
2221 """],
2222 close_fds=True,
2223 stdin=subprocess.PIPE,
2224 stdout=subprocess.PIPE,
2225 stderr=subprocess.PIPE)
2226 # Wait for the interpreter to be completely initialized before
2227 # sending any signal.
2228 p.stdout.read(1)
2229 # The process should end after this
2230 time.sleep(1)
2231 # This shouldn't raise even though the child is now dead
2232 getattr(p, method)(*args)
2233 p.communicate()
2234
Florent Xicluna4886d242010-03-08 13:27:26 +00002235 def test_send_signal(self):
2236 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00002237 _, stderr = p.communicate()
2238 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002239 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00002240
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002241 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002242 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00002243 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002244 self.assertEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002245 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00002246
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002247 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002248 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00002249 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002250 self.assertEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002251 self.assertEqual(p.wait(), -signal.SIGTERM)
2252
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002253 def test_send_signal_dead(self):
2254 # Sending a signal to a dead process
2255 self._kill_dead_process('send_signal', signal.SIGINT)
2256
2257 def test_kill_dead(self):
2258 # Killing a dead process
2259 self._kill_dead_process('kill')
2260
2261 def test_terminate_dead(self):
2262 # Terminating a dead process
2263 self._kill_dead_process('terminate')
2264
Victor Stinnerdaf45552013-08-28 00:53:59 +02002265 def _save_fds(self, save_fds):
2266 fds = []
2267 for fd in save_fds:
2268 inheritable = os.get_inheritable(fd)
2269 saved = os.dup(fd)
2270 fds.append((fd, saved, inheritable))
2271 return fds
2272
2273 def _restore_fds(self, fds):
2274 for fd, saved, inheritable in fds:
2275 os.dup2(saved, fd, inheritable=inheritable)
2276 os.close(saved)
2277
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002278 def check_close_std_fds(self, fds):
2279 # Issue #9905: test that subprocess pipes still work properly with
2280 # some standard fds closed
2281 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02002282 saved_fds = self._save_fds(fds)
2283 for fd, saved, inheritable in saved_fds:
2284 if fd == 0:
2285 stdin = saved
2286 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002287 try:
2288 for fd in fds:
2289 os.close(fd)
2290 out, err = subprocess.Popen([sys.executable, "-c",
2291 'import sys;'
2292 'sys.stdout.write("apple");'
2293 'sys.stdout.flush();'
2294 'sys.stderr.write("orange")'],
2295 stdin=stdin,
2296 stdout=subprocess.PIPE,
2297 stderr=subprocess.PIPE).communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002298 self.assertEqual(out, b'apple')
2299 self.assertEqual(err, b'orange')
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002300 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002301 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002302
2303 def test_close_fd_0(self):
2304 self.check_close_std_fds([0])
2305
2306 def test_close_fd_1(self):
2307 self.check_close_std_fds([1])
2308
2309 def test_close_fd_2(self):
2310 self.check_close_std_fds([2])
2311
2312 def test_close_fds_0_1(self):
2313 self.check_close_std_fds([0, 1])
2314
2315 def test_close_fds_0_2(self):
2316 self.check_close_std_fds([0, 2])
2317
2318 def test_close_fds_1_2(self):
2319 self.check_close_std_fds([1, 2])
2320
2321 def test_close_fds_0_1_2(self):
2322 # Issue #10806: test that subprocess pipes still work properly with
2323 # all standard fds closed.
2324 self.check_close_std_fds([0, 1, 2])
2325
Gregory P. Smith53dd8162013-12-01 16:03:24 -08002326 def test_small_errpipe_write_fd(self):
2327 """Issue #15798: Popen should work when stdio fds are available."""
2328 new_stdin = os.dup(0)
2329 new_stdout = os.dup(1)
2330 try:
2331 os.close(0)
2332 os.close(1)
2333
2334 # Side test: if errpipe_write fails to have its CLOEXEC
2335 # flag set this should cause the parent to think the exec
2336 # failed. Extremely unlikely: everyone supports CLOEXEC.
2337 subprocess.Popen([
2338 sys.executable, "-c",
2339 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
2340 finally:
2341 # Restore original stdin and stdout
2342 os.dup2(new_stdin, 0)
2343 os.dup2(new_stdout, 1)
2344 os.close(new_stdin)
2345 os.close(new_stdout)
2346
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002347 def test_remapping_std_fds(self):
2348 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002349 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002350 try:
2351 temp_fds = [fd for fd, fname in temps]
2352
2353 # unlink the files -- we won't need to reopen them
2354 for fd, fname in temps:
2355 os.unlink(fname)
2356
2357 # write some data to what will become stdin, and rewind
2358 os.write(temp_fds[1], b"STDIN")
2359 os.lseek(temp_fds[1], 0, 0)
2360
2361 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02002362 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002363 try:
2364 # duplicate the file objects over the standard fd's
2365 for fd, temp_fd in enumerate(temp_fds):
2366 os.dup2(temp_fd, fd)
2367
2368 # now use those files in the "wrong" order, so that subprocess
2369 # has to rearrange them in the child
2370 p = subprocess.Popen([sys.executable, "-c",
2371 'import sys; got = sys.stdin.read();'
2372 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2373 stdin=temp_fds[1],
2374 stdout=temp_fds[2],
2375 stderr=temp_fds[0])
2376 p.wait()
2377 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002378 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002379
2380 for fd in temp_fds:
2381 os.lseek(fd, 0, 0)
2382
2383 out = os.read(temp_fds[2], 1024)
Victor Stinner6cac1132019-12-08 08:38:16 +01002384 err = os.read(temp_fds[0], 1024).strip()
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002385 self.assertEqual(out, b"got STDIN")
2386 self.assertEqual(err, b"err")
2387
2388 finally:
2389 for fd in temp_fds:
2390 os.close(fd)
2391
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002392 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
2393 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002394 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002395 temp_fds = [fd for fd, fname in temps]
2396 try:
2397 # unlink the files -- we won't need to reopen them
2398 for fd, fname in temps:
2399 os.unlink(fname)
2400
2401 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02002402 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002403 try:
2404 # duplicate the temp files over the standard fd's 0, 1, 2
2405 for fd, temp_fd in enumerate(temp_fds):
2406 os.dup2(temp_fd, fd)
2407
2408 # write some data to what will become stdin, and rewind
2409 os.write(stdin_no, b"STDIN")
2410 os.lseek(stdin_no, 0, 0)
2411
2412 # now use those files in the given order, so that subprocess
2413 # has to rearrange them in the child
2414 p = subprocess.Popen([sys.executable, "-c",
2415 'import sys; got = sys.stdin.read();'
2416 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2417 stdin=stdin_no,
2418 stdout=stdout_no,
2419 stderr=stderr_no)
2420 p.wait()
2421
2422 for fd in temp_fds:
2423 os.lseek(fd, 0, 0)
2424
2425 out = os.read(stdout_no, 1024)
Victor Stinner6cac1132019-12-08 08:38:16 +01002426 err = os.read(stderr_no, 1024).strip()
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002427 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002428 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002429
2430 self.assertEqual(out, b"got STDIN")
2431 self.assertEqual(err, b"err")
2432
2433 finally:
2434 for fd in temp_fds:
2435 os.close(fd)
2436
2437 # When duping fds, if there arises a situation where one of the fds is
2438 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
2439 # This tests all combinations of this.
2440 def test_swap_fds(self):
2441 self.check_swap_fds(0, 1, 2)
2442 self.check_swap_fds(0, 2, 1)
2443 self.check_swap_fds(1, 0, 2)
2444 self.check_swap_fds(1, 2, 0)
2445 self.check_swap_fds(2, 0, 1)
2446 self.check_swap_fds(2, 1, 0)
2447
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +03002448 def _check_swap_std_fds_with_one_closed(self, from_fds, to_fds):
2449 saved_fds = self._save_fds(range(3))
2450 try:
2451 for from_fd in from_fds:
2452 with tempfile.TemporaryFile() as f:
2453 os.dup2(f.fileno(), from_fd)
2454
2455 fd_to_close = (set(range(3)) - set(from_fds)).pop()
2456 os.close(fd_to_close)
2457
2458 arg_names = ['stdin', 'stdout', 'stderr']
2459 kwargs = {}
2460 for from_fd, to_fd in zip(from_fds, to_fds):
2461 kwargs[arg_names[to_fd]] = from_fd
2462
2463 code = textwrap.dedent(r'''
2464 import os, sys
2465 skipped_fd = int(sys.argv[1])
2466 for fd in range(3):
2467 if fd != skipped_fd:
2468 os.write(fd, str(fd).encode('ascii'))
2469 ''')
2470
2471 skipped_fd = (set(range(3)) - set(to_fds)).pop()
2472
2473 rc = subprocess.call([sys.executable, '-c', code, str(skipped_fd)],
2474 **kwargs)
2475 self.assertEqual(rc, 0)
2476
2477 for from_fd, to_fd in zip(from_fds, to_fds):
2478 os.lseek(from_fd, 0, os.SEEK_SET)
2479 read_bytes = os.read(from_fd, 1024)
2480 read_fds = list(map(int, read_bytes.decode('ascii')))
2481 msg = textwrap.dedent(f"""
2482 When testing {from_fds} to {to_fds} redirection,
2483 parent descriptor {from_fd} got redirected
2484 to descriptor(s) {read_fds} instead of descriptor {to_fd}.
2485 """)
2486 self.assertEqual([to_fd], read_fds, msg)
2487 finally:
2488 self._restore_fds(saved_fds)
2489
2490 # Check that subprocess can remap std fds correctly even
2491 # if one of them is closed (#32844).
2492 def test_swap_std_fds_with_one_closed(self):
2493 for from_fds in itertools.combinations(range(3), 2):
2494 for to_fds in itertools.permutations(range(3), 2):
2495 self._check_swap_std_fds_with_one_closed(from_fds, to_fds)
2496
Victor Stinner13bb71c2010-04-23 21:41:56 +00002497 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00002498 def prepare():
2499 raise ValueError("surrogate:\uDCff")
2500
2501 try:
2502 subprocess.call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002503 ZERO_RETURN_CMD,
Victor Stinner4d078042010-04-23 19:28:32 +00002504 preexec_fn=prepare)
2505 except ValueError as err:
2506 # Pure Python implementations keeps the message
2507 self.assertIsNone(subprocess._posixsubprocess)
2508 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002509 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00002510 # _posixsubprocess uses a default message
2511 self.assertIsNotNone(subprocess._posixsubprocess)
2512 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
2513 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002514 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00002515
Victor Stinner13bb71c2010-04-23 21:41:56 +00002516 def test_undecodable_env(self):
2517 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01002518 encoded_value = value.encode("ascii", "surrogateescape")
2519
Victor Stinner13bb71c2010-04-23 21:41:56 +00002520 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002521 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002522 env = os.environ.copy()
2523 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01002524 # Use C locale to get ASCII for the locale encoding to force
Michael Felt89d79b12018-08-26 19:29:36 +02002525 # surrogate-escaping of \xFF in the child process
Victor Stinnerebc78d22010-10-14 10:38:17 +00002526 env['LC_ALL'] = 'C'
Michael Felt89d79b12018-08-26 19:29:36 +02002527 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002528 stdout = subprocess.check_output(
2529 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002530 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002531 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002532 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002533
2534 # test bytes
2535 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002536 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002537 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01002538 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002539 stdout = subprocess.check_output(
2540 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002541 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002542 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002543 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002544
Victor Stinnerb745a742010-05-18 17:17:23 +00002545 def test_bytes_program(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002546 abs_program = os.fsencode(ZERO_RETURN_CMD[0])
2547 args = list(ZERO_RETURN_CMD[1:])
2548 path, program = os.path.split(ZERO_RETURN_CMD[0])
Victor Stinnerb745a742010-05-18 17:17:23 +00002549 program = os.fsencode(program)
2550
2551 # absolute bytes path
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002552 exitcode = subprocess.call([abs_program]+args)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002553 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002554
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002555 # absolute bytes path as a string
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002556 cmd = b"'%s' %s" % (abs_program, " ".join(args).encode("utf-8"))
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002557 exitcode = subprocess.call(cmd, shell=True)
2558 self.assertEqual(exitcode, 0)
2559
Victor Stinnerb745a742010-05-18 17:17:23 +00002560 # bytes program, unicode PATH
2561 env = os.environ.copy()
2562 env["PATH"] = path
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002563 exitcode = subprocess.call([program]+args, env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002564 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002565
2566 # bytes program, bytes PATH
2567 envb = os.environb.copy()
2568 envb[b"PATH"] = os.fsencode(path)
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002569 exitcode = subprocess.call([program]+args, env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002570 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002571
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002572 def test_pipe_cloexec(self):
2573 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2574 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2575
2576 p1 = subprocess.Popen([sys.executable, sleeper],
2577 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2578 stderr=subprocess.PIPE, close_fds=False)
2579
2580 self.addCleanup(p1.communicate, b'')
2581
2582 p2 = subprocess.Popen([sys.executable, fd_status],
2583 stdout=subprocess.PIPE, close_fds=False)
2584
2585 output, error = p2.communicate()
2586 result_fds = set(map(int, output.split(b',')))
2587 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2588 p1.stderr.fileno()])
2589
2590 self.assertFalse(result_fds & unwanted_fds,
2591 "Expected no fds from %r to be open in child, "
2592 "found %r" %
2593 (unwanted_fds, result_fds & unwanted_fds))
2594
2595 def test_pipe_cloexec_real_tools(self):
2596 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2597 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2598
2599 subdata = b'zxcvbn'
2600 data = subdata * 4 + b'\n'
2601
2602 p1 = subprocess.Popen([sys.executable, qcat],
2603 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2604 close_fds=False)
2605
2606 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2607 stdin=p1.stdout, stdout=subprocess.PIPE,
2608 close_fds=False)
2609
2610 self.addCleanup(p1.wait)
2611 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002612 def kill_p1():
2613 try:
2614 p1.terminate()
2615 except ProcessLookupError:
2616 pass
2617 def kill_p2():
2618 try:
2619 p2.terminate()
2620 except ProcessLookupError:
2621 pass
2622 self.addCleanup(kill_p1)
2623 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002624
2625 p1.stdin.write(data)
2626 p1.stdin.close()
2627
2628 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2629
2630 self.assertTrue(readfiles, "The child hung")
2631 self.assertEqual(p2.stdout.read(), data)
2632
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002633 p1.stdout.close()
2634 p2.stdout.close()
2635
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002636 def test_close_fds(self):
2637 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2638
2639 fds = os.pipe()
2640 self.addCleanup(os.close, fds[0])
2641 self.addCleanup(os.close, fds[1])
2642
2643 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002644 # add a bunch more fds
2645 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002646 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002647 self.addCleanup(os.close, fd)
2648 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002649
Victor Stinnerdaf45552013-08-28 00:53:59 +02002650 for fd in open_fds:
2651 os.set_inheritable(fd, True)
2652
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002653 p = subprocess.Popen([sys.executable, fd_status],
2654 stdout=subprocess.PIPE, close_fds=False)
2655 output, ignored = p.communicate()
2656 remaining_fds = set(map(int, output.split(b',')))
2657
2658 self.assertEqual(remaining_fds & open_fds, open_fds,
2659 "Some fds were closed")
2660
2661 p = subprocess.Popen([sys.executable, fd_status],
2662 stdout=subprocess.PIPE, close_fds=True)
2663 output, ignored = p.communicate()
2664 remaining_fds = set(map(int, output.split(b',')))
2665
2666 self.assertFalse(remaining_fds & open_fds,
2667 "Some fds were left open")
2668 self.assertIn(1, remaining_fds, "Subprocess failed")
2669
Gregory P. Smith8facece2012-01-21 14:01:08 -08002670 # Keep some of the fd's we opened open in the subprocess.
2671 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2672 fds_to_keep = set(open_fds.pop() for _ in range(8))
2673 p = subprocess.Popen([sys.executable, fd_status],
2674 stdout=subprocess.PIPE, close_fds=True,
izbyshev2d8f0632017-12-19 03:26:49 +07002675 pass_fds=fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002676 output, ignored = p.communicate()
2677 remaining_fds = set(map(int, output.split(b',')))
2678
izbyshev2d8f0632017-12-19 03:26:49 +07002679 self.assertFalse((remaining_fds - fds_to_keep) & open_fds,
Gregory P. Smith8facece2012-01-21 14:01:08 -08002680 "Some fds not in pass_fds were left open")
2681 self.assertIn(1, remaining_fds, "Subprocess failed")
2682
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002683
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002684 @unittest.skipIf(sys.platform.startswith("freebsd") and
2685 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2686 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002687 def test_close_fds_when_max_fd_is_lowered(self):
2688 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2689 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2690
Gregory P. Smith634aa682014-06-15 17:51:04 -07002691 # This launches the meat of the test in a child process to
2692 # avoid messing with the larger unittest processes maximum
2693 # number of file descriptors.
2694 # This process launches:
2695 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2696 # a bunch of high open fds above the new lower rlimit.
2697 # Those are reported via stdout before launching a new
2698 # process with close_fds=False to run the actual test:
2699 # +--> The TEST: This one launches a fd_status.py
2700 # subprocess with close_fds=True so we can find out if
2701 # any of the fds above the lowered rlimit are still open.
2702 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2703 '''
2704 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002705 open_fds = set()
2706 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002707 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002708 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002709 open_fds.add(fd)
2710
2711 # Leave a two pairs of low ones available for use by the
2712 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002713 # We also leave 10 more open as some Python buildbots run into
2714 # "too many open files" errors during the test if we do not.
2715 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002716 os.close(fd)
2717 open_fds.remove(fd)
2718
2719 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002720 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002721 os.set_inheritable(fd, True)
2722
2723 max_fd_open = max(open_fds)
2724
Gregory P. Smith634aa682014-06-15 17:51:04 -07002725 # Communicate the open_fds to the parent unittest.TestCase process.
2726 print(','.join(map(str, sorted(open_fds))))
2727 sys.stdout.flush()
2728
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002729 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2730 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002731 # 29 is lower than the highest fds we are leaving open.
2732 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002733 # Launch a new Python interpreter with our low fd rlim_cur that
2734 # inherits open fds above that limit. It then uses subprocess
2735 # with close_fds=True to get a report of open fds in the child.
2736 # An explicit list of fds to check is passed to fd_status.py as
2737 # letting fd_status rely on its default logic would miss the
2738 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002739 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002740 [sys.executable, '-c',
2741 textwrap.dedent("""
2742 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002743 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002744 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002745 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002746 """.format(max_fd=max_fd_open+1))],
2747 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002748 finally:
2749 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002750 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002751
2752 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002753 output_lines = output.splitlines()
2754 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002755 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002756 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2757 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002758
Gregory P. Smith634aa682014-06-15 17:51:04 -07002759 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002760 msg="Some fds were left open.")
2761
2762
Victor Stinner88701e22011-06-01 13:13:04 +02002763 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2764 # descriptor of a pipe closed in the parent process is valid in the
2765 # child process according to fstat(), but the mode of the file
2766 # descriptor is invalid, and read or write raise an error.
2767 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002768 def test_pass_fds(self):
2769 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2770
2771 open_fds = set()
2772
2773 for x in range(5):
2774 fds = os.pipe()
2775 self.addCleanup(os.close, fds[0])
2776 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002777 os.set_inheritable(fds[0], True)
2778 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002779 open_fds.update(fds)
2780
2781 for fd in open_fds:
2782 p = subprocess.Popen([sys.executable, fd_status],
2783 stdout=subprocess.PIPE, close_fds=True,
2784 pass_fds=(fd, ))
2785 output, ignored = p.communicate()
2786
2787 remaining_fds = set(map(int, output.split(b',')))
2788 to_be_closed = open_fds - {fd}
2789
2790 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2791 self.assertFalse(remaining_fds & to_be_closed,
2792 "fd to be closed passed")
2793
2794 # pass_fds overrides close_fds with a warning.
2795 with self.assertWarns(RuntimeWarning) as context:
2796 self.assertFalse(subprocess.call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002797 ZERO_RETURN_CMD,
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002798 close_fds=False, pass_fds=(fd, )))
2799 self.assertIn('overriding close_fds', str(context.warning))
2800
Victor Stinnerdaf45552013-08-28 00:53:59 +02002801 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002802 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002803
2804 inheritable, non_inheritable = os.pipe()
2805 self.addCleanup(os.close, inheritable)
2806 self.addCleanup(os.close, non_inheritable)
2807 os.set_inheritable(inheritable, True)
2808 os.set_inheritable(non_inheritable, False)
2809 pass_fds = (inheritable, non_inheritable)
2810 args = [sys.executable, script]
2811 args += list(map(str, pass_fds))
2812
2813 p = subprocess.Popen(args,
2814 stdout=subprocess.PIPE, close_fds=True,
2815 pass_fds=pass_fds)
2816 output, ignored = p.communicate()
2817 fds = set(map(int, output.split(b',')))
2818
2819 # the inheritable file descriptor must be inherited, so its inheritable
2820 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002821 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002822
2823 # inheritable flag must not be changed in the parent process
2824 self.assertEqual(os.get_inheritable(inheritable), True)
2825 self.assertEqual(os.get_inheritable(non_inheritable), False)
2826
Gregory P. Smithce344102018-09-10 17:46:22 -07002827
2828 # bpo-32270: Ensure that descriptors specified in pass_fds
2829 # are inherited even if they are used in redirections.
2830 # Contributed by @izbyshev.
2831 def test_pass_fds_redirected(self):
2832 """Regression test for https://bugs.python.org/issue32270."""
2833 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2834 pass_fds = []
2835 for _ in range(2):
2836 fd = os.open(os.devnull, os.O_RDWR)
2837 self.addCleanup(os.close, fd)
2838 pass_fds.append(fd)
2839
2840 stdout_r, stdout_w = os.pipe()
2841 self.addCleanup(os.close, stdout_r)
2842 self.addCleanup(os.close, stdout_w)
2843 pass_fds.insert(1, stdout_w)
2844
2845 with subprocess.Popen([sys.executable, fd_status],
2846 stdin=pass_fds[0],
2847 stdout=pass_fds[1],
2848 stderr=pass_fds[2],
2849 close_fds=True,
2850 pass_fds=pass_fds):
2851 output = os.read(stdout_r, 1024)
2852 fds = {int(num) for num in output.split(b',')}
2853
2854 self.assertEqual(fds, {0, 1, 2} | frozenset(pass_fds), f"output={output!a}")
2855
2856
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002857 def test_stdout_stdin_are_single_inout_fd(self):
2858 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002859 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002860 stdout=inout, stdin=inout)
2861 p.wait()
2862
2863 def test_stdout_stderr_are_single_inout_fd(self):
2864 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002865 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002866 stdout=inout, stderr=inout)
2867 p.wait()
2868
2869 def test_stderr_stdin_are_single_inout_fd(self):
2870 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002871 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002872 stderr=inout, stdin=inout)
2873 p.wait()
2874
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002875 def test_wait_when_sigchild_ignored(self):
2876 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2877 sigchild_ignore = support.findfile("sigchild_ignore.py",
2878 subdir="subprocessdata")
2879 p = subprocess.Popen([sys.executable, sigchild_ignore],
2880 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2881 stdout, stderr = p.communicate()
2882 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002883 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002884 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002885
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002886 def test_select_unbuffered(self):
2887 # Issue #11459: bufsize=0 should really set the pipes as
2888 # unbuffered (and therefore let select() work properly).
Hai Shi0c4f0f32020-06-30 21:46:31 +08002889 select = import_helper.import_module("select")
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002890 p = subprocess.Popen([sys.executable, "-c",
2891 'import sys;'
2892 'sys.stdout.write("apple")'],
2893 stdout=subprocess.PIPE,
2894 bufsize=0)
2895 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002896 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002897 try:
2898 self.assertEqual(f.read(4), b"appl")
2899 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2900 finally:
2901 p.wait()
2902
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002903 def test_zombie_fast_process_del(self):
2904 # Issue #12650: on Unix, if Popen.__del__() was called before the
2905 # process exited, it wouldn't be added to subprocess._active, and would
2906 # remain a zombie.
2907 # spawn a Popen, and delete its reference before it exits
2908 p = subprocess.Popen([sys.executable, "-c",
2909 'import sys, time;'
2910 'time.sleep(0.2)'],
2911 stdout=subprocess.PIPE,
2912 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002913 self.addCleanup(p.stdout.close)
2914 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002915 ident = id(p)
2916 pid = p.pid
Hai Shi0c4f0f32020-06-30 21:46:31 +08002917 with warnings_helper.check_warnings(('', ResourceWarning)):
Victor Stinner5a48e212016-05-20 12:11:15 +02002918 p = None
2919
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002920 if mswindows:
2921 # subprocess._active is not used on Windows and is set to None.
2922 self.assertIsNone(subprocess._active)
2923 else:
2924 # check that p is in the active processes list
2925 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002926
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002927 def test_leak_fast_process_del_killed(self):
2928 # Issue #12650: on Unix, if Popen.__del__() was called before the
2929 # process exited, and the process got killed by a signal, it would never
2930 # be removed from subprocess._active, which triggered a FD and memory
2931 # leak.
2932 # spawn a Popen, delete its reference and kill it
2933 p = subprocess.Popen([sys.executable, "-c",
2934 'import time;'
2935 'time.sleep(3)'],
2936 stdout=subprocess.PIPE,
2937 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002938 self.addCleanup(p.stdout.close)
2939 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002940 ident = id(p)
2941 pid = p.pid
Hai Shi0c4f0f32020-06-30 21:46:31 +08002942 with warnings_helper.check_warnings(('', ResourceWarning)):
Victor Stinner5a48e212016-05-20 12:11:15 +02002943 p = None
2944
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002945 os.kill(pid, signal.SIGKILL)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002946 if mswindows:
2947 # subprocess._active is not used on Windows and is set to None.
2948 self.assertIsNone(subprocess._active)
2949 else:
2950 # check that p is in the active processes list
2951 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002952
2953 # let some time for the process to exit, and create a new Popen: this
2954 # should trigger the wait() of p
2955 time.sleep(0.2)
Victor Stinnerb31206a2018-01-25 19:06:05 +01002956 with self.assertRaises(OSError):
Victor Stinner9a83f652017-08-21 23:51:31 +02002957 with subprocess.Popen(NONEXISTING_CMD,
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002958 stdout=subprocess.PIPE,
2959 stderr=subprocess.PIPE) as proc:
2960 pass
2961 # p should have been wait()ed on, and removed from the _active list
2962 self.assertRaises(OSError, os.waitpid, pid, 0)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002963 if mswindows:
2964 # subprocess._active is not used on Windows and is set to None.
2965 self.assertIsNone(subprocess._active)
2966 else:
2967 self.assertNotIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002968
Charles-François Natali249cdc32013-08-25 18:24:45 +02002969 def test_close_fds_after_preexec(self):
2970 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2971
2972 # this FD is used as dup2() target by preexec_fn, and should be closed
2973 # in the child process
2974 fd = os.dup(1)
2975 self.addCleanup(os.close, fd)
2976
2977 p = subprocess.Popen([sys.executable, fd_status],
2978 stdout=subprocess.PIPE, close_fds=True,
2979 preexec_fn=lambda: os.dup2(1, fd))
2980 output, ignored = p.communicate()
2981
2982 remaining_fds = set(map(int, output.split(b',')))
2983
2984 self.assertNotIn(fd, remaining_fds)
2985
Victor Stinner8f437aa2014-10-05 17:25:19 +02002986 @support.cpython_only
2987 def test_fork_exec(self):
2988 # Issue #22290: fork_exec() must not crash on memory allocation failure
2989 # or other errors
2990 import _posixsubprocess
2991 gc_enabled = gc.isenabled()
2992 try:
2993 # Use a preexec function and enable the garbage collector
2994 # to force fork_exec() to re-enable the garbage collector
2995 # on error.
2996 func = lambda: None
2997 gc.enable()
2998
Victor Stinner8f437aa2014-10-05 17:25:19 +02002999 for args, exe_list, cwd, env_list in (
3000 (123, [b"exe"], None, [b"env"]),
3001 ([b"arg"], 123, None, [b"env"]),
3002 ([b"arg"], [b"exe"], 123, [b"env"]),
3003 ([b"arg"], [b"exe"], None, 123),
3004 ):
Patrick McLean2b2ead72019-09-12 10:15:44 -07003005 with self.assertRaises(TypeError) as err:
Victor Stinner8f437aa2014-10-05 17:25:19 +02003006 _posixsubprocess.fork_exec(
3007 args, exe_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003008 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02003009 -1, -1, -1, -1,
3010 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003011 True, True,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07003012 False, [], 0, -1,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003013 func)
3014 # Attempt to prevent
3015 # "TypeError: fork_exec() takes exactly N arguments (M given)"
3016 # from passing the test. More refactoring to have us start
3017 # with a valid *args list, confirm a good call with that works
3018 # before mutating it in various ways to ensure that bad calls
3019 # with individual arg type errors raise a typeerror would be
3020 # ideal. Saving that for a future PR...
3021 self.assertNotIn('takes exactly', str(err.exception))
Victor Stinner8f437aa2014-10-05 17:25:19 +02003022 finally:
3023 if not gc_enabled:
3024 gc.disable()
3025
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003026 @support.cpython_only
3027 def test_fork_exec_sorted_fd_sanity_check(self):
3028 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
3029 import _posixsubprocess
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003030 class BadInt:
3031 first = True
3032 def __init__(self, value):
3033 self.value = value
3034 def __int__(self):
3035 if self.first:
3036 self.first = False
3037 return self.value
3038 raise ValueError
3039
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003040 gc_enabled = gc.isenabled()
3041 try:
3042 gc.enable()
3043
3044 for fds_to_keep in (
3045 (-1, 2, 3, 4, 5), # Negative number.
3046 ('str', 4), # Not an int.
3047 (18, 23, 42, 2**63), # Out of range.
3048 (5, 4), # Not sorted.
3049 (6, 7, 7, 8), # Duplicate.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003050 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003051 ):
3052 with self.assertRaises(
3053 ValueError,
3054 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
3055 _posixsubprocess.fork_exec(
3056 [b"false"], [b"false"],
3057 True, fds_to_keep, None, [b"env"],
3058 -1, -1, -1, -1,
3059 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003060 True, True,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07003061 None, None, None, -1,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003062 None)
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003063 self.assertIn('fds_to_keep', str(c.exception))
3064 finally:
3065 if not gc_enabled:
3066 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02003067
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003068 def test_communicate_BrokenPipeError_stdin_close(self):
3069 # By not setting stdout or stderr or a timeout we force the fast path
3070 # that just calls _stdin_write() internally due to our mock.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003071 proc = subprocess.Popen(ZERO_RETURN_CMD)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003072 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3073 mock_proc_stdin.close.side_effect = BrokenPipeError
3074 proc.communicate() # Should swallow BrokenPipeError from close.
3075 mock_proc_stdin.close.assert_called_with()
3076
3077 def test_communicate_BrokenPipeError_stdin_write(self):
3078 # By not setting stdout or stderr or a timeout we force the fast path
3079 # that just calls _stdin_write() internally due to our mock.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003080 proc = subprocess.Popen(ZERO_RETURN_CMD)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003081 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3082 mock_proc_stdin.write.side_effect = BrokenPipeError
3083 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
3084 mock_proc_stdin.write.assert_called_once_with(b'stuff')
3085 mock_proc_stdin.close.assert_called_once_with()
3086
3087 def test_communicate_BrokenPipeError_stdin_flush(self):
3088 # Setting stdin and stdout forces the ._communicate() code path.
3089 # python -h exits faster than python -c pass (but spams stdout).
3090 proc = subprocess.Popen([sys.executable, '-h'],
3091 stdin=subprocess.PIPE,
3092 stdout=subprocess.PIPE)
3093 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
3094 open(os.devnull, 'wb') as dev_null:
3095 mock_proc_stdin.flush.side_effect = BrokenPipeError
3096 # because _communicate registers a selector using proc.stdin...
3097 mock_proc_stdin.fileno.return_value = dev_null.fileno()
3098 # _communicate() should swallow BrokenPipeError from flush.
3099 proc.communicate(b'stuff')
3100 mock_proc_stdin.flush.assert_called_once_with()
3101
3102 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
3103 # Setting stdin and stdout forces the ._communicate() code path.
3104 # python -h exits faster than python -c pass (but spams stdout).
3105 proc = subprocess.Popen([sys.executable, '-h'],
3106 stdin=subprocess.PIPE,
3107 stdout=subprocess.PIPE)
3108 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3109 mock_proc_stdin.close.side_effect = BrokenPipeError
3110 # _communicate() should swallow BrokenPipeError from close.
3111 proc.communicate(timeout=999)
3112 mock_proc_stdin.close.assert_called_once_with()
3113
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003114 @unittest.skipUnless(_testcapi is not None
3115 and hasattr(_testcapi, 'W_STOPCODE'),
3116 'need _testcapi.W_STOPCODE')
3117 def test_stopped(self):
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003118 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003119 args = ZERO_RETURN_CMD
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003120 proc = subprocess.Popen(args)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003121
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003122 # Wait until the real process completes to avoid zombie process
Victor Stinner278c1e12020-03-31 20:08:12 +02003123 support.wait_process(proc.pid, exitcode=0)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003124
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003125 status = _testcapi.W_STOPCODE(3)
Victor Stinner278c1e12020-03-31 20:08:12 +02003126 with mock.patch('subprocess.os.waitpid', return_value=(proc.pid, status)):
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003127 returncode = proc.wait()
Victor Stinnercdee3f12017-06-26 17:23:03 +02003128
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003129 self.assertEqual(returncode, -3)
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003130
Victor Stinnere85a3052020-01-15 17:38:55 +01003131 def test_send_signal_race(self):
3132 # bpo-38630: send_signal() must poll the process exit status to reduce
3133 # the risk of sending the signal to the wrong process.
3134 proc = subprocess.Popen(ZERO_RETURN_CMD)
3135
3136 # wait until the process completes without using the Popen APIs.
Victor Stinner278c1e12020-03-31 20:08:12 +02003137 support.wait_process(proc.pid, exitcode=0)
Victor Stinnere85a3052020-01-15 17:38:55 +01003138
3139 # returncode is still None but the process completed.
3140 self.assertIsNone(proc.returncode)
3141
3142 with mock.patch("os.kill") as mock_kill:
3143 proc.send_signal(signal.SIGTERM)
3144
3145 # send_signal() didn't call os.kill() since the process already
3146 # completed.
3147 mock_kill.assert_not_called()
3148
3149 # Don't check the returncode value: the test reads the exit status,
3150 # so Popen failed to read it and uses a default returncode instead.
3151 self.assertIsNotNone(proc.returncode)
3152
Alex Rebertd3ae95e2020-01-22 18:28:31 -05003153 def test_communicate_repeated_call_after_stdout_close(self):
3154 proc = subprocess.Popen([sys.executable, '-c',
3155 'import os, time; os.close(1), time.sleep(2)'],
3156 stdout=subprocess.PIPE)
3157 while True:
3158 try:
3159 proc.communicate(timeout=0.1)
3160 return
3161 except subprocess.TimeoutExpired:
3162 pass
3163
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003164
Victor Stinner937ee9e2018-06-26 02:11:06 +02003165@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00003166class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00003167
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003168 def test_startupinfo(self):
3169 # startupinfo argument
3170 # We uses hardcoded constants, because we do not want to
3171 # depend on win32all.
3172 STARTF_USESHOWWINDOW = 1
3173 SW_MAXIMIZE = 3
3174 startupinfo = subprocess.STARTUPINFO()
3175 startupinfo.dwFlags = STARTF_USESHOWWINDOW
3176 startupinfo.wShowWindow = SW_MAXIMIZE
3177 # Since Python is a console process, it won't be affected
3178 # by wShowWindow, but the argument should be silently
3179 # ignored
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003180 subprocess.call(ZERO_RETURN_CMD,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003181 startupinfo=startupinfo)
3182
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05303183 def test_startupinfo_keywords(self):
3184 # startupinfo argument
3185 # We use hardcoded constants, because we do not want to
3186 # depend on win32all.
3187 STARTF_USERSHOWWINDOW = 1
3188 SW_MAXIMIZE = 3
3189 startupinfo = subprocess.STARTUPINFO(
3190 dwFlags=STARTF_USERSHOWWINDOW,
3191 wShowWindow=SW_MAXIMIZE
3192 )
3193 # Since Python is a console process, it won't be affected
3194 # by wShowWindow, but the argument should be silently
3195 # ignored
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003196 subprocess.call(ZERO_RETURN_CMD,
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05303197 startupinfo=startupinfo)
3198
Victor Stinner483422f2018-07-05 22:54:17 +02003199 def test_startupinfo_copy(self):
3200 # bpo-34044: Popen must not modify input STARTUPINFO structure
3201 startupinfo = subprocess.STARTUPINFO()
3202 startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
3203 startupinfo.wShowWindow = subprocess.SW_HIDE
3204
3205 # Call Popen() twice with the same startupinfo object to make sure
3206 # that it's not modified
3207 for _ in range(2):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003208 cmd = ZERO_RETURN_CMD
Victor Stinner483422f2018-07-05 22:54:17 +02003209 with open(os.devnull, 'w') as null:
3210 proc = subprocess.Popen(cmd,
3211 stdout=null,
3212 stderr=subprocess.STDOUT,
3213 startupinfo=startupinfo)
3214 with proc:
3215 proc.communicate()
3216 self.assertEqual(proc.returncode, 0)
3217
3218 self.assertEqual(startupinfo.dwFlags,
3219 subprocess.STARTF_USESHOWWINDOW)
3220 self.assertIsNone(startupinfo.hStdInput)
3221 self.assertIsNone(startupinfo.hStdOutput)
3222 self.assertIsNone(startupinfo.hStdError)
3223 self.assertEqual(startupinfo.wShowWindow, subprocess.SW_HIDE)
3224 self.assertEqual(startupinfo.lpAttributeList, {"handle_list": []})
3225
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003226 def test_creationflags(self):
3227 # creationflags argument
3228 CREATE_NEW_CONSOLE = 16
3229 sys.stderr.write(" a DOS box should flash briefly ...\n")
3230 subprocess.call(sys.executable +
3231 ' -c "import time; time.sleep(0.25)"',
3232 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003233
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003234 def test_invalid_args(self):
3235 # invalid arguments should raise ValueError
3236 self.assertRaises(ValueError, subprocess.call,
3237 [sys.executable, "-c",
3238 "import sys; sys.exit(47)"],
3239 preexec_fn=lambda: 1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003240
Oren Milman0b3a87e2017-09-14 22:30:28 +03003241 @support.cpython_only
3242 def test_issue31471(self):
3243 # There shouldn't be an assertion failure in Popen() in case the env
3244 # argument has a bad keys() method.
3245 class BadEnv(dict):
3246 keys = None
3247 with self.assertRaises(TypeError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003248 subprocess.Popen(ZERO_RETURN_CMD, env=BadEnv())
Oren Milman0b3a87e2017-09-14 22:30:28 +03003249
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003250 def test_close_fds(self):
3251 # close file descriptors
3252 rc = subprocess.call([sys.executable, "-c",
3253 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003254 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003255 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003256
Segev Finerb2a60832017-12-18 11:28:19 +02003257 def test_close_fds_with_stdio(self):
3258 import msvcrt
3259
3260 fds = os.pipe()
3261 self.addCleanup(os.close, fds[0])
3262 self.addCleanup(os.close, fds[1])
3263
3264 handles = []
3265 for fd in fds:
3266 os.set_inheritable(fd, True)
3267 handles.append(msvcrt.get_osfhandle(fd))
3268
3269 p = subprocess.Popen([sys.executable, "-c",
3270 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3271 stdout=subprocess.PIPE, close_fds=False)
3272 stdout, stderr = p.communicate()
3273 self.assertEqual(p.returncode, 0)
3274 int(stdout.strip()) # Check that stdout is an integer
3275
3276 p = subprocess.Popen([sys.executable, "-c",
3277 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3278 stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
3279 stdout, stderr = p.communicate()
3280 self.assertEqual(p.returncode, 1)
3281 self.assertIn(b"OSError", stderr)
3282
3283 # The same as the previous call, but with an empty handle_list
3284 handle_list = []
3285 startupinfo = subprocess.STARTUPINFO()
3286 startupinfo.lpAttributeList = {"handle_list": handle_list}
3287 p = subprocess.Popen([sys.executable, "-c",
3288 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3289 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3290 startupinfo=startupinfo, close_fds=True)
3291 stdout, stderr = p.communicate()
3292 self.assertEqual(p.returncode, 1)
3293 self.assertIn(b"OSError", stderr)
3294
3295 # Check for a warning due to using handle_list and close_fds=False
Hai Shi0c4f0f32020-06-30 21:46:31 +08003296 with warnings_helper.check_warnings((".*overriding close_fds",
3297 RuntimeWarning)):
Segev Finerb2a60832017-12-18 11:28:19 +02003298 startupinfo = subprocess.STARTUPINFO()
3299 startupinfo.lpAttributeList = {"handle_list": handles[:]}
3300 p = subprocess.Popen([sys.executable, "-c",
3301 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3302 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3303 startupinfo=startupinfo, close_fds=False)
3304 stdout, stderr = p.communicate()
3305 self.assertEqual(p.returncode, 0)
3306
3307 def test_empty_attribute_list(self):
3308 startupinfo = subprocess.STARTUPINFO()
3309 startupinfo.lpAttributeList = {}
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003310 subprocess.call(ZERO_RETURN_CMD,
Segev Finerb2a60832017-12-18 11:28:19 +02003311 startupinfo=startupinfo)
3312
3313 def test_empty_handle_list(self):
3314 startupinfo = subprocess.STARTUPINFO()
3315 startupinfo.lpAttributeList = {"handle_list": []}
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003316 subprocess.call(ZERO_RETURN_CMD,
Segev Finerb2a60832017-12-18 11:28:19 +02003317 startupinfo=startupinfo)
3318
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003319 def test_shell_sequence(self):
3320 # Run command through the shell (sequence)
3321 newenv = os.environ.copy()
3322 newenv["FRUIT"] = "physalis"
3323 p = subprocess.Popen(["set"], shell=1,
3324 stdout=subprocess.PIPE,
3325 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003326 with p:
3327 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00003328
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003329 def test_shell_string(self):
3330 # Run command through the shell (string)
3331 newenv = os.environ.copy()
3332 newenv["FRUIT"] = "physalis"
3333 p = subprocess.Popen("set", shell=1,
3334 stdout=subprocess.PIPE,
3335 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003336 with p:
3337 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003338
Steve Dower050acae2016-09-06 20:16:17 -07003339 def test_shell_encodings(self):
3340 # Run command through the shell (string)
3341 for enc in ['ansi', 'oem']:
3342 newenv = os.environ.copy()
3343 newenv["FRUIT"] = "physalis"
3344 p = subprocess.Popen("set", shell=1,
3345 stdout=subprocess.PIPE,
3346 env=newenv,
3347 encoding=enc)
3348 with p:
3349 self.assertIn("physalis", p.stdout.read(), enc)
3350
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003351 def test_call_string(self):
3352 # call() function with string argument on Windows
3353 rc = subprocess.call(sys.executable +
3354 ' -c "import sys; sys.exit(47)"')
3355 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003356
Florent Xicluna4886d242010-03-08 13:27:26 +00003357 def _kill_process(self, method, *args):
3358 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00003359 p = subprocess.Popen([sys.executable, "-c", """if 1:
3360 import sys, time
3361 sys.stdout.write('x\\n')
3362 sys.stdout.flush()
3363 time.sleep(30)
3364 """],
3365 stdin=subprocess.PIPE,
3366 stdout=subprocess.PIPE,
3367 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003368 with p:
3369 # Wait for the interpreter to be completely initialized before
3370 # sending any signal.
3371 p.stdout.read(1)
3372 getattr(p, method)(*args)
3373 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01003374 self.assertEqual(stderr, b'')
Victor Stinner7438c612016-05-20 12:43:15 +02003375 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00003376 self.assertNotEqual(returncode, 0)
3377
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003378 def _kill_dead_process(self, method, *args):
3379 p = subprocess.Popen([sys.executable, "-c", """if 1:
3380 import sys, time
3381 sys.stdout.write('x\\n')
3382 sys.stdout.flush()
3383 sys.exit(42)
3384 """],
3385 stdin=subprocess.PIPE,
3386 stdout=subprocess.PIPE,
3387 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003388 with p:
3389 # Wait for the interpreter to be completely initialized before
3390 # sending any signal.
3391 p.stdout.read(1)
3392 # The process should end after this
3393 time.sleep(1)
3394 # This shouldn't raise even though the child is now dead
3395 getattr(p, method)(*args)
3396 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01003397 self.assertEqual(stderr, b'')
Victor Stinner7438c612016-05-20 12:43:15 +02003398 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003399 self.assertEqual(rc, 42)
3400
Florent Xicluna4886d242010-03-08 13:27:26 +00003401 def test_send_signal(self):
3402 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00003403
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003404 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003405 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00003406
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003407 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003408 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00003409
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003410 def test_send_signal_dead(self):
3411 self._kill_dead_process('send_signal', signal.SIGTERM)
3412
3413 def test_kill_dead(self):
3414 self._kill_dead_process('kill')
3415
3416 def test_terminate_dead(self):
3417 self._kill_dead_process('terminate')
3418
Martin Panter23172bd2016-04-16 11:28:10 +00003419class MiscTests(unittest.TestCase):
Gregory P. Smithf4d644f2018-01-29 21:27:39 -08003420
3421 class RecordingPopen(subprocess.Popen):
3422 """A Popen that saves a reference to each instance for testing."""
3423 instances_created = []
3424
3425 def __init__(self, *args, **kwargs):
3426 super().__init__(*args, **kwargs)
3427 self.instances_created.append(self)
3428
3429 @mock.patch.object(subprocess.Popen, "_communicate")
3430 def _test_keyboardinterrupt_no_kill(self, popener, mock__communicate,
3431 **kwargs):
3432 """Fake a SIGINT happening during Popen._communicate() and ._wait().
3433
3434 This avoids the need to actually try and get test environments to send
3435 and receive signals reliably across platforms. The net effect of a ^C
3436 happening during a blocking subprocess execution which we want to clean
3437 up from is a KeyboardInterrupt coming out of communicate() or wait().
3438 """
3439
3440 mock__communicate.side_effect = KeyboardInterrupt
3441 try:
3442 with mock.patch.object(subprocess.Popen, "_wait") as mock__wait:
3443 # We patch out _wait() as no signal was involved so the
3444 # child process isn't actually going to exit rapidly.
3445 mock__wait.side_effect = KeyboardInterrupt
3446 with mock.patch.object(subprocess, "Popen",
3447 self.RecordingPopen):
3448 with self.assertRaises(KeyboardInterrupt):
3449 popener([sys.executable, "-c",
3450 "import time\ntime.sleep(9)\nimport sys\n"
3451 "sys.stderr.write('\\n!runaway child!\\n')"],
3452 stdout=subprocess.DEVNULL, **kwargs)
3453 for call in mock__wait.call_args_list[1:]:
3454 self.assertNotEqual(
3455 call, mock.call(timeout=None),
3456 "no open-ended wait() after the first allowed: "
3457 f"{mock__wait.call_args_list}")
3458 sigint_calls = []
3459 for call in mock__wait.call_args_list:
3460 if call == mock.call(timeout=0.25): # from Popen.__init__
3461 sigint_calls.append(call)
3462 self.assertLessEqual(mock__wait.call_count, 2,
3463 msg=mock__wait.call_args_list)
3464 self.assertEqual(len(sigint_calls), 1,
3465 msg=mock__wait.call_args_list)
3466 finally:
3467 # cleanup the forgotten (due to our mocks) child process
3468 process = self.RecordingPopen.instances_created.pop()
3469 process.kill()
3470 process.wait()
3471 self.assertEqual([], self.RecordingPopen.instances_created)
3472
3473 def test_call_keyboardinterrupt_no_kill(self):
3474 self._test_keyboardinterrupt_no_kill(subprocess.call, timeout=6.282)
3475
3476 def test_run_keyboardinterrupt_no_kill(self):
3477 self._test_keyboardinterrupt_no_kill(subprocess.run, timeout=6.282)
3478
3479 def test_context_manager_keyboardinterrupt_no_kill(self):
3480 def popen_via_context_manager(*args, **kwargs):
3481 with subprocess.Popen(*args, **kwargs) as unused_process:
3482 raise KeyboardInterrupt # Test how __exit__ handles ^C.
3483 self._test_keyboardinterrupt_no_kill(popen_via_context_manager)
3484
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003485 def test_getoutput(self):
3486 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
3487 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
3488 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00003489
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003490 # we use mkdtemp in the next line to create an empty directory
3491 # under our exclusive control; from that, we can invent a pathname
3492 # that we _know_ won't exist. This is guaranteed to fail.
3493 dir = None
3494 try:
3495 dir = tempfile.mkdtemp()
3496 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00003497 status, output = subprocess.getstatusoutput(
Victor Stinner937ee9e2018-06-26 02:11:06 +02003498 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003499 self.assertNotEqual(status, 0)
3500 finally:
3501 if dir is not None:
3502 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00003503
Gregory P. Smithace55862015-04-07 15:57:54 -07003504 def test__all__(self):
3505 """Ensure that __all__ is populated properly."""
Patrick McLean2b2ead72019-09-12 10:15:44 -07003506 intentionally_excluded = {"list2cmdline", "Handle", "pwd", "grp"}
Gregory P. Smithace55862015-04-07 15:57:54 -07003507 exported = set(subprocess.__all__)
3508 possible_exports = set()
3509 import types
3510 for name, value in subprocess.__dict__.items():
3511 if name.startswith('_'):
3512 continue
3513 if isinstance(value, (types.ModuleType,)):
3514 continue
3515 possible_exports.add(name)
3516 self.assertEqual(exported, possible_exports - intentionally_excluded)
3517
3518
Martin Panter23172bd2016-04-16 11:28:10 +00003519@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
3520 "Test needs selectors.PollSelector")
3521class ProcessTestCaseNoPoll(ProcessTestCase):
3522 def setUp(self):
3523 self.orig_selector = subprocess._PopenSelector
3524 subprocess._PopenSelector = selectors.SelectSelector
3525 ProcessTestCase.setUp(self)
3526
3527 def tearDown(self):
3528 subprocess._PopenSelector = self.orig_selector
3529 ProcessTestCase.tearDown(self)
3530
Gregory P. Smithd06fa472009-07-04 02:46:54 +00003531
Victor Stinner937ee9e2018-06-26 02:11:06 +02003532@unittest.skipUnless(mswindows, "Windows-specific tests")
Tim Golden126c2962010-08-11 14:20:40 +00003533class CommandsWithSpaces (BaseTestCase):
3534
3535 def setUp(self):
3536 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03003537 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00003538 self.fname = fname.lower ()
3539 os.write(f, b"import sys;"
3540 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
3541 )
3542 os.close(f)
3543
3544 def tearDown(self):
3545 os.remove(self.fname)
3546 super().tearDown()
3547
3548 def with_spaces(self, *args, **kwargs):
3549 kwargs['stdout'] = subprocess.PIPE
3550 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02003551 with p:
3552 self.assertEqual(
3553 p.stdout.read ().decode("mbcs"),
3554 "2 [%r, 'ab cd']" % self.fname
3555 )
Tim Golden126c2962010-08-11 14:20:40 +00003556
3557 def test_shell_string_with_spaces(self):
3558 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003559 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3560 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003561
3562 def test_shell_sequence_with_spaces(self):
3563 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003564 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003565
3566 def test_noshell_string_with_spaces(self):
3567 # call() function with string argument with spaces on Windows
3568 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3569 "ab cd"))
3570
3571 def test_noshell_sequence_with_spaces(self):
3572 # call() function with sequence argument with spaces on Windows
3573 self.with_spaces([sys.executable, self.fname, "ab cd"])
3574
Brian Curtin79cdb662010-12-03 02:46:02 +00003575
Georg Brandla86b2622012-02-20 21:34:57 +01003576class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00003577
3578 def test_pipe(self):
3579 with subprocess.Popen([sys.executable, "-c",
3580 "import sys;"
3581 "sys.stdout.write('stdout');"
3582 "sys.stderr.write('stderr');"],
3583 stdout=subprocess.PIPE,
3584 stderr=subprocess.PIPE) as proc:
3585 self.assertEqual(proc.stdout.read(), b"stdout")
Victor Stinner6cac1132019-12-08 08:38:16 +01003586 self.assertEqual(proc.stderr.read(), b"stderr")
Brian Curtin79cdb662010-12-03 02:46:02 +00003587
3588 self.assertTrue(proc.stdout.closed)
3589 self.assertTrue(proc.stderr.closed)
3590
3591 def test_returncode(self):
3592 with subprocess.Popen([sys.executable, "-c",
3593 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07003594 pass
3595 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00003596 self.assertEqual(proc.returncode, 100)
3597
3598 def test_communicate_stdin(self):
3599 with subprocess.Popen([sys.executable, "-c",
3600 "import sys;"
3601 "sys.exit(sys.stdin.read() == 'context')"],
3602 stdin=subprocess.PIPE) as proc:
3603 proc.communicate(b"context")
3604 self.assertEqual(proc.returncode, 1)
3605
3606 def test_invalid_args(self):
Victor Stinnerb31206a2018-01-25 19:06:05 +01003607 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02003608 with subprocess.Popen(NONEXISTING_CMD,
Brian Curtin79cdb662010-12-03 02:46:02 +00003609 stdout=subprocess.PIPE,
3610 stderr=subprocess.PIPE) as proc:
3611 pass
3612
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003613 def test_broken_pipe_cleanup(self):
3614 """Broken pipe error should not prevent wait() (Issue 21619)"""
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003615 proc = subprocess.Popen(ZERO_RETURN_CMD,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003616 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003617 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003618 proc = proc.__enter__()
3619 # Prepare to send enough data to overflow any OS pipe buffering and
3620 # guarantee a broken pipe error. Data is held in BufferedWriter
3621 # buffer until closed.
3622 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003623 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003624 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02003625 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003626 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003627 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003628
Brian Curtin79cdb662010-12-03 02:46:02 +00003629
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003630if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04003631 unittest.main()