blob: 70b54f4155a9a5c06dc5c3558eaffa39ce535b46 [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
Ruben Vorderman23c0fb82020-10-20 01:30:02 +020042try:
43 import fcntl
44except:
45 fcntl = None
46
Steve Dower22d06982016-09-06 19:38:15 -070047if support.PGO:
48 raise unittest.SkipTest("test is not helpful for PGO")
49
Victor Stinner937ee9e2018-06-26 02:11:06 +020050mswindows = (sys.platform == "win32")
51
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000052#
53# Depends on the following external programs: Python
54#
55
Victor Stinner937ee9e2018-06-26 02:11:06 +020056if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000057 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
58 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000059else:
60 SETBINARY = ''
61
Victor Stinner9a83f652017-08-21 23:51:31 +020062NONEXISTING_CMD = ('nonexisting_i_hope',)
Victor Stinnerb31206a2018-01-25 19:06:05 +010063# Ignore errors that indicate the command was not found
64NONEXISTING_ERRORS = (FileNotFoundError, NotADirectoryError, PermissionError)
Victor Stinner9a83f652017-08-21 23:51:31 +020065
Gregory P. Smith67b93f82019-10-12 16:35:53 -070066ZERO_RETURN_CMD = (sys.executable, '-c', 'pass')
67
68
69def setUpModule():
70 shell_true = shutil.which('true')
Pablo Galindo46113e02019-10-13 02:40:24 +010071 if shell_true is None:
72 return
Gregory P. Smith67b93f82019-10-12 16:35:53 -070073 if (os.access(shell_true, os.X_OK) and
74 subprocess.run([shell_true]).returncode == 0):
75 global ZERO_RETURN_CMD
76 ZERO_RETURN_CMD = (shell_true,) # Faster than Python startup.
77
Florent Xiclunab1e94e82010-02-27 22:12:37 +000078
Florent Xiclunac049d872010-03-27 22:47:23 +000079class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000080 def setUp(self):
81 # Try to minimize the number of children we have so this test
82 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000083 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000084
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000085 def tearDown(self):
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +030086 if not mswindows:
87 # subprocess._active is not used on Windows and is set to None.
88 for inst in subprocess._active:
89 inst.wait()
90 subprocess._cleanup()
91 self.assertFalse(
92 subprocess._active, "subprocess._active not empty"
93 )
Victor Stinnercc42c122017-07-28 18:00:22 +020094 self.doCleanups()
95 support.reap_children()
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000096
Florent Xiclunac049d872010-03-27 22:47:23 +000097
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080098class PopenTestException(Exception):
99 pass
100
101
102class PopenExecuteChildRaises(subprocess.Popen):
103 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
104 _execute_child fails.
105 """
106 def _execute_child(self, *args, **kwargs):
107 raise PopenTestException("Forced Exception for Test")
108
109
Florent Xiclunac049d872010-03-27 22:47:23 +0000110class ProcessTestCase(BaseTestCase):
111
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700112 def test_io_buffered_by_default(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700113 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700114 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
115 stderr=subprocess.PIPE)
116 try:
117 self.assertIsInstance(p.stdin, io.BufferedIOBase)
118 self.assertIsInstance(p.stdout, io.BufferedIOBase)
119 self.assertIsInstance(p.stderr, io.BufferedIOBase)
120 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700121 p.stdin.close()
122 p.stdout.close()
123 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700124 p.wait()
125
126 def test_io_unbuffered_works(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700127 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700128 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
129 stderr=subprocess.PIPE, bufsize=0)
130 try:
131 self.assertIsInstance(p.stdin, io.RawIOBase)
132 self.assertIsInstance(p.stdout, io.RawIOBase)
133 self.assertIsInstance(p.stderr, io.RawIOBase)
134 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700135 p.stdin.close()
136 p.stdout.close()
137 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700138 p.wait()
139
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000140 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000141 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000142 rc = subprocess.call([sys.executable, "-c",
143 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000144 self.assertEqual(rc, 47)
145
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400146 def test_call_timeout(self):
147 # call() function with timeout argument; we want to test that the child
148 # process gets killed when the timeout expires. If the child isn't
149 # killed, this call will deadlock since subprocess.call waits for the
150 # child.
151 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
152 [sys.executable, "-c", "while True: pass"],
153 timeout=0.1)
154
Peter Astrand454f7672005-01-01 09:36:35 +0000155 def test_check_call_zero(self):
156 # check_call() function with zero return code
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700157 rc = subprocess.check_call(ZERO_RETURN_CMD)
Peter Astrand454f7672005-01-01 09:36:35 +0000158 self.assertEqual(rc, 0)
159
160 def test_check_call_nonzero(self):
161 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000162 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000163 subprocess.check_call([sys.executable, "-c",
164 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000165 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000166
Georg Brandlf9734072008-12-07 15:30:06 +0000167 def test_check_output(self):
168 # check_output() function with zero return code
169 output = subprocess.check_output(
170 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000171 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000172
173 def test_check_output_nonzero(self):
174 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000175 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000176 subprocess.check_output(
177 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000178 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000179
180 def test_check_output_stderr(self):
181 # check_output() function stderr redirected to stdout
182 output = subprocess.check_output(
183 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
184 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000185 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000186
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300187 def test_check_output_stdin_arg(self):
188 # check_output() can be called with stdin set to a file
189 tf = tempfile.TemporaryFile()
190 self.addCleanup(tf.close)
191 tf.write(b'pear')
192 tf.seek(0)
193 output = subprocess.check_output(
194 [sys.executable, "-c",
195 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
196 stdin=tf)
197 self.assertIn(b'PEAR', output)
198
199 def test_check_output_input_arg(self):
200 # check_output() can be called with input set to a string
201 output = subprocess.check_output(
202 [sys.executable, "-c",
203 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
204 input=b'pear')
205 self.assertIn(b'PEAR', output)
206
Gregory P. Smith64abf372020-12-24 20:57:21 -0800207 def test_check_output_input_none(self):
208 """input=None has a legacy meaning of input='' on check_output."""
209 output = subprocess.check_output(
210 [sys.executable, "-c",
211 "import sys; print('XX' if sys.stdin.read() else '')"],
212 input=None)
213 self.assertNotIn(b'XX', output)
214
215 def test_check_output_input_none_text(self):
216 output = subprocess.check_output(
217 [sys.executable, "-c",
218 "import sys; print('XX' if sys.stdin.read() else '')"],
219 input=None, text=True)
220 self.assertNotIn('XX', output)
221
222 def test_check_output_input_none_universal_newlines(self):
223 output = subprocess.check_output(
224 [sys.executable, "-c",
225 "import sys; print('XX' if sys.stdin.read() else '')"],
226 input=None, universal_newlines=True)
227 self.assertNotIn('XX', output)
228
Georg Brandlf9734072008-12-07 15:30:06 +0000229 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300230 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000231 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000232 output = subprocess.check_output(
233 [sys.executable, "-c", "print('will not be run')"],
234 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000235 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000236 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000237
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300238 def test_check_output_stdin_with_input_arg(self):
239 # check_output() refuses to accept 'stdin' with 'input'
240 tf = tempfile.TemporaryFile()
241 self.addCleanup(tf.close)
242 tf.write(b'pear')
243 tf.seek(0)
244 with self.assertRaises(ValueError) as c:
245 output = subprocess.check_output(
246 [sys.executable, "-c", "print('will not be run')"],
247 stdin=tf, input=b'hare')
248 self.fail("Expected ValueError when stdin and input args supplied.")
249 self.assertIn('stdin', c.exception.args[0])
250 self.assertIn('input', c.exception.args[0])
251
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400252 def test_check_output_timeout(self):
253 # check_output() function with timeout arg
254 with self.assertRaises(subprocess.TimeoutExpired) as c:
255 output = subprocess.check_output(
256 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200257 "import sys, time\n"
258 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400259 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200260 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400261 # Some heavily loaded buildbots (sparc Debian 3.x) require
262 # this much time to start and print.
263 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400264 self.fail("Expected TimeoutExpired.")
265 self.assertEqual(c.exception.output, b'BDFL')
266
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000267 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000268 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000269 newenv = os.environ.copy()
270 newenv["FRUIT"] = "banana"
271 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000272 'import sys, os;'
273 'sys.exit(os.getenv("FRUIT")=="banana")'],
274 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000275 self.assertEqual(rc, 1)
276
Victor Stinner87b9bc32011-06-01 00:57:47 +0200277 def test_invalid_args(self):
278 # Popen() called with invalid arguments should raise TypeError
279 # but Popen.__del__ should not complain (issue #12085)
280 with support.captured_stderr() as s:
281 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
282 argcount = subprocess.Popen.__init__.__code__.co_argcount
283 too_many_args = [0] * (argcount + 1)
284 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
285 self.assertEqual(s.getvalue(), '')
286
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000287 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000288 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000289 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000290 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000291 self.addCleanup(p.stdout.close)
292 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000293 p.wait()
294 self.assertEqual(p.stdin, None)
295
296 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200297 # .stdout is None when not redirected, and the child's stdout will
298 # be inherited from the parent. In order to test this we run a
299 # subprocess in a subprocess:
300 # this_test
301 # \-- subprocess created by this test (parent)
302 # \-- subprocess created by the parent subprocess (child)
303 # The parent doesn't specify stdout, so the child will use the
304 # parent's stdout. This test checks that the message printed by the
305 # child goes to the parent stdout. The parent also checks that the
306 # child's stdout is None. See #11963.
307 code = ('import sys; from subprocess import Popen, PIPE;'
308 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
309 ' stdin=PIPE, stderr=PIPE);'
310 'p.wait(); assert p.stdout is None;')
311 p = subprocess.Popen([sys.executable, "-c", code],
312 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
313 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000314 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200315 out, err = p.communicate()
316 self.assertEqual(p.returncode, 0, err)
317 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000318
319 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000320 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000321 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000322 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000323 self.addCleanup(p.stdout.close)
324 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000325 p.wait()
326 self.assertEqual(p.stderr, None)
327
Chris Jerdonek776cb192012-10-08 15:56:43 -0700328 def _assert_python(self, pre_args, **kwargs):
329 # We include sys.exit() to prevent the test runner from hanging
330 # whenever python is found.
331 args = pre_args + ["import sys; sys.exit(47)"]
332 p = subprocess.Popen(args, **kwargs)
333 p.wait()
334 self.assertEqual(47, p.returncode)
335
336 def test_executable(self):
337 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700338 #
339 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
340 # determine where its standard library is, so we need the directory
341 # of args[0] to be valid for the Popen() call to Python to succeed.
342 # See also issue #16170 and issue #7774.
343 doesnotexist = os.path.join(os.path.dirname(sys.executable),
344 "doesnotexist")
345 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700346
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300347 def test_bytes_executable(self):
348 doesnotexist = os.path.join(os.path.dirname(sys.executable),
349 "doesnotexist")
350 self._assert_python([doesnotexist, "-c"],
351 executable=os.fsencode(sys.executable))
352
353 def test_pathlike_executable(self):
354 doesnotexist = os.path.join(os.path.dirname(sys.executable),
355 "doesnotexist")
356 self._assert_python([doesnotexist, "-c"],
357 executable=FakePath(sys.executable))
358
Chris Jerdonek776cb192012-10-08 15:56:43 -0700359 def test_executable_takes_precedence(self):
360 # Check that the executable argument takes precedence over args[0].
361 #
362 # Verify first that the call succeeds without the executable arg.
363 pre_args = [sys.executable, "-c"]
364 self._assert_python(pre_args)
Victor Stinnerb31206a2018-01-25 19:06:05 +0100365 self.assertRaises(NONEXISTING_ERRORS,
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +0100366 self._assert_python, pre_args,
Victor Stinnerb31206a2018-01-25 19:06:05 +0100367 executable=NONEXISTING_CMD[0])
Chris Jerdonek776cb192012-10-08 15:56:43 -0700368
Victor Stinner937ee9e2018-06-26 02:11:06 +0200369 @unittest.skipIf(mswindows, "executable argument replaces shell")
Chris Jerdonek776cb192012-10-08 15:56:43 -0700370 def test_executable_replaces_shell(self):
371 # Check that the executable argument replaces the default shell
372 # when shell=True.
373 self._assert_python([], executable=sys.executable, shell=True)
374
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300375 @unittest.skipIf(mswindows, "executable argument replaces shell")
376 def test_bytes_executable_replaces_shell(self):
377 self._assert_python([], executable=os.fsencode(sys.executable),
378 shell=True)
379
380 @unittest.skipIf(mswindows, "executable argument replaces shell")
381 def test_pathlike_executable_replaces_shell(self):
382 self._assert_python([], executable=FakePath(sys.executable),
383 shell=True)
384
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700385 # For use in the test_cwd* tests below.
386 def _normalize_cwd(self, cwd):
387 # Normalize an expected cwd (for Tru64 support).
388 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
389 # strings. See bug #1063571.
Hai Shi0c4f0f32020-06-30 21:46:31 +0800390 with os_helper.change_cwd(cwd):
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300391 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700392
393 # For use in the test_cwd* tests below.
394 def _split_python_path(self):
395 # Return normalized (python_dir, python_base).
396 python_path = os.path.realpath(sys.executable)
397 return os.path.split(python_path)
398
399 # For use in the test_cwd* tests below.
400 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
401 # Invoke Python via Popen, and assert that (1) the call succeeds,
402 # and that (2) the current working directory of the child process
403 # matches *expected_cwd*.
404 p = subprocess.Popen([python_arg, "-c",
405 "import os, sys; "
Serhiy Storchakab1a87302020-07-26 10:21:39 +0300406 "buf = sys.stdout.buffer; "
407 "buf.write(os.getcwd().encode()); "
408 "buf.flush(); "
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700409 "sys.exit(47)"],
410 stdout=subprocess.PIPE,
411 **kwargs)
412 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000413 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700414 self.assertEqual(47, p.returncode)
415 normcase = os.path.normcase
416 self.assertEqual(normcase(expected_cwd),
Serhiy Storchakab1a87302020-07-26 10:21:39 +0300417 normcase(p.stdout.read().decode()))
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700418
419 def test_cwd(self):
420 # Check that cwd changes the cwd for the child process.
421 temp_dir = tempfile.gettempdir()
422 temp_dir = self._normalize_cwd(temp_dir)
423 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
424
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300425 def test_cwd_with_bytes(self):
426 temp_dir = tempfile.gettempdir()
427 temp_dir = self._normalize_cwd(temp_dir)
428 self._assert_cwd(temp_dir, sys.executable, cwd=os.fsencode(temp_dir))
429
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530430 def test_cwd_with_pathlike(self):
431 temp_dir = tempfile.gettempdir()
432 temp_dir = self._normalize_cwd(temp_dir)
Serhiy Storchakab21d1552018-03-02 11:53:51 +0200433 self._assert_cwd(temp_dir, sys.executable, cwd=FakePath(temp_dir))
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530434
Victor Stinner937ee9e2018-06-26 02:11:06 +0200435 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700436 def test_cwd_with_relative_arg(self):
437 # Check that Popen looks for args[0] relative to cwd if args[0]
438 # is relative.
439 python_dir, python_base = self._split_python_path()
440 rel_python = os.path.join(os.curdir, python_base)
Hai Shi0c4f0f32020-06-30 21:46:31 +0800441 with os_helper.temp_cwd() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700442 # Before calling with the correct cwd, confirm that the call fails
443 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700444 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700445 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700446 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700447 [rel_python], cwd=wrong_dir)
448 python_dir = self._normalize_cwd(python_dir)
449 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
450
Victor Stinner937ee9e2018-06-26 02:11:06 +0200451 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700452 def test_cwd_with_relative_executable(self):
453 # Check that Popen looks for executable relative to cwd if executable
454 # is relative (and that executable takes precedence over args[0]).
455 python_dir, python_base = self._split_python_path()
456 rel_python = os.path.join(os.curdir, python_base)
457 doesntexist = "somethingyoudonthave"
Hai Shi0c4f0f32020-06-30 21:46:31 +0800458 with os_helper.temp_cwd() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700459 # Before calling with the correct cwd, confirm that the call fails
460 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700461 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700462 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700463 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700464 [doesntexist], executable=rel_python,
465 cwd=wrong_dir)
466 python_dir = self._normalize_cwd(python_dir)
467 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
468 cwd=python_dir)
469
470 def test_cwd_with_absolute_arg(self):
471 # Check that Popen can find the executable when the cwd is wrong
472 # if args[0] is an absolute path.
473 python_dir, python_base = self._split_python_path()
474 abs_python = os.path.join(python_dir, python_base)
475 rel_python = os.path.join(os.curdir, python_base)
Hai Shi0c4f0f32020-06-30 21:46:31 +0800476 with os_helper.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700477 # Before calling with an absolute path, confirm that using a
478 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700479 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700480 [rel_python], cwd=wrong_dir)
481 wrong_dir = self._normalize_cwd(wrong_dir)
482 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
483
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100484 @unittest.skipIf(sys.base_prefix != sys.prefix,
485 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000486 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700487 python_dir, python_base = self._split_python_path()
488 python_dir = self._normalize_cwd(python_dir)
489 self._assert_cwd(python_dir, "somethingyoudonthave",
490 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000491
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100492 @unittest.skipIf(sys.base_prefix != sys.prefix,
493 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000494 @unittest.skipIf(sysconfig.is_python_build(),
495 "need an installed Python. See #7774")
496 def test_executable_without_cwd(self):
497 # For a normal installation, it should work without 'cwd'
498 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700499 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
500 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000501
502 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000503 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000504 p = subprocess.Popen([sys.executable, "-c",
505 'import sys; sys.exit(sys.stdin.read() == "pear")'],
506 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000507 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000508 p.stdin.close()
509 p.wait()
510 self.assertEqual(p.returncode, 1)
511
512 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000513 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000514 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000515 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000516 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000517 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000518 os.lseek(d, 0, 0)
519 p = subprocess.Popen([sys.executable, "-c",
520 'import sys; sys.exit(sys.stdin.read() == "pear")'],
521 stdin=d)
522 p.wait()
523 self.assertEqual(p.returncode, 1)
524
525 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000526 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000527 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000528 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000529 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000530 tf.seek(0)
531 p = subprocess.Popen([sys.executable, "-c",
532 'import sys; sys.exit(sys.stdin.read() == "pear")'],
533 stdin=tf)
534 p.wait()
535 self.assertEqual(p.returncode, 1)
536
537 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000538 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000539 p = subprocess.Popen([sys.executable, "-c",
540 'import sys; sys.stdout.write("orange")'],
541 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200542 with p:
543 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000544
545 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000546 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000547 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000548 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000549 d = tf.fileno()
550 p = subprocess.Popen([sys.executable, "-c",
551 'import sys; sys.stdout.write("orange")'],
552 stdout=d)
553 p.wait()
554 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000555 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000556
557 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000558 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000559 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000560 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000561 p = subprocess.Popen([sys.executable, "-c",
562 'import sys; sys.stdout.write("orange")'],
563 stdout=tf)
564 p.wait()
565 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000566 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000567
568 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000569 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000570 p = subprocess.Popen([sys.executable, "-c",
571 'import sys; sys.stderr.write("strawberry")'],
572 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200573 with p:
Victor Stinner6cac1132019-12-08 08:38:16 +0100574 self.assertEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000575
576 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000577 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000578 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000579 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000580 d = tf.fileno()
581 p = subprocess.Popen([sys.executable, "-c",
582 'import sys; sys.stderr.write("strawberry")'],
583 stderr=d)
584 p.wait()
585 os.lseek(d, 0, 0)
Victor Stinner6cac1132019-12-08 08:38:16 +0100586 self.assertEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000587
588 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000589 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000590 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000591 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000592 p = subprocess.Popen([sys.executable, "-c",
593 'import sys; sys.stderr.write("strawberry")'],
594 stderr=tf)
595 p.wait()
596 tf.seek(0)
Victor Stinner6cac1132019-12-08 08:38:16 +0100597 self.assertEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000598
Martin Panterc7635892016-05-13 01:54:44 +0000599 def test_stderr_redirect_with_no_stdout_redirect(self):
600 # test stderr=STDOUT while stdout=None (not set)
601
602 # - grandchild prints to stderr
603 # - child redirects grandchild's stderr to its stdout
604 # - the parent should get grandchild's stderr in child's stdout
605 p = subprocess.Popen([sys.executable, "-c",
606 'import sys, subprocess;'
607 'rc = subprocess.call([sys.executable, "-c",'
608 ' "import sys;"'
609 ' "sys.stderr.write(\'42\')"],'
610 ' stderr=subprocess.STDOUT);'
611 'sys.exit(rc)'],
612 stdout=subprocess.PIPE,
613 stderr=subprocess.PIPE)
614 stdout, stderr = p.communicate()
615 #NOTE: stdout should get stderr from grandchild
Victor Stinner6cac1132019-12-08 08:38:16 +0100616 self.assertEqual(stdout, b'42')
617 self.assertEqual(stderr, b'') # should be empty
Martin Panterc7635892016-05-13 01:54:44 +0000618 self.assertEqual(p.returncode, 0)
619
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000620 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000621 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000622 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000623 'import sys;'
624 'sys.stdout.write("apple");'
625 'sys.stdout.flush();'
626 'sys.stderr.write("orange")'],
627 stdout=subprocess.PIPE,
628 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200629 with p:
Victor Stinner6cac1132019-12-08 08:38:16 +0100630 self.assertEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000631
632 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000633 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000634 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000635 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000636 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000637 'import sys;'
638 'sys.stdout.write("apple");'
639 'sys.stdout.flush();'
640 'sys.stderr.write("orange")'],
641 stdout=tf,
642 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000643 p.wait()
644 tf.seek(0)
Victor Stinner6cac1132019-12-08 08:38:16 +0100645 self.assertEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000646
Thomas Wouters89f507f2006-12-13 04:49:30 +0000647 def test_stdout_filedes_of_stdout(self):
648 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200649 # To avoid printing the text on stdout, we do something similar to
650 # test_stdout_none (see above). The parent subprocess calls the child
651 # subprocess passing stdout=1, and this test uses stdout=PIPE in
652 # order to capture and check the output of the parent. See #11963.
653 code = ('import sys, subprocess; '
654 'rc = subprocess.call([sys.executable, "-c", '
655 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
656 'b\'test with stdout=1\'))"], stdout=1); '
657 'assert rc == 18')
658 p = subprocess.Popen([sys.executable, "-c", code],
659 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
660 self.addCleanup(p.stdout.close)
661 self.addCleanup(p.stderr.close)
662 out, err = p.communicate()
663 self.assertEqual(p.returncode, 0, err)
664 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000665
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200666 def test_stdout_devnull(self):
667 p = subprocess.Popen([sys.executable, "-c",
668 'for i in range(10240):'
669 'print("x" * 1024)'],
670 stdout=subprocess.DEVNULL)
671 p.wait()
672 self.assertEqual(p.stdout, None)
673
674 def test_stderr_devnull(self):
675 p = subprocess.Popen([sys.executable, "-c",
676 'import sys\n'
677 'for i in range(10240):'
678 'sys.stderr.write("x" * 1024)'],
679 stderr=subprocess.DEVNULL)
680 p.wait()
681 self.assertEqual(p.stderr, None)
682
683 def test_stdin_devnull(self):
684 p = subprocess.Popen([sys.executable, "-c",
685 'import sys;'
686 'sys.stdin.read(1)'],
687 stdin=subprocess.DEVNULL)
688 p.wait()
689 self.assertEqual(p.stdin, None)
690
Gregory P. Smith786addd2020-10-20 17:37:20 -0700691 @unittest.skipUnless(fcntl and hasattr(fcntl, 'F_GETPIPE_SZ'),
692 'fcntl.F_GETPIPE_SZ required for test.')
Ruben Vorderman23c0fb82020-10-20 01:30:02 +0200693 def test_pipesizes(self):
Gregory P. Smith786addd2020-10-20 17:37:20 -0700694 test_pipe_r, test_pipe_w = os.pipe()
695 try:
696 # Get the default pipesize with F_GETPIPE_SZ
697 pipesize_default = fcntl.fcntl(test_pipe_w, fcntl.F_GETPIPE_SZ)
698 finally:
699 os.close(test_pipe_r)
700 os.close(test_pipe_w)
701 pipesize = pipesize_default // 2
702 if pipesize < 512: # the POSIX minimum
703 raise unittest.SkitTest(
704 'default pipesize too small to perform test.')
705 p = subprocess.Popen(
706 [sys.executable, "-c",
707 'import sys; sys.stdin.read(); sys.stdout.write("out"); '
708 'sys.stderr.write("error!")'],
709 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
710 stderr=subprocess.PIPE, pipesize=pipesize)
711 try:
Ruben Vorderman23c0fb82020-10-20 01:30:02 +0200712 for fifo in [p.stdin, p.stdout, p.stderr]:
713 self.assertEqual(
Gregory P. Smith786addd2020-10-20 17:37:20 -0700714 fcntl.fcntl(fifo.fileno(), fcntl.F_GETPIPE_SZ),
715 pipesize)
716 # Windows pipe size can be acquired via GetNamedPipeInfoFunction
717 # https://docs.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-getnamedpipeinfo
718 # However, this function is not yet in _winapi.
719 p.stdin.write(b"pear")
720 p.stdin.close()
721 finally:
722 p.kill()
723 p.wait()
724
725 @unittest.skipUnless(fcntl and hasattr(fcntl, 'F_GETPIPE_SZ'),
726 'fcntl.F_GETPIPE_SZ required for test.')
727 def test_pipesize_default(self):
728 p = subprocess.Popen(
729 [sys.executable, "-c",
730 'import sys; sys.stdin.read(); sys.stdout.write("out"); '
731 'sys.stderr.write("error!")'],
732 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
733 stderr=subprocess.PIPE, pipesize=-1)
734 try:
735 fp_r, fp_w = os.pipe()
736 try:
737 default_pipesize = fcntl.fcntl(fp_w, fcntl.F_GETPIPE_SZ)
738 for fifo in [p.stdin, p.stdout, p.stderr]:
739 self.assertEqual(
740 fcntl.fcntl(fifo.fileno(), fcntl.F_GETPIPE_SZ),
741 default_pipesize)
742 finally:
743 os.close(fp_r)
744 os.close(fp_w)
745 # On other platforms we cannot test the pipe size (yet). But above
746 # code using pipesize=-1 should not crash.
747 p.stdin.close()
748 finally:
749 p.kill()
750 p.wait()
Ruben Vorderman23c0fb82020-10-20 01:30:02 +0200751
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000752 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000753 newenv = os.environ.copy()
754 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200755 with subprocess.Popen([sys.executable, "-c",
756 'import sys,os;'
757 'sys.stdout.write(os.getenv("FRUIT"))'],
758 stdout=subprocess.PIPE,
759 env=newenv) as p:
760 stdout, stderr = p.communicate()
761 self.assertEqual(stdout, b"orange")
762
Victor Stinner62d51182011-06-23 01:02:25 +0200763 # Windows requires at least the SYSTEMROOT environment variable to start
764 # Python
765 @unittest.skipIf(sys.platform == 'win32',
766 'cannot test an empty env on Windows')
Gregory P. Smithb3512482017-05-30 14:40:37 -0700767 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
768 'The Python shared library cannot be loaded '
769 'with an empty environment.')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200770 def test_empty_env(self):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700771 """Verify that env={} is as empty as possible."""
772
Gregory P. Smith85aba232017-05-30 16:21:47 -0700773 def is_env_var_to_ignore(n):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700774 """Determine if an environment variable is under our control."""
775 # This excludes some __CF_* and VERSIONER_* keys MacOS insists
776 # on adding even when the environment in exec is empty.
777 # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist.
Gregory P. Smith85aba232017-05-30 16:21:47 -0700778 return ('VERSIONER' in n or '__CF' in n or # MacOS
Nick Coghlan6ea41862017-06-11 13:16:15 +1000779 n == 'LD_PRELOAD' or n.startswith('SANDBOX') or # Gentoo
780 n == 'LC_CTYPE') # Locale coercion triggered
Gregory P. Smithb3512482017-05-30 14:40:37 -0700781
Victor Stinnerf1512a22011-06-21 17:18:38 +0200782 with subprocess.Popen([sys.executable, "-c",
Gregory P. Smithb3512482017-05-30 14:40:37 -0700783 'import os; print(list(os.environ.keys()))'],
784 stdout=subprocess.PIPE, env={}) as p:
Victor Stinnerf1512a22011-06-21 17:18:38 +0200785 stdout, stderr = p.communicate()
Gregory P. Smithb3512482017-05-30 14:40:37 -0700786 child_env_names = eval(stdout.strip())
787 self.assertIsInstance(child_env_names, list)
788 child_env_names = [k for k in child_env_names
789 if not is_env_var_to_ignore(k)]
790 self.assertEqual(child_env_names, [])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000791
Serhiy Storchakad174d242017-06-23 19:39:27 +0300792 def test_invalid_cmd(self):
793 # null character in the command name
794 cmd = sys.executable + '\0'
795 with self.assertRaises(ValueError):
796 subprocess.Popen([cmd, "-c", "pass"])
797
798 # null character in the command argument
799 with self.assertRaises(ValueError):
800 subprocess.Popen([sys.executable, "-c", "pass#\0"])
801
802 def test_invalid_env(self):
Ville Skyttä49b27342017-08-03 09:00:59 +0300803 # null character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300804 newenv = os.environ.copy()
805 newenv["FRUIT\0VEGETABLE"] = "cabbage"
806 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700807 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300808
Ville Skyttä49b27342017-08-03 09:00:59 +0300809 # null character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300810 newenv = os.environ.copy()
811 newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
812 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700813 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300814
Ville Skyttä49b27342017-08-03 09:00:59 +0300815 # equal character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300816 newenv = os.environ.copy()
817 newenv["FRUIT=ORANGE"] = "lemon"
818 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700819 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300820
Ville Skyttä49b27342017-08-03 09:00:59 +0300821 # equal character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300822 newenv = os.environ.copy()
823 newenv["FRUIT"] = "orange=lemon"
824 with subprocess.Popen([sys.executable, "-c",
825 'import sys, os;'
826 'sys.stdout.write(os.getenv("FRUIT"))'],
827 stdout=subprocess.PIPE,
828 env=newenv) as p:
829 stdout, stderr = p.communicate()
830 self.assertEqual(stdout, b"orange=lemon")
831
Peter Astrandcbac93c2005-03-03 20:24:28 +0000832 def test_communicate_stdin(self):
833 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000834 'import sys;'
835 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000836 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000837 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000838 self.assertEqual(p.returncode, 1)
839
840 def test_communicate_stdout(self):
841 p = subprocess.Popen([sys.executable, "-c",
842 'import sys; sys.stdout.write("pineapple")'],
843 stdout=subprocess.PIPE)
844 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000845 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000846 self.assertEqual(stderr, None)
847
848 def test_communicate_stderr(self):
849 p = subprocess.Popen([sys.executable, "-c",
850 'import sys; sys.stderr.write("pineapple")'],
851 stderr=subprocess.PIPE)
852 (stdout, stderr) = p.communicate()
853 self.assertEqual(stdout, None)
Victor Stinner6cac1132019-12-08 08:38:16 +0100854 self.assertEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000855
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000856 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000857 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000858 'import sys,os;'
859 'sys.stderr.write("pineapple");'
860 'sys.stdout.write(sys.stdin.read())'],
861 stdin=subprocess.PIPE,
862 stdout=subprocess.PIPE,
863 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000864 self.addCleanup(p.stdout.close)
865 self.addCleanup(p.stderr.close)
866 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000867 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000868 self.assertEqual(stdout, b"banana")
Victor Stinner6cac1132019-12-08 08:38:16 +0100869 self.assertEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000870
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400871 def test_communicate_timeout(self):
872 p = subprocess.Popen([sys.executable, "-c",
873 'import sys,os,time;'
874 'sys.stderr.write("pineapple\\n");'
875 'time.sleep(1);'
876 'sys.stderr.write("pear\\n");'
877 'sys.stdout.write(sys.stdin.read())'],
878 universal_newlines=True,
879 stdin=subprocess.PIPE,
880 stdout=subprocess.PIPE,
881 stderr=subprocess.PIPE)
882 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
883 timeout=0.3)
884 # Make sure we can keep waiting for it, and that we get the whole output
885 # after it completes.
886 (stdout, stderr) = p.communicate()
887 self.assertEqual(stdout, "banana")
Victor Stinner6cac1132019-12-08 08:38:16 +0100888 self.assertEqual(stderr.encode(), b"pineapple\npear\n")
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400889
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700890 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200891 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400892 p = subprocess.Popen([sys.executable, "-c",
893 'import sys,os,time;'
894 'sys.stdout.write("a" * (64 * 1024));'
895 'time.sleep(0.2);'
896 'sys.stdout.write("a" * (64 * 1024));'
897 'time.sleep(0.2);'
898 'sys.stdout.write("a" * (64 * 1024));'
899 'time.sleep(0.2);'
900 'sys.stdout.write("a" * (64 * 1024));'],
901 stdout=subprocess.PIPE)
902 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
903 (stdout, _) = p.communicate()
904 self.assertEqual(len(stdout), 4 * 64 * 1024)
905
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000906 # Test for the fd leak reported in http://bugs.python.org/issue2791.
907 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000908 for stdin_pipe in (False, True):
909 for stdout_pipe in (False, True):
910 for stderr_pipe in (False, True):
911 options = {}
912 if stdin_pipe:
913 options['stdin'] = subprocess.PIPE
914 if stdout_pipe:
915 options['stdout'] = subprocess.PIPE
916 if stderr_pipe:
917 options['stderr'] = subprocess.PIPE
918 if not options:
919 continue
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700920 p = subprocess.Popen(ZERO_RETURN_CMD, **options)
Victor Stinner667d4b52010-12-25 22:40:32 +0000921 p.communicate()
922 if p.stdin is not None:
923 self.assertTrue(p.stdin.closed)
924 if p.stdout is not None:
925 self.assertTrue(p.stdout.closed)
926 if p.stderr is not None:
927 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000928
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000929 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000930 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000931 p = subprocess.Popen([sys.executable, "-c",
932 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000933 (stdout, stderr) = p.communicate()
934 self.assertEqual(stdout, None)
935 self.assertEqual(stderr, None)
936
937 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000938 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000939 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000940 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000941 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000942 os.close(x)
943 os.close(y)
944 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000945 'import sys,os;'
946 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200947 'sys.stderr.write("x" * %d);'
948 'sys.stdout.write(sys.stdin.read())' %
949 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000950 stdin=subprocess.PIPE,
951 stdout=subprocess.PIPE,
952 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000953 self.addCleanup(p.stdout.close)
954 self.addCleanup(p.stderr.close)
955 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200956 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000957 (stdout, stderr) = p.communicate(string_to_write)
958 self.assertEqual(stdout, string_to_write)
959
960 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000961 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000962 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000963 'import sys,os;'
964 'sys.stdout.write(sys.stdin.read())'],
965 stdin=subprocess.PIPE,
966 stdout=subprocess.PIPE,
967 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000968 self.addCleanup(p.stdout.close)
969 self.addCleanup(p.stderr.close)
970 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000971 p.stdin.write(b"banana")
972 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000973 self.assertEqual(stdout, b"bananasplit")
Victor Stinner6cac1132019-12-08 08:38:16 +0100974 self.assertEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000975
andyclegg7fed7bd2017-10-23 03:01:19 +0100976 def test_universal_newlines_and_text(self):
977 args = [
978 sys.executable, "-c",
979 'import sys,os;' + SETBINARY +
980 'buf = sys.stdout.buffer;'
981 'buf.write(sys.stdin.readline().encode());'
982 'buf.flush();'
983 'buf.write(b"line2\\n");'
984 'buf.flush();'
985 'buf.write(sys.stdin.read().encode());'
986 'buf.flush();'
987 'buf.write(b"line4\\n");'
988 'buf.flush();'
989 'buf.write(b"line5\\r\\n");'
990 'buf.flush();'
991 'buf.write(b"line6\\r");'
992 'buf.flush();'
993 'buf.write(b"\\nline7");'
994 'buf.flush();'
995 'buf.write(b"\\nline8");']
996
997 for extra_kwarg in ('universal_newlines', 'text'):
998 p = subprocess.Popen(args, **{'stdin': subprocess.PIPE,
999 'stdout': subprocess.PIPE,
1000 extra_kwarg: True})
1001 with p:
1002 p.stdin.write("line1\n")
1003 p.stdin.flush()
1004 self.assertEqual(p.stdout.readline(), "line1\n")
1005 p.stdin.write("line3\n")
1006 p.stdin.close()
1007 self.addCleanup(p.stdout.close)
1008 self.assertEqual(p.stdout.readline(),
1009 "line2\n")
1010 self.assertEqual(p.stdout.read(6),
1011 "line3\n")
1012 self.assertEqual(p.stdout.read(),
1013 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001014
1015 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +00001016 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001017 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +00001018 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +02001019 'buf = sys.stdout.buffer;'
1020 'buf.write(b"line2\\n");'
1021 'buf.flush();'
1022 'buf.write(b"line4\\n");'
1023 'buf.flush();'
1024 'buf.write(b"line5\\r\\n");'
1025 'buf.flush();'
1026 'buf.write(b"line6\\r");'
1027 'buf.flush();'
1028 'buf.write(b"\\nline7");'
1029 'buf.flush();'
1030 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +02001031 stderr=subprocess.PIPE,
1032 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +00001033 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +00001034 self.addCleanup(p.stdout.close)
1035 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001036 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +02001037 self.assertEqual(stdout,
1038 "line2\nline4\nline5\nline6\nline7\nline8")
1039
1040 def test_universal_newlines_communicate_stdin(self):
1041 # universal newlines through communicate(), with only stdin
1042 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +03001043 'import sys,os;' + SETBINARY + textwrap.dedent('''
1044 s = sys.stdin.readline()
1045 assert s == "line1\\n", repr(s)
1046 s = sys.stdin.read()
1047 assert s == "line3\\n", repr(s)
1048 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +02001049 stdin=subprocess.PIPE,
1050 universal_newlines=1)
1051 (stdout, stderr) = p.communicate("line1\nline3\n")
1052 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001053
Andrew Svetlovf3765072012-08-14 18:35:17 +03001054 def test_universal_newlines_communicate_input_none(self):
1055 # Test communicate(input=None) with universal newlines.
1056 #
1057 # We set stdout to PIPE because, as of this writing, a different
1058 # code path is tested when the number of pipes is zero or one.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001059 p = subprocess.Popen(ZERO_RETURN_CMD,
Andrew Svetlovf3765072012-08-14 18:35:17 +03001060 stdin=subprocess.PIPE,
1061 stdout=subprocess.PIPE,
1062 universal_newlines=True)
1063 p.communicate()
1064 self.assertEqual(p.returncode, 0)
1065
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001066 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +03001067 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001068 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +03001069 'import sys,os;' + SETBINARY + textwrap.dedent('''
1070 s = sys.stdin.buffer.readline()
1071 sys.stdout.buffer.write(s)
1072 sys.stdout.buffer.write(b"line2\\r")
1073 sys.stderr.buffer.write(b"eline2\\n")
1074 s = sys.stdin.buffer.read()
1075 sys.stdout.buffer.write(s)
1076 sys.stdout.buffer.write(b"line4\\n")
1077 sys.stdout.buffer.write(b"line5\\r\\n")
1078 sys.stderr.buffer.write(b"eline6\\r")
1079 sys.stderr.buffer.write(b"eline7\\r\\nz")
1080 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001081 stdin=subprocess.PIPE,
1082 stderr=subprocess.PIPE,
1083 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +03001084 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001085 self.addCleanup(p.stdout.close)
1086 self.addCleanup(p.stderr.close)
1087 (stdout, stderr) = p.communicate("line1\nline3\n")
1088 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +03001089 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001090 # Python debug build push something like "[42442 refs]\n"
1091 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +03001092 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001093
Andrew Svetlov82860712012-08-19 22:13:41 +03001094 def test_universal_newlines_communicate_encodings(self):
1095 # Check that universal newlines mode works for various encodings,
1096 # in particular for encodings in the UTF-16 and UTF-32 families.
1097 # See issue #15595.
1098 #
1099 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
1100 # without, and UTF-16 and UTF-32.
1101 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +03001102 code = ("import sys; "
1103 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
1104 encoding)
1105 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -07001106 # We set stdin to be non-None because, as of this writing,
1107 # a different code path is used when the number of pipes is
1108 # zero or one.
1109 popen = subprocess.Popen(args,
1110 stdin=subprocess.PIPE,
1111 stdout=subprocess.PIPE,
1112 encoding=encoding)
1113 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +03001114 self.assertEqual(stdout, '1\n2\n3\n4')
1115
Steve Dower050acae2016-09-06 20:16:17 -07001116 def test_communicate_errors(self):
1117 for errors, expected in [
1118 ('ignore', ''),
1119 ('replace', '\ufffd\ufffd'),
1120 ('surrogateescape', '\udc80\udc80'),
1121 ('backslashreplace', '\\x80\\x80'),
1122 ]:
1123 code = ("import sys; "
1124 r"sys.stdout.buffer.write(b'[\x80\x80]')")
1125 args = [sys.executable, '-c', code]
1126 # We set stdin to be non-None because, as of this writing,
1127 # a different code path is used when the number of pipes is
1128 # zero or one.
1129 popen = subprocess.Popen(args,
1130 stdin=subprocess.PIPE,
1131 stdout=subprocess.PIPE,
1132 encoding='utf-8',
1133 errors=errors)
1134 stdout, stderr = popen.communicate(input='')
1135 self.assertEqual(stdout, '[{}]'.format(expected))
1136
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001137 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +00001138 # Make sure we leak no resources
Victor Stinner937ee9e2018-06-26 02:11:06 +02001139 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +00001140 max_handles = 1026 # too much for most UNIX systems
1141 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +00001142 max_handles = 2050 # too much for (at least some) Windows setups
1143 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001144 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +00001145 try:
1146 for i in range(max_handles):
1147 try:
Hai Shi0c4f0f32020-06-30 21:46:31 +08001148 tmpfile = os.path.join(tmpdir, os_helper.TESTFN)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001149 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +00001150 except OSError as e:
1151 if e.errno != errno.EMFILE:
1152 raise
1153 break
1154 else:
1155 self.skipTest("failed to reach the file descriptor limit "
1156 "(tried %d)" % max_handles)
1157 # Close a couple of them (should be enough for a subprocess)
1158 for i in range(10):
1159 os.close(handles.pop())
1160 # Loop creating some subprocesses. If one of them leaks some fds,
1161 # the next loop iteration will fail by reaching the max fd limit.
1162 for i in range(15):
1163 p = subprocess.Popen([sys.executable, "-c",
1164 "import sys;"
1165 "sys.stdout.write(sys.stdin.read())"],
1166 stdin=subprocess.PIPE,
1167 stdout=subprocess.PIPE,
1168 stderr=subprocess.PIPE)
1169 data = p.communicate(b"lime")[0]
1170 self.assertEqual(data, b"lime")
1171 finally:
1172 for h in handles:
1173 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001174 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001175
1176 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001177 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
1178 '"a b c" d e')
1179 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
1180 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +00001181 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
1182 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001183 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
1184 'a\\\\\\b "de fg" h')
1185 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
1186 'a\\\\\\"b c d')
1187 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
1188 '"a\\\\b c" d e')
1189 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
1190 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001191 self.assertEqual(subprocess.list2cmdline(['ab', '']),
1192 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001193
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001194 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001195 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +02001196 "import os; os.read(0, 1)"],
1197 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001198 self.addCleanup(p.stdin.close)
1199 self.assertIsNone(p.poll())
1200 os.write(p.stdin.fileno(), b'A')
1201 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001202 # Subsequent invocations should just return the returncode
1203 self.assertEqual(p.poll(), 0)
1204
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001205 def test_wait(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001206 p = subprocess.Popen(ZERO_RETURN_CMD)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001207 self.assertEqual(p.wait(), 0)
1208 # Subsequent invocations should just return the returncode
1209 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001210
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001211 def test_wait_timeout(self):
1212 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001213 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001214 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001215 p.wait(timeout=0.0001)
1216 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Victor Stinner0d63bac2019-12-11 11:30:03 +01001217 self.assertEqual(p.wait(timeout=support.SHORT_TIMEOUT), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001218
Peter Astrand738131d2004-11-30 21:04:45 +00001219 def test_invalid_bufsize(self):
1220 # an invalid type of the bufsize argument should raise
1221 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001222 with self.assertRaises(TypeError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001223 subprocess.Popen(ZERO_RETURN_CMD, "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001224
Guido van Rossum46a05a72007-06-07 21:56:45 +00001225 def test_bufsize_is_none(self):
1226 # bufsize=None should be the same as bufsize=0.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001227 p = subprocess.Popen(ZERO_RETURN_CMD, None)
Guido van Rossum46a05a72007-06-07 21:56:45 +00001228 self.assertEqual(p.wait(), 0)
1229 # Again with keyword arg
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001230 p = subprocess.Popen(ZERO_RETURN_CMD, bufsize=None)
Guido van Rossum46a05a72007-06-07 21:56:45 +00001231 self.assertEqual(p.wait(), 0)
1232
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001233 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1234 # subprocess may deadlock with bufsize=1, see issue #21332
1235 with subprocess.Popen([sys.executable, "-c", "import sys;"
1236 "sys.stdout.write(sys.stdin.readline());"
1237 "sys.stdout.flush()"],
1238 stdin=subprocess.PIPE,
1239 stdout=subprocess.PIPE,
1240 stderr=subprocess.DEVNULL,
1241 bufsize=1,
1242 universal_newlines=universal_newlines) as p:
1243 p.stdin.write(line) # expect that it flushes the line in text mode
1244 os.close(p.stdin.fileno()) # close it without flushing the buffer
1245 read_line = p.stdout.readline()
Segev Finer4d385172017-08-18 16:18:13 +03001246 with support.SuppressCrashReport():
1247 try:
1248 p.stdin.close()
1249 except OSError:
1250 pass
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001251 p.stdin = None
1252 self.assertEqual(p.returncode, 0)
1253 self.assertEqual(read_line, expected)
1254
1255 def test_bufsize_equal_one_text_mode(self):
1256 # line is flushed in text mode with bufsize=1.
1257 # we should get the full line in return
1258 line = "line\n"
1259 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1260
1261 def test_bufsize_equal_one_binary_mode(self):
1262 # line is not flushed in binary mode with bufsize=1.
1263 # we should get empty response
1264 line = b'line' + os.linesep.encode() # assume ascii-based locale
Alexey Izbysheva2670562018-10-20 03:22:31 +03001265 with self.assertWarnsRegex(RuntimeWarning, 'line buffering'):
1266 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001267
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001268 def test_leaking_fds_on_error(self):
1269 # see bug #5179: Popen leaks file descriptors to PIPEs if
1270 # the child fails to execute; this will eventually exhaust
1271 # the maximum number of open fds. 1024 seems a very common
1272 # value for that limit, but Windows has 2048, so we loop
1273 # 1024 times (each call leaked two fds).
1274 for i in range(1024):
Victor Stinnerb31206a2018-01-25 19:06:05 +01001275 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02001276 subprocess.Popen(NONEXISTING_CMD,
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001277 stdout=subprocess.PIPE,
1278 stderr=subprocess.PIPE)
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001279
Victor Stinner9a83f652017-08-21 23:51:31 +02001280 def test_nonexisting_with_pipes(self):
1281 # bpo-30121: Popen with pipes must close properly pipes on error.
1282 # Previously, os.close() was called with a Windows handle which is not
1283 # a valid file descriptor.
1284 #
1285 # Run the test in a subprocess to control how the CRT reports errors
1286 # and to get stderr content.
1287 try:
1288 import msvcrt
1289 msvcrt.CrtSetReportMode
1290 except (AttributeError, ImportError):
1291 self.skipTest("need msvcrt.CrtSetReportMode")
1292
1293 code = textwrap.dedent(f"""
1294 import msvcrt
1295 import subprocess
1296
1297 cmd = {NONEXISTING_CMD!r}
1298
1299 for report_type in [msvcrt.CRT_WARN,
1300 msvcrt.CRT_ERROR,
1301 msvcrt.CRT_ASSERT]:
1302 msvcrt.CrtSetReportMode(report_type, msvcrt.CRTDBG_MODE_FILE)
1303 msvcrt.CrtSetReportFile(report_type, msvcrt.CRTDBG_FILE_STDERR)
1304
1305 try:
Zachary Ware55376462018-02-19 14:02:38 -06001306 subprocess.Popen(cmd,
Victor Stinner9a83f652017-08-21 23:51:31 +02001307 stdout=subprocess.PIPE,
1308 stderr=subprocess.PIPE)
1309 except OSError:
1310 pass
1311 """)
1312 cmd = [sys.executable, "-c", code]
1313 proc = subprocess.Popen(cmd,
1314 stderr=subprocess.PIPE,
1315 universal_newlines=True)
1316 with proc:
1317 stderr = proc.communicate()[1]
1318 self.assertEqual(stderr, "")
1319 self.assertEqual(proc.returncode, 0)
1320
Antoine Pitroua8392712013-08-30 23:38:13 +02001321 def test_double_close_on_error(self):
1322 # Issue #18851
1323 fds = []
1324 def open_fds():
1325 for i in range(20):
1326 fds.extend(os.pipe())
1327 time.sleep(0.001)
1328 t = threading.Thread(target=open_fds)
1329 t.start()
1330 try:
1331 with self.assertRaises(EnvironmentError):
Victor Stinner9a83f652017-08-21 23:51:31 +02001332 subprocess.Popen(NONEXISTING_CMD,
Antoine Pitroua8392712013-08-30 23:38:13 +02001333 stdin=subprocess.PIPE,
1334 stdout=subprocess.PIPE,
1335 stderr=subprocess.PIPE)
1336 finally:
1337 t.join()
1338 exc = None
1339 for fd in fds:
1340 # If a double close occurred, some of those fds will
1341 # already have been closed by mistake, and os.close()
1342 # here will raise.
1343 try:
1344 os.close(fd)
1345 except OSError as e:
1346 exc = e
1347 if exc is not None:
1348 raise exc
1349
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001350 def test_threadsafe_wait(self):
1351 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1352 proc = subprocess.Popen([sys.executable, '-c',
1353 'import time; time.sleep(12)'])
1354 self.assertEqual(proc.returncode, None)
1355 results = []
1356
1357 def kill_proc_timer_thread():
1358 results.append(('thread-start-poll-result', proc.poll()))
1359 # terminate it from the thread and wait for the result.
1360 proc.kill()
1361 proc.wait()
1362 results.append(('thread-after-kill-and-wait', proc.returncode))
1363 # this wait should be a no-op given the above.
1364 proc.wait()
1365 results.append(('thread-after-second-wait', proc.returncode))
1366
1367 # This is a timing sensitive test, the failure mode is
1368 # triggered when both the main thread and this thread are in
1369 # the wait() call at once. The delay here is to allow the
1370 # main thread to most likely be blocked in its wait() call.
1371 t = threading.Timer(0.2, kill_proc_timer_thread)
1372 t.start()
1373
Victor Stinner937ee9e2018-06-26 02:11:06 +02001374 if mswindows:
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001375 expected_errorcode = 1
1376 else:
1377 # Should be -9 because of the proc.kill() from the thread.
1378 expected_errorcode = -9
1379
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001380 # Wait for the process to finish; the thread should kill it
1381 # long before it finishes on its own. Supplying a timeout
1382 # triggers a different code path for better coverage.
Victor Stinner0d63bac2019-12-11 11:30:03 +01001383 proc.wait(timeout=support.SHORT_TIMEOUT)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001384 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001385 msg="unexpected result in wait from main thread")
1386
1387 # This should be a no-op with no change in returncode.
1388 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001389 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001390 msg="unexpected result in second main wait.")
1391
1392 t.join()
1393 # Ensure that all of the thread results are as expected.
1394 # When a race condition occurs in wait(), the returncode could
1395 # be set by the wrong thread that doesn't actually have it
1396 # leading to an incorrect value.
1397 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001398 ('thread-after-kill-and-wait', expected_errorcode),
1399 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001400 results)
1401
Victor Stinnerb3693582010-05-21 20:13:12 +00001402 def test_issue8780(self):
1403 # Ensure that stdout is inherited from the parent
1404 # if stdout=PIPE is not used
1405 code = ';'.join((
1406 'import subprocess, sys',
1407 'retcode = subprocess.call('
1408 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1409 'assert retcode == 0'))
1410 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001411 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001412
Tim Goldenaf5ac392010-08-06 13:03:56 +00001413 def test_handles_closed_on_exception(self):
1414 # If CreateProcess exits with an error, ensure the
1415 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001416 ifhandle, ifname = tempfile.mkstemp()
1417 ofhandle, ofname = tempfile.mkstemp()
1418 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001419 try:
1420 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1421 stderr=efhandle)
1422 except OSError:
1423 os.close(ifhandle)
1424 os.remove(ifname)
1425 os.close(ofhandle)
1426 os.remove(ofname)
1427 os.close(efhandle)
1428 os.remove(efname)
1429 self.assertFalse(os.path.exists(ifname))
1430 self.assertFalse(os.path.exists(ofname))
1431 self.assertFalse(os.path.exists(efname))
1432
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001433 def test_communicate_epipe(self):
1434 # Issue 10963: communicate() should hide EPIPE
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001435 p = subprocess.Popen(ZERO_RETURN_CMD,
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001436 stdin=subprocess.PIPE,
1437 stdout=subprocess.PIPE,
1438 stderr=subprocess.PIPE)
1439 self.addCleanup(p.stdout.close)
1440 self.addCleanup(p.stderr.close)
1441 self.addCleanup(p.stdin.close)
1442 p.communicate(b"x" * 2**20)
1443
Andrey Doroschenko645005e2019-11-17 17:08:31 +03001444 def test_repr(self):
1445 # Run a command that waits for user input, to check the repr() of
1446 # a Proc object while and after the sub-process runs.
1447 code = 'import sys; input(); sys.exit(57)'
1448 cmd = [sys.executable, '-c', code]
1449 result = "<Popen: returncode: {}"
1450
1451 with subprocess.Popen(
1452 cmd, stdin=subprocess.PIPE, universal_newlines=True) as proc:
1453 self.assertIsNone(proc.returncode)
1454 self.assertTrue(
1455 repr(proc).startswith(result.format(proc.returncode)) and
1456 repr(proc).endswith('>')
1457 )
1458
1459 proc.communicate(input='exit...\n')
1460 proc.wait()
1461
1462 self.assertIsNotNone(proc.returncode)
1463 self.assertTrue(
1464 repr(proc).startswith(result.format(proc.returncode)) and
1465 repr(proc).endswith('>')
1466 )
1467
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001468 def test_communicate_epipe_only_stdin(self):
1469 # Issue 10963: communicate() should hide EPIPE
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001470 p = subprocess.Popen(ZERO_RETURN_CMD,
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001471 stdin=subprocess.PIPE)
1472 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001473 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001474 p.communicate(b"x" * 2**20)
1475
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001476 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1477 "Requires signal.SIGUSR1")
1478 @unittest.skipUnless(hasattr(os, 'kill'),
1479 "Requires os.kill")
1480 @unittest.skipUnless(hasattr(os, 'getppid'),
1481 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001482 def test_communicate_eintr(self):
1483 # Issue #12493: communicate() should handle EINTR
1484 def handler(signum, frame):
1485 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001486 old_handler = signal.signal(signal.SIGUSR1, handler)
1487 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001488
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001489 args = [sys.executable, "-c",
1490 'import os, signal;'
1491 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001492 for stream in ('stdout', 'stderr'):
1493 kw = {stream: subprocess.PIPE}
1494 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001495 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001496 process.communicate()
1497
Tim Peterse718f612004-10-12 21:51:32 +00001498
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001499 # This test is Linux-ish specific for simplicity to at least have
1500 # some coverage. It is not a platform specific bug.
1501 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1502 "Linux specific")
1503 def test_failed_child_execute_fd_leak(self):
1504 """Test for the fork() failure fd leak reported in issue16327."""
1505 fd_directory = '/proc/%d/fd' % os.getpid()
1506 fds_before_popen = os.listdir(fd_directory)
1507 with self.assertRaises(PopenTestException):
1508 PopenExecuteChildRaises(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001509 ZERO_RETURN_CMD, stdin=subprocess.PIPE,
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001510 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1511
1512 # NOTE: This test doesn't verify that the real _execute_child
1513 # does not close the file descriptors itself on the way out
1514 # during an exception. Code inspection has confirmed that.
1515
1516 fds_after_exception = os.listdir(fd_directory)
1517 self.assertEqual(fds_before_popen, fds_after_exception)
1518
Victor Stinner937ee9e2018-06-26 02:11:06 +02001519 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001520 def test_file_not_found_includes_filename(self):
1521 with self.assertRaises(FileNotFoundError) as c:
1522 subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args'])
1523 self.assertEqual(c.exception.filename, '/opt/nonexistent_binary')
1524
Victor Stinner937ee9e2018-06-26 02:11:06 +02001525 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001526 def test_file_not_found_with_bad_cwd(self):
1527 with self.assertRaises(FileNotFoundError) as c:
1528 subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory')
1529 self.assertEqual(c.exception.filename, '/some/nonexistent/directory')
1530
Batuhan Taşkaya4dc5a9d2019-12-30 19:02:04 +03001531 def test_class_getitems(self):
Guido van Rossum48b069a2020-04-07 09:50:06 -07001532 self.assertIsInstance(subprocess.Popen[bytes], types.GenericAlias)
1533 self.assertIsInstance(subprocess.CompletedProcess[str], types.GenericAlias)
Gregory P. Smith6e730002015-04-14 16:14:25 -07001534
1535class RunFuncTestCase(BaseTestCase):
1536 def run_python(self, code, **kwargs):
1537 """Run Python code in a subprocess using subprocess.run"""
1538 argv = [sys.executable, "-c", code]
1539 return subprocess.run(argv, **kwargs)
1540
1541 def test_returncode(self):
1542 # call() function with sequence argument
1543 cp = self.run_python("import sys; sys.exit(47)")
1544 self.assertEqual(cp.returncode, 47)
1545 with self.assertRaises(subprocess.CalledProcessError):
1546 cp.check_returncode()
1547
1548 def test_check(self):
1549 with self.assertRaises(subprocess.CalledProcessError) as c:
1550 self.run_python("import sys; sys.exit(47)", check=True)
1551 self.assertEqual(c.exception.returncode, 47)
1552
1553 def test_check_zero(self):
1554 # check_returncode shouldn't raise when returncode is zero
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001555 cp = subprocess.run(ZERO_RETURN_CMD, check=True)
Gregory P. Smith6e730002015-04-14 16:14:25 -07001556 self.assertEqual(cp.returncode, 0)
1557
1558 def test_timeout(self):
1559 # run() function with timeout argument; we want to test that the child
1560 # process gets killed when the timeout expires. If the child isn't
1561 # killed, this call will deadlock since subprocess.run waits for the
1562 # child.
1563 with self.assertRaises(subprocess.TimeoutExpired):
1564 self.run_python("while True: pass", timeout=0.0001)
1565
1566 def test_capture_stdout(self):
1567 # capture stdout with zero return code
1568 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1569 self.assertIn(b'BDFL', cp.stdout)
1570
1571 def test_capture_stderr(self):
1572 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1573 stderr=subprocess.PIPE)
1574 self.assertIn(b'BDFL', cp.stderr)
1575
1576 def test_check_output_stdin_arg(self):
1577 # run() can be called with stdin set to a file
1578 tf = tempfile.TemporaryFile()
1579 self.addCleanup(tf.close)
1580 tf.write(b'pear')
1581 tf.seek(0)
1582 cp = self.run_python(
1583 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1584 stdin=tf, stdout=subprocess.PIPE)
1585 self.assertIn(b'PEAR', cp.stdout)
1586
1587 def test_check_output_input_arg(self):
1588 # check_output() can be called with input set to a string
1589 cp = self.run_python(
1590 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1591 input=b'pear', stdout=subprocess.PIPE)
1592 self.assertIn(b'PEAR', cp.stdout)
1593
1594 def test_check_output_stdin_with_input_arg(self):
1595 # run() refuses to accept 'stdin' with 'input'
1596 tf = tempfile.TemporaryFile()
1597 self.addCleanup(tf.close)
1598 tf.write(b'pear')
1599 tf.seek(0)
1600 with self.assertRaises(ValueError,
1601 msg="Expected ValueError when stdin and input args supplied.") as c:
1602 output = self.run_python("print('will not be run')",
1603 stdin=tf, input=b'hare')
1604 self.assertIn('stdin', c.exception.args[0])
1605 self.assertIn('input', c.exception.args[0])
1606
1607 def test_check_output_timeout(self):
1608 with self.assertRaises(subprocess.TimeoutExpired) as c:
1609 cp = self.run_python((
1610 "import sys, time\n"
1611 "sys.stdout.write('BDFL')\n"
1612 "sys.stdout.flush()\n"
1613 "time.sleep(3600)"),
1614 # Some heavily loaded buildbots (sparc Debian 3.x) require
1615 # this much time to start and print.
1616 timeout=3, stdout=subprocess.PIPE)
1617 self.assertEqual(c.exception.output, b'BDFL')
1618 # output is aliased to stdout
1619 self.assertEqual(c.exception.stdout, b'BDFL')
1620
1621 def test_run_kwargs(self):
1622 newenv = os.environ.copy()
1623 newenv["FRUIT"] = "banana"
1624 cp = self.run_python(('import sys, os;'
1625 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1626 env=newenv)
1627 self.assertEqual(cp.returncode, 33)
1628
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001629 def test_run_with_pathlike_path(self):
1630 # bpo-31961: test run(pathlike_object)
1631 # the name of a command that can be run without
Min ho Kimc4cacc82019-07-31 08:16:13 +10001632 # any arguments that exit fast
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001633 prog = 'tree.com' if mswindows else 'ls'
1634 path = shutil.which(prog)
1635 if path is None:
1636 self.skipTest(f'{prog} required for this test')
1637 path = FakePath(path)
1638 res = subprocess.run(path, stdout=subprocess.DEVNULL)
1639 self.assertEqual(res.returncode, 0)
1640 with self.assertRaises(TypeError):
1641 subprocess.run(path, stdout=subprocess.DEVNULL, shell=True)
1642
1643 def test_run_with_bytes_path_and_arguments(self):
1644 # bpo-31961: test run([bytes_object, b'additional arguments'])
1645 path = os.fsencode(sys.executable)
1646 args = [path, '-c', b'import sys; sys.exit(57)']
1647 res = subprocess.run(args)
1648 self.assertEqual(res.returncode, 57)
1649
1650 def test_run_with_pathlike_path_and_arguments(self):
1651 # bpo-31961: test run([pathlike_object, 'additional arguments'])
1652 path = FakePath(sys.executable)
1653 args = [path, '-c', 'import sys; sys.exit(57)']
1654 res = subprocess.run(args)
1655 self.assertEqual(res.returncode, 57)
1656
Bo Baylesce0f33d2018-01-30 00:40:39 -06001657 def test_capture_output(self):
1658 cp = self.run_python(("import sys;"
1659 "sys.stdout.write('BDFL'); "
1660 "sys.stderr.write('FLUFL')"),
1661 capture_output=True)
1662 self.assertIn(b'BDFL', cp.stdout)
1663 self.assertIn(b'FLUFL', cp.stderr)
1664
1665 def test_stdout_with_capture_output_arg(self):
1666 # run() refuses to accept 'stdout' with 'capture_output'
1667 tf = tempfile.TemporaryFile()
1668 self.addCleanup(tf.close)
1669 with self.assertRaises(ValueError,
1670 msg=("Expected ValueError when stdout and capture_output "
1671 "args supplied.")) as c:
1672 output = self.run_python("print('will not be run')",
1673 capture_output=True, stdout=tf)
1674 self.assertIn('stdout', c.exception.args[0])
1675 self.assertIn('capture_output', c.exception.args[0])
1676
1677 def test_stderr_with_capture_output_arg(self):
1678 # run() refuses to accept 'stderr' with 'capture_output'
1679 tf = tempfile.TemporaryFile()
1680 self.addCleanup(tf.close)
1681 with self.assertRaises(ValueError,
1682 msg=("Expected ValueError when stderr and capture_output "
1683 "args supplied.")) as c:
1684 output = self.run_python("print('will not be run')",
1685 capture_output=True, stderr=tf)
1686 self.assertIn('stderr', c.exception.args[0])
1687 self.assertIn('capture_output', c.exception.args[0])
1688
Gregory P. Smith580d2782019-09-11 04:23:05 -05001689 # This test _might_ wind up a bit fragile on loaded build+test machines
1690 # as it depends on the timing with wide enough margins for normal situations
1691 # but does assert that it happened "soon enough" to believe the right thing
1692 # happened.
1693 @unittest.skipIf(mswindows, "requires posix like 'sleep' shell command")
1694 def test_run_with_shell_timeout_and_capture_output(self):
1695 """Output capturing after a timeout mustn't hang forever on open filehandles."""
1696 before_secs = time.monotonic()
1697 try:
1698 subprocess.run('sleep 3', shell=True, timeout=0.1,
1699 capture_output=True) # New session unspecified.
1700 except subprocess.TimeoutExpired as exc:
1701 after_secs = time.monotonic()
1702 stacks = traceback.format_exc() # assertRaises doesn't give this.
1703 else:
1704 self.fail("TimeoutExpired not raised.")
1705 self.assertLess(after_secs - before_secs, 1.5,
1706 msg="TimeoutExpired was delayed! Bad traceback:\n```\n"
1707 f"{stacks}```")
1708
Gregory P. Smith6e730002015-04-14 16:14:25 -07001709
Gregory P. Smith693aa802019-09-13 14:43:35 +01001710def _get_test_grp_name():
Victor Stinnerfaca8552019-09-25 15:52:49 +02001711 for name_group in ('staff', 'nogroup', 'grp', 'nobody', 'nfsnobody'):
Gregory P. Smith693aa802019-09-13 14:43:35 +01001712 if grp:
1713 try:
1714 grp.getgrnam(name_group)
1715 except KeyError:
1716 continue
1717 return name_group
1718 else:
1719 raise unittest.SkipTest('No identified group name to use for this test on this platform.')
1720
1721
Victor Stinner937ee9e2018-06-26 02:11:06 +02001722@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001723class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001724
Gregory P. Smith5591b022012-10-10 03:34:47 -07001725 def setUp(self):
1726 super().setUp()
1727 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1728
1729 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001730 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001731 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001732 except OSError as e:
1733 # This avoids hard coding the errno value or the OS perror()
1734 # string and instead capture the exception that we want to see
1735 # below for comparison.
1736 desired_exception = e
1737 else:
Martin Pantereb995702016-07-28 01:11:04 +00001738 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001739 self._nonexistent_dir)
1740 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001741
Gregory P. Smith5591b022012-10-10 03:34:47 -07001742 def test_exception_cwd(self):
1743 """Test error in the child raised in the parent for a bad cwd."""
1744 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001745 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001746 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001747 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001748 except OSError as e:
1749 # Test that the child process chdir failure actually makes
1750 # it up to the parent process as the correct exception.
1751 self.assertEqual(desired_exception.errno, e.errno)
1752 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001753 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001754 else:
1755 self.fail("Expected OSError: %s" % desired_exception)
1756
Gregory P. Smith5591b022012-10-10 03:34:47 -07001757 def test_exception_bad_executable(self):
1758 """Test error in the child raised in the parent for a bad executable."""
1759 desired_exception = self._get_chdir_exception()
1760 try:
1761 p = subprocess.Popen([sys.executable, "-c", ""],
1762 executable=self._nonexistent_dir)
1763 except OSError as e:
1764 # Test that the child process exec failure actually makes
1765 # it up to the parent process as the correct exception.
1766 self.assertEqual(desired_exception.errno, e.errno)
1767 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001768 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001769 else:
1770 self.fail("Expected OSError: %s" % desired_exception)
1771
1772 def test_exception_bad_args_0(self):
1773 """Test error in the child raised in the parent for a bad args[0]."""
1774 desired_exception = self._get_chdir_exception()
1775 try:
1776 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1777 except OSError as e:
1778 # Test that the child process exec failure actually makes
1779 # it up to the parent process as the correct exception.
1780 self.assertEqual(desired_exception.errno, e.errno)
1781 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001782 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001783 else:
1784 self.fail("Expected OSError: %s" % desired_exception)
1785
Ammar Askar3fc499b2017-09-06 02:41:30 -04001786 # We mock the __del__ method for Popen in the next two tests
1787 # because it does cleanup based on the pid returned by fork_exec
1788 # along with issuing a resource warning if it still exists. Since
1789 # we don't actually spawn a process in these tests we can forego
1790 # the destructor. An alternative would be to set _child_created to
1791 # False before the destructor is called but there is no easy way
1792 # to do that
1793 class PopenNoDestructor(subprocess.Popen):
1794 def __del__(self):
1795 pass
1796
1797 @mock.patch("subprocess._posixsubprocess.fork_exec")
1798 def test_exception_errpipe_normal(self, fork_exec):
1799 """Test error passing done through errpipe_write in the good case"""
1800 def proper_error(*args):
1801 errpipe_write = args[13]
1802 # Write the hex for the error code EISDIR: 'is a directory'
1803 err_code = '{:x}'.format(errno.EISDIR).encode()
1804 os.write(errpipe_write, b"OSError:" + err_code + b":")
1805 return 0
1806
1807 fork_exec.side_effect = proper_error
1808
Victor Stinner11045c92017-10-05 06:32:53 -07001809 with mock.patch("subprocess.os.waitpid",
1810 side_effect=ChildProcessError):
1811 with self.assertRaises(IsADirectoryError):
1812 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001813
1814 @mock.patch("subprocess._posixsubprocess.fork_exec")
1815 def test_exception_errpipe_bad_data(self, fork_exec):
1816 """Test error passing done through errpipe_write where its not
1817 in the expected format"""
1818 error_data = b"\xFF\x00\xDE\xAD"
1819 def bad_error(*args):
1820 errpipe_write = args[13]
1821 # Anything can be in the pipe, no assumptions should
1822 # be made about its encoding, so we'll write some
1823 # arbitrary hex bytes to test it out
1824 os.write(errpipe_write, error_data)
1825 return 0
1826
1827 fork_exec.side_effect = bad_error
1828
Victor Stinner11045c92017-10-05 06:32:53 -07001829 with mock.patch("subprocess.os.waitpid",
1830 side_effect=ChildProcessError):
1831 with self.assertRaises(subprocess.SubprocessError) as e:
1832 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001833
1834 self.assertIn(repr(error_data), str(e.exception))
1835
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001836 @unittest.skipIf(not os.path.exists('/proc/self/status'),
1837 "need /proc/self/status")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001838 def test_restore_signals(self):
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001839 # Blindly assume that cat exists on systems with /proc/self/status...
1840 default_proc_status = subprocess.check_output(
1841 ['cat', '/proc/self/status'],
1842 restore_signals=False)
1843 for line in default_proc_status.splitlines():
1844 if line.startswith(b'SigIgn'):
1845 default_sig_ign_mask = line
1846 break
1847 else:
1848 self.skipTest("SigIgn not found in /proc/self/status.")
1849 restored_proc_status = subprocess.check_output(
1850 ['cat', '/proc/self/status'],
1851 restore_signals=True)
1852 for line in restored_proc_status.splitlines():
1853 if line.startswith(b'SigIgn'):
1854 restored_sig_ign_mask = line
1855 break
1856 self.assertNotEqual(default_sig_ign_mask, restored_sig_ign_mask,
1857 msg="restore_signals=True should've unblocked "
1858 "SIGPIPE and friends.")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001859
1860 def test_start_new_session(self):
1861 # For code coverage of calling setsid(). We don't care if we get an
1862 # EPERM error from it depending on the test execution environment, that
1863 # still indicates that it was called.
1864 try:
1865 output = subprocess.check_output(
Victor Stinner58840432019-06-14 19:31:43 +02001866 [sys.executable, "-c", "import os; print(os.getsid(0))"],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001867 start_new_session=True)
1868 except OSError as e:
1869 if e.errno != errno.EPERM:
1870 raise
1871 else:
Victor Stinner58840432019-06-14 19:31:43 +02001872 parent_sid = os.getsid(0)
1873 child_sid = int(output)
1874 self.assertNotEqual(parent_sid, child_sid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001875
Patrick McLean2b2ead72019-09-12 10:15:44 -07001876 @unittest.skipUnless(hasattr(os, 'setreuid'), 'no setreuid on platform')
1877 def test_user(self):
1878 # For code coverage of the user parameter. We don't care if we get an
1879 # EPERM error from it depending on the test execution environment, that
1880 # still indicates that it was called.
1881
1882 uid = os.geteuid()
1883 test_users = [65534 if uid != 65534 else 65533, uid]
1884 name_uid = "nobody" if sys.platform != 'darwin' else "unknown"
1885
1886 if pwd is not None:
Victor Stinnerf7b5d412020-03-05 14:28:40 +01001887 try:
1888 pwd.getpwnam(name_uid)
1889 test_users.append(name_uid)
1890 except KeyError:
1891 # unknown user name
1892 name_uid = None
Patrick McLean2b2ead72019-09-12 10:15:44 -07001893
1894 for user in test_users:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001895 # posix_spawn() may be used with close_fds=False
1896 for close_fds in (False, True):
1897 with self.subTest(user=user, close_fds=close_fds):
1898 try:
1899 output = subprocess.check_output(
1900 [sys.executable, "-c",
1901 "import os; print(os.getuid())"],
1902 user=user,
1903 close_fds=close_fds)
1904 except PermissionError: # (EACCES, EPERM)
1905 pass
1906 except OSError as e:
1907 if e.errno not in (errno.EACCES, errno.EPERM):
1908 raise
Patrick McLean2b2ead72019-09-12 10:15:44 -07001909 else:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001910 if isinstance(user, str):
1911 user_uid = pwd.getpwnam(user).pw_uid
1912 else:
1913 user_uid = user
1914 child_user = int(output)
1915 self.assertEqual(child_user, user_uid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001916
1917 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001918 subprocess.check_call(ZERO_RETURN_CMD, user=-1)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001919
Alexey Izbyshevc0590c02020-10-26 03:09:32 +03001920 with self.assertRaises(OverflowError):
1921 subprocess.check_call(ZERO_RETURN_CMD,
1922 cwd=os.curdir, env=os.environ, user=2**64)
1923
Victor Stinnerf7b5d412020-03-05 14:28:40 +01001924 if pwd is None and name_uid is not None:
Patrick McLean2b2ead72019-09-12 10:15:44 -07001925 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001926 subprocess.check_call(ZERO_RETURN_CMD, user=name_uid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001927
1928 @unittest.skipIf(hasattr(os, 'setreuid'), 'setreuid() available on platform')
1929 def test_user_error(self):
1930 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001931 subprocess.check_call(ZERO_RETURN_CMD, user=65535)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001932
1933 @unittest.skipUnless(hasattr(os, 'setregid'), 'no setregid() on platform')
1934 def test_group(self):
1935 gid = os.getegid()
1936 group_list = [65534 if gid != 65534 else 65533]
Gregory P. Smith693aa802019-09-13 14:43:35 +01001937 name_group = _get_test_grp_name()
Patrick McLean2b2ead72019-09-12 10:15:44 -07001938
1939 if grp is not None:
1940 group_list.append(name_group)
1941
1942 for group in group_list + [gid]:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001943 # posix_spawn() may be used with close_fds=False
1944 for close_fds in (False, True):
1945 with self.subTest(group=group, close_fds=close_fds):
1946 try:
1947 output = subprocess.check_output(
1948 [sys.executable, "-c",
1949 "import os; print(os.getgid())"],
1950 group=group,
1951 close_fds=close_fds)
1952 except PermissionError: # (EACCES, EPERM)
1953 pass
Patrick McLean2b2ead72019-09-12 10:15:44 -07001954 else:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001955 if isinstance(group, str):
1956 group_gid = grp.getgrnam(group).gr_gid
1957 else:
1958 group_gid = group
Patrick McLean2b2ead72019-09-12 10:15:44 -07001959
Victor Stinnerfaca8552019-09-25 15:52:49 +02001960 child_group = int(output)
1961 self.assertEqual(child_group, group_gid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001962
1963 # make sure we bomb on negative values
1964 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001965 subprocess.check_call(ZERO_RETURN_CMD, group=-1)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001966
Alexey Izbyshevc0590c02020-10-26 03:09:32 +03001967 with self.assertRaises(OverflowError):
1968 subprocess.check_call(ZERO_RETURN_CMD,
1969 cwd=os.curdir, env=os.environ, group=2**64)
1970
Patrick McLean2b2ead72019-09-12 10:15:44 -07001971 if grp is None:
1972 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001973 subprocess.check_call(ZERO_RETURN_CMD, group=name_group)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001974
1975 @unittest.skipIf(hasattr(os, 'setregid'), 'setregid() available on platform')
1976 def test_group_error(self):
1977 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001978 subprocess.check_call(ZERO_RETURN_CMD, group=65535)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001979
1980 @unittest.skipUnless(hasattr(os, 'setgroups'), 'no setgroups() on platform')
1981 def test_extra_groups(self):
1982 gid = os.getegid()
1983 group_list = [65534 if gid != 65534 else 65533]
Gregory P. Smith693aa802019-09-13 14:43:35 +01001984 name_group = _get_test_grp_name()
Patrick McLean2b2ead72019-09-12 10:15:44 -07001985 perm_error = False
1986
1987 if grp is not None:
1988 group_list.append(name_group)
1989
1990 try:
1991 output = subprocess.check_output(
1992 [sys.executable, "-c",
1993 "import os, sys, json; json.dump(os.getgroups(), sys.stdout)"],
1994 extra_groups=group_list)
1995 except OSError as ex:
1996 if ex.errno != errno.EPERM:
1997 raise
1998 perm_error = True
1999
2000 else:
2001 parent_groups = os.getgroups()
2002 child_groups = json.loads(output)
2003
2004 if grp is not None:
2005 desired_gids = [grp.getgrnam(g).gr_gid if isinstance(g, str) else g
2006 for g in group_list]
2007 else:
2008 desired_gids = group_list
2009
2010 if perm_error:
2011 self.assertEqual(set(child_groups), set(parent_groups))
2012 else:
2013 self.assertEqual(set(desired_gids), set(child_groups))
2014
2015 # make sure we bomb on negative values
2016 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002017 subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[-1])
Patrick McLean2b2ead72019-09-12 10:15:44 -07002018
Alexey Izbyshevc0590c02020-10-26 03:09:32 +03002019 with self.assertRaises(ValueError):
2020 subprocess.check_call(ZERO_RETURN_CMD,
2021 cwd=os.curdir, env=os.environ,
2022 extra_groups=[2**64])
2023
Patrick McLean2b2ead72019-09-12 10:15:44 -07002024 if grp is None:
2025 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002026 subprocess.check_call(ZERO_RETURN_CMD,
Patrick McLean2b2ead72019-09-12 10:15:44 -07002027 extra_groups=[name_group])
2028
2029 @unittest.skipIf(hasattr(os, 'setgroups'), 'setgroups() available on platform')
2030 def test_extra_groups_error(self):
2031 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002032 subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[])
Patrick McLean2b2ead72019-09-12 10:15:44 -07002033
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07002034 @unittest.skipIf(mswindows or not hasattr(os, 'umask'),
2035 'POSIX umask() is not available.')
2036 def test_umask(self):
2037 tmpdir = None
2038 try:
2039 tmpdir = tempfile.mkdtemp()
2040 name = os.path.join(tmpdir, "beans")
2041 # We set an unusual umask in the child so as a unique mode
2042 # for us to test the child's touched file for.
2043 subprocess.check_call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002044 [sys.executable, "-c", f"open({name!r}, 'w').close()"],
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07002045 umask=0o053)
2046 # Ignore execute permissions entirely in our test,
2047 # filesystems could be mounted to ignore or force that.
2048 st_mode = os.stat(name).st_mode & 0o666
2049 expected_mode = 0o624
2050 self.assertEqual(expected_mode, st_mode,
2051 msg=f'{oct(expected_mode)} != {oct(st_mode)}')
2052 finally:
2053 if tmpdir is not None:
2054 shutil.rmtree(tmpdir)
2055
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002056 def test_run_abort(self):
2057 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02002058 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002059 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002060 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002061 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002062 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002063
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00002064 def test_CalledProcessError_str_signal(self):
2065 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
2066 error_string = str(err)
2067 # We're relying on the repr() of the signal.Signals intenum to provide
2068 # the word signal, the signal name and the numeric value.
2069 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00002070 # We're not being specific about the signal name as some signals have
2071 # multiple names and which name is revealed can vary.
2072 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00002073 self.assertIn(str(signal.SIGABRT), error_string)
2074
2075 def test_CalledProcessError_str_unknown_signal(self):
2076 err = subprocess.CalledProcessError(-9876543, "fake cmd")
2077 error_string = str(err)
2078 self.assertIn("unknown signal 9876543.", error_string)
2079
2080 def test_CalledProcessError_str_non_zero(self):
2081 err = subprocess.CalledProcessError(2, "fake cmd")
2082 error_string = str(err)
2083 self.assertIn("non-zero exit status 2.", error_string)
2084
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002085 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002086 # DISCLAIMER: Setting environment variables is *not* a good use
2087 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002088 p = subprocess.Popen([sys.executable, "-c",
2089 'import sys,os;'
2090 'sys.stdout.write(os.getenv("FRUIT"))'],
2091 stdout=subprocess.PIPE,
2092 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02002093 with p:
2094 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002095
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002096 def test_preexec_exception(self):
2097 def raise_it():
2098 raise ValueError("What if two swallows carried a coconut?")
2099 try:
2100 p = subprocess.Popen([sys.executable, "-c", ""],
2101 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002102 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002103 self.assertTrue(
2104 subprocess._posixsubprocess,
2105 "Expected a ValueError from the preexec_fn")
2106 except ValueError as e:
2107 self.assertIn("coconut", e.args[0])
2108 else:
2109 self.fail("Exception raised by preexec_fn did not make it "
2110 "to the parent process.")
2111
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002112 class _TestExecuteChildPopen(subprocess.Popen):
2113 """Used to test behavior at the end of _execute_child."""
2114 def __init__(self, testcase, *args, **kwargs):
2115 self._testcase = testcase
2116 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002117
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002118 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08002119 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002120 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002121 finally:
2122 # Open a bunch of file descriptors and verify that
2123 # none of them are the same as the ones the Popen
2124 # instance is using for stdin/stdout/stderr.
2125 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
2126 for _ in range(8)]
2127 try:
2128 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002129 self._testcase.assertNotIn(
2130 fd, (self.stdin.fileno(), self.stdout.fileno(),
2131 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08002132 msg="At least one fd was closed early.")
2133 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01002134 for fd in devzero_fds:
2135 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002136
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002137 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
2138 def test_preexec_errpipe_does_not_double_close_pipes(self):
2139 """Issue16140: Don't double close pipes on preexec error."""
2140
2141 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08002142 raise subprocess.SubprocessError(
2143 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08002144
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08002145 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002146 self._TestExecuteChildPopen(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002147 self, ZERO_RETURN_CMD,
Gregory P. Smith12489d92012-11-11 01:37:02 -08002148 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2149 stderr=subprocess.PIPE, preexec_fn=raise_it)
2150
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00002151 def test_preexec_gc_module_failure(self):
2152 # This tests the code that disables garbage collection if the child
2153 # process will execute any Python.
2154 def raise_runtime_error():
2155 raise RuntimeError("this shouldn't escape")
2156 enabled = gc.isenabled()
2157 orig_gc_disable = gc.disable
2158 orig_gc_isenabled = gc.isenabled
2159 try:
2160 gc.disable()
2161 self.assertFalse(gc.isenabled())
2162 subprocess.call([sys.executable, '-c', ''],
2163 preexec_fn=lambda: None)
2164 self.assertFalse(gc.isenabled(),
2165 "Popen enabled gc when it shouldn't.")
2166
2167 gc.enable()
2168 self.assertTrue(gc.isenabled())
2169 subprocess.call([sys.executable, '-c', ''],
2170 preexec_fn=lambda: None)
2171 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
2172
2173 gc.disable = raise_runtime_error
2174 self.assertRaises(RuntimeError, subprocess.Popen,
2175 [sys.executable, '-c', ''],
2176 preexec_fn=lambda: None)
2177
2178 del gc.isenabled # force an AttributeError
2179 self.assertRaises(AttributeError, subprocess.Popen,
2180 [sys.executable, '-c', ''],
2181 preexec_fn=lambda: None)
2182 finally:
2183 gc.disable = orig_gc_disable
2184 gc.isenabled = orig_gc_isenabled
2185 if not enabled:
2186 gc.disable()
2187
Martin Panterf7fdbda2015-12-05 09:51:52 +00002188 @unittest.skipIf(
2189 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00002190 def test_preexec_fork_failure(self):
2191 # The internal code did not preserve the previous exception when
2192 # re-enabling garbage collection
2193 try:
2194 from resource import getrlimit, setrlimit, RLIMIT_NPROC
2195 except ImportError as err:
2196 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
2197 limits = getrlimit(RLIMIT_NPROC)
2198 [_, hard] = limits
2199 setrlimit(RLIMIT_NPROC, (0, hard))
2200 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00002201 try:
Martin Panterafdd5132015-11-30 02:21:41 +00002202 subprocess.call([sys.executable, '-c', ''],
2203 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00002204 except BlockingIOError:
2205 # Forking should raise EAGAIN, translated to BlockingIOError
2206 pass
2207 else:
2208 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00002209
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002210 def test_args_string(self):
2211 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03002212 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002213 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002214 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002215 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002216 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2217 sys.executable)
2218 os.chmod(fname, 0o700)
2219 p = subprocess.Popen(fname)
2220 p.wait()
2221 os.remove(fname)
2222 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002223
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002224 def test_invalid_args(self):
2225 # invalid arguments should raise ValueError
2226 self.assertRaises(ValueError, subprocess.call,
2227 [sys.executable, "-c",
2228 "import sys; sys.exit(47)"],
2229 startupinfo=47)
2230 self.assertRaises(ValueError, subprocess.call,
2231 [sys.executable, "-c",
2232 "import sys; sys.exit(47)"],
2233 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002234
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002235 def test_shell_sequence(self):
2236 # Run command through the shell (sequence)
2237 newenv = os.environ.copy()
2238 newenv["FRUIT"] = "apple"
2239 p = subprocess.Popen(["echo $FRUIT"], shell=1,
2240 stdout=subprocess.PIPE,
2241 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002242 with p:
2243 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002244
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002245 def test_shell_string(self):
2246 # Run command through the shell (string)
2247 newenv = os.environ.copy()
2248 newenv["FRUIT"] = "apple"
2249 p = subprocess.Popen("echo $FRUIT", shell=1,
2250 stdout=subprocess.PIPE,
2251 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002252 with p:
2253 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00002254
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002255 def test_call_string(self):
2256 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03002257 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002258 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002259 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002260 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002261 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2262 sys.executable)
2263 os.chmod(fname, 0o700)
2264 rc = subprocess.call(fname)
2265 os.remove(fname)
2266 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00002267
Stefan Krah9542cc62010-07-19 14:20:53 +00002268 def test_specific_shell(self):
2269 # Issue #9265: Incorrect name passed as arg[0].
2270 shells = []
2271 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
2272 for name in ['bash', 'ksh']:
2273 sh = os.path.join(prefix, name)
2274 if os.path.isfile(sh):
2275 shells.append(sh)
2276 if not shells: # Will probably work for any shell but csh.
2277 self.skipTest("bash or ksh required for this test")
2278 sh = '/bin/sh'
2279 if os.path.isfile(sh) and not os.path.islink(sh):
2280 # Test will fail if /bin/sh is a symlink to csh.
2281 shells.append(sh)
2282 for sh in shells:
2283 p = subprocess.Popen("echo $0", executable=sh, shell=True,
2284 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002285 with p:
2286 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00002287
Florent Xicluna4886d242010-03-08 13:27:26 +00002288 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00002289 # Do not inherit file handles from the parent.
2290 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07002291 # Also set the SIGINT handler to the default to make sure it's not
2292 # being ignored (some tests rely on that.)
2293 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
2294 try:
2295 p = subprocess.Popen([sys.executable, "-c", """if 1:
2296 import sys, time
2297 sys.stdout.write('x\\n')
2298 sys.stdout.flush()
2299 time.sleep(30)
2300 """],
2301 close_fds=True,
2302 stdin=subprocess.PIPE,
2303 stdout=subprocess.PIPE,
2304 stderr=subprocess.PIPE)
2305 finally:
2306 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00002307 # Wait for the interpreter to be completely initialized before
2308 # sending any signal.
2309 p.stdout.read(1)
2310 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00002311 return p
2312
Charles-François Natali53221e32013-01-12 16:52:20 +01002313 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
2314 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002315 def _kill_dead_process(self, method, *args):
2316 # Do not inherit file handles from the parent.
2317 # It should fix failures on some platforms.
2318 p = subprocess.Popen([sys.executable, "-c", """if 1:
2319 import sys, time
2320 sys.stdout.write('x\\n')
2321 sys.stdout.flush()
2322 """],
2323 close_fds=True,
2324 stdin=subprocess.PIPE,
2325 stdout=subprocess.PIPE,
2326 stderr=subprocess.PIPE)
2327 # Wait for the interpreter to be completely initialized before
2328 # sending any signal.
2329 p.stdout.read(1)
2330 # The process should end after this
2331 time.sleep(1)
2332 # This shouldn't raise even though the child is now dead
2333 getattr(p, method)(*args)
2334 p.communicate()
2335
Florent Xicluna4886d242010-03-08 13:27:26 +00002336 def test_send_signal(self):
2337 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00002338 _, stderr = p.communicate()
2339 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002340 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00002341
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002342 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002343 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00002344 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002345 self.assertEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002346 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00002347
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002348 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002349 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00002350 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002351 self.assertEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002352 self.assertEqual(p.wait(), -signal.SIGTERM)
2353
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002354 def test_send_signal_dead(self):
2355 # Sending a signal to a dead process
2356 self._kill_dead_process('send_signal', signal.SIGINT)
2357
2358 def test_kill_dead(self):
2359 # Killing a dead process
2360 self._kill_dead_process('kill')
2361
2362 def test_terminate_dead(self):
2363 # Terminating a dead process
2364 self._kill_dead_process('terminate')
2365
Victor Stinnerdaf45552013-08-28 00:53:59 +02002366 def _save_fds(self, save_fds):
2367 fds = []
2368 for fd in save_fds:
2369 inheritable = os.get_inheritable(fd)
2370 saved = os.dup(fd)
2371 fds.append((fd, saved, inheritable))
2372 return fds
2373
2374 def _restore_fds(self, fds):
2375 for fd, saved, inheritable in fds:
2376 os.dup2(saved, fd, inheritable=inheritable)
2377 os.close(saved)
2378
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002379 def check_close_std_fds(self, fds):
2380 # Issue #9905: test that subprocess pipes still work properly with
2381 # some standard fds closed
2382 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02002383 saved_fds = self._save_fds(fds)
2384 for fd, saved, inheritable in saved_fds:
2385 if fd == 0:
2386 stdin = saved
2387 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002388 try:
2389 for fd in fds:
2390 os.close(fd)
2391 out, err = subprocess.Popen([sys.executable, "-c",
2392 'import sys;'
2393 'sys.stdout.write("apple");'
2394 'sys.stdout.flush();'
2395 'sys.stderr.write("orange")'],
2396 stdin=stdin,
2397 stdout=subprocess.PIPE,
2398 stderr=subprocess.PIPE).communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002399 self.assertEqual(out, b'apple')
2400 self.assertEqual(err, b'orange')
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002401 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002402 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002403
2404 def test_close_fd_0(self):
2405 self.check_close_std_fds([0])
2406
2407 def test_close_fd_1(self):
2408 self.check_close_std_fds([1])
2409
2410 def test_close_fd_2(self):
2411 self.check_close_std_fds([2])
2412
2413 def test_close_fds_0_1(self):
2414 self.check_close_std_fds([0, 1])
2415
2416 def test_close_fds_0_2(self):
2417 self.check_close_std_fds([0, 2])
2418
2419 def test_close_fds_1_2(self):
2420 self.check_close_std_fds([1, 2])
2421
2422 def test_close_fds_0_1_2(self):
2423 # Issue #10806: test that subprocess pipes still work properly with
2424 # all standard fds closed.
2425 self.check_close_std_fds([0, 1, 2])
2426
Gregory P. Smith53dd8162013-12-01 16:03:24 -08002427 def test_small_errpipe_write_fd(self):
2428 """Issue #15798: Popen should work when stdio fds are available."""
2429 new_stdin = os.dup(0)
2430 new_stdout = os.dup(1)
2431 try:
2432 os.close(0)
2433 os.close(1)
2434
2435 # Side test: if errpipe_write fails to have its CLOEXEC
2436 # flag set this should cause the parent to think the exec
2437 # failed. Extremely unlikely: everyone supports CLOEXEC.
2438 subprocess.Popen([
2439 sys.executable, "-c",
2440 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
2441 finally:
2442 # Restore original stdin and stdout
2443 os.dup2(new_stdin, 0)
2444 os.dup2(new_stdout, 1)
2445 os.close(new_stdin)
2446 os.close(new_stdout)
2447
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002448 def test_remapping_std_fds(self):
2449 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002450 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002451 try:
2452 temp_fds = [fd for fd, fname in temps]
2453
2454 # unlink the files -- we won't need to reopen them
2455 for fd, fname in temps:
2456 os.unlink(fname)
2457
2458 # write some data to what will become stdin, and rewind
2459 os.write(temp_fds[1], b"STDIN")
2460 os.lseek(temp_fds[1], 0, 0)
2461
2462 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02002463 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002464 try:
2465 # duplicate the file objects over the standard fd's
2466 for fd, temp_fd in enumerate(temp_fds):
2467 os.dup2(temp_fd, fd)
2468
2469 # now use those files in the "wrong" order, so that subprocess
2470 # has to rearrange them in the child
2471 p = subprocess.Popen([sys.executable, "-c",
2472 'import sys; got = sys.stdin.read();'
2473 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2474 stdin=temp_fds[1],
2475 stdout=temp_fds[2],
2476 stderr=temp_fds[0])
2477 p.wait()
2478 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002479 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002480
2481 for fd in temp_fds:
2482 os.lseek(fd, 0, 0)
2483
2484 out = os.read(temp_fds[2], 1024)
Victor Stinner6cac1132019-12-08 08:38:16 +01002485 err = os.read(temp_fds[0], 1024).strip()
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002486 self.assertEqual(out, b"got STDIN")
2487 self.assertEqual(err, b"err")
2488
2489 finally:
2490 for fd in temp_fds:
2491 os.close(fd)
2492
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002493 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
2494 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002495 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002496 temp_fds = [fd for fd, fname in temps]
2497 try:
2498 # unlink the files -- we won't need to reopen them
2499 for fd, fname in temps:
2500 os.unlink(fname)
2501
2502 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02002503 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002504 try:
2505 # duplicate the temp files over the standard fd's 0, 1, 2
2506 for fd, temp_fd in enumerate(temp_fds):
2507 os.dup2(temp_fd, fd)
2508
2509 # write some data to what will become stdin, and rewind
2510 os.write(stdin_no, b"STDIN")
2511 os.lseek(stdin_no, 0, 0)
2512
2513 # now use those files in the given order, so that subprocess
2514 # has to rearrange them in the child
2515 p = subprocess.Popen([sys.executable, "-c",
2516 'import sys; got = sys.stdin.read();'
2517 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2518 stdin=stdin_no,
2519 stdout=stdout_no,
2520 stderr=stderr_no)
2521 p.wait()
2522
2523 for fd in temp_fds:
2524 os.lseek(fd, 0, 0)
2525
2526 out = os.read(stdout_no, 1024)
Victor Stinner6cac1132019-12-08 08:38:16 +01002527 err = os.read(stderr_no, 1024).strip()
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002528 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002529 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002530
2531 self.assertEqual(out, b"got STDIN")
2532 self.assertEqual(err, b"err")
2533
2534 finally:
2535 for fd in temp_fds:
2536 os.close(fd)
2537
2538 # When duping fds, if there arises a situation where one of the fds is
2539 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
2540 # This tests all combinations of this.
2541 def test_swap_fds(self):
2542 self.check_swap_fds(0, 1, 2)
2543 self.check_swap_fds(0, 2, 1)
2544 self.check_swap_fds(1, 0, 2)
2545 self.check_swap_fds(1, 2, 0)
2546 self.check_swap_fds(2, 0, 1)
2547 self.check_swap_fds(2, 1, 0)
2548
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +03002549 def _check_swap_std_fds_with_one_closed(self, from_fds, to_fds):
2550 saved_fds = self._save_fds(range(3))
2551 try:
2552 for from_fd in from_fds:
2553 with tempfile.TemporaryFile() as f:
2554 os.dup2(f.fileno(), from_fd)
2555
2556 fd_to_close = (set(range(3)) - set(from_fds)).pop()
2557 os.close(fd_to_close)
2558
2559 arg_names = ['stdin', 'stdout', 'stderr']
2560 kwargs = {}
2561 for from_fd, to_fd in zip(from_fds, to_fds):
2562 kwargs[arg_names[to_fd]] = from_fd
2563
2564 code = textwrap.dedent(r'''
2565 import os, sys
2566 skipped_fd = int(sys.argv[1])
2567 for fd in range(3):
2568 if fd != skipped_fd:
2569 os.write(fd, str(fd).encode('ascii'))
2570 ''')
2571
2572 skipped_fd = (set(range(3)) - set(to_fds)).pop()
2573
2574 rc = subprocess.call([sys.executable, '-c', code, str(skipped_fd)],
2575 **kwargs)
2576 self.assertEqual(rc, 0)
2577
2578 for from_fd, to_fd in zip(from_fds, to_fds):
2579 os.lseek(from_fd, 0, os.SEEK_SET)
2580 read_bytes = os.read(from_fd, 1024)
2581 read_fds = list(map(int, read_bytes.decode('ascii')))
2582 msg = textwrap.dedent(f"""
2583 When testing {from_fds} to {to_fds} redirection,
2584 parent descriptor {from_fd} got redirected
2585 to descriptor(s) {read_fds} instead of descriptor {to_fd}.
2586 """)
2587 self.assertEqual([to_fd], read_fds, msg)
2588 finally:
2589 self._restore_fds(saved_fds)
2590
2591 # Check that subprocess can remap std fds correctly even
2592 # if one of them is closed (#32844).
2593 def test_swap_std_fds_with_one_closed(self):
2594 for from_fds in itertools.combinations(range(3), 2):
2595 for to_fds in itertools.permutations(range(3), 2):
2596 self._check_swap_std_fds_with_one_closed(from_fds, to_fds)
2597
Victor Stinner13bb71c2010-04-23 21:41:56 +00002598 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00002599 def prepare():
2600 raise ValueError("surrogate:\uDCff")
2601
2602 try:
2603 subprocess.call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002604 ZERO_RETURN_CMD,
Victor Stinner4d078042010-04-23 19:28:32 +00002605 preexec_fn=prepare)
2606 except ValueError as err:
2607 # Pure Python implementations keeps the message
2608 self.assertIsNone(subprocess._posixsubprocess)
2609 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002610 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00002611 # _posixsubprocess uses a default message
2612 self.assertIsNotNone(subprocess._posixsubprocess)
2613 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
2614 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002615 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00002616
Victor Stinner13bb71c2010-04-23 21:41:56 +00002617 def test_undecodable_env(self):
2618 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01002619 encoded_value = value.encode("ascii", "surrogateescape")
2620
Victor Stinner13bb71c2010-04-23 21:41:56 +00002621 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002622 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002623 env = os.environ.copy()
2624 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01002625 # Use C locale to get ASCII for the locale encoding to force
Michael Felt89d79b12018-08-26 19:29:36 +02002626 # surrogate-escaping of \xFF in the child process
Victor Stinnerebc78d22010-10-14 10:38:17 +00002627 env['LC_ALL'] = 'C'
Michael Felt89d79b12018-08-26 19:29:36 +02002628 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002629 stdout = subprocess.check_output(
2630 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002631 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002632 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002633 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002634
2635 # test bytes
2636 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002637 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002638 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01002639 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002640 stdout = subprocess.check_output(
2641 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002642 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002643 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002644 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002645
Victor Stinnerb745a742010-05-18 17:17:23 +00002646 def test_bytes_program(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002647 abs_program = os.fsencode(ZERO_RETURN_CMD[0])
2648 args = list(ZERO_RETURN_CMD[1:])
2649 path, program = os.path.split(ZERO_RETURN_CMD[0])
Victor Stinnerb745a742010-05-18 17:17:23 +00002650 program = os.fsencode(program)
2651
2652 # absolute bytes path
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002653 exitcode = subprocess.call([abs_program]+args)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002654 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002655
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002656 # absolute bytes path as a string
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002657 cmd = b"'%s' %s" % (abs_program, " ".join(args).encode("utf-8"))
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002658 exitcode = subprocess.call(cmd, shell=True)
2659 self.assertEqual(exitcode, 0)
2660
Victor Stinnerb745a742010-05-18 17:17:23 +00002661 # bytes program, unicode PATH
2662 env = os.environ.copy()
2663 env["PATH"] = path
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002664 exitcode = subprocess.call([program]+args, env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002665 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002666
2667 # bytes program, bytes PATH
2668 envb = os.environb.copy()
2669 envb[b"PATH"] = os.fsencode(path)
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002670 exitcode = subprocess.call([program]+args, env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002671 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002672
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002673 def test_pipe_cloexec(self):
2674 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2675 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2676
2677 p1 = subprocess.Popen([sys.executable, sleeper],
2678 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2679 stderr=subprocess.PIPE, close_fds=False)
2680
2681 self.addCleanup(p1.communicate, b'')
2682
2683 p2 = subprocess.Popen([sys.executable, fd_status],
2684 stdout=subprocess.PIPE, close_fds=False)
2685
2686 output, error = p2.communicate()
2687 result_fds = set(map(int, output.split(b',')))
2688 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2689 p1.stderr.fileno()])
2690
2691 self.assertFalse(result_fds & unwanted_fds,
2692 "Expected no fds from %r to be open in child, "
2693 "found %r" %
2694 (unwanted_fds, result_fds & unwanted_fds))
2695
2696 def test_pipe_cloexec_real_tools(self):
2697 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2698 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2699
2700 subdata = b'zxcvbn'
2701 data = subdata * 4 + b'\n'
2702
2703 p1 = subprocess.Popen([sys.executable, qcat],
2704 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2705 close_fds=False)
2706
2707 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2708 stdin=p1.stdout, stdout=subprocess.PIPE,
2709 close_fds=False)
2710
2711 self.addCleanup(p1.wait)
2712 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002713 def kill_p1():
2714 try:
2715 p1.terminate()
2716 except ProcessLookupError:
2717 pass
2718 def kill_p2():
2719 try:
2720 p2.terminate()
2721 except ProcessLookupError:
2722 pass
2723 self.addCleanup(kill_p1)
2724 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002725
2726 p1.stdin.write(data)
2727 p1.stdin.close()
2728
2729 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2730
2731 self.assertTrue(readfiles, "The child hung")
2732 self.assertEqual(p2.stdout.read(), data)
2733
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002734 p1.stdout.close()
2735 p2.stdout.close()
2736
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002737 def test_close_fds(self):
2738 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2739
2740 fds = os.pipe()
2741 self.addCleanup(os.close, fds[0])
2742 self.addCleanup(os.close, fds[1])
2743
2744 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002745 # add a bunch more fds
2746 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002747 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002748 self.addCleanup(os.close, fd)
2749 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002750
Victor Stinnerdaf45552013-08-28 00:53:59 +02002751 for fd in open_fds:
2752 os.set_inheritable(fd, True)
2753
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002754 p = subprocess.Popen([sys.executable, fd_status],
2755 stdout=subprocess.PIPE, close_fds=False)
2756 output, ignored = p.communicate()
2757 remaining_fds = set(map(int, output.split(b',')))
2758
2759 self.assertEqual(remaining_fds & open_fds, open_fds,
2760 "Some fds were closed")
2761
2762 p = subprocess.Popen([sys.executable, fd_status],
2763 stdout=subprocess.PIPE, close_fds=True)
2764 output, ignored = p.communicate()
2765 remaining_fds = set(map(int, output.split(b',')))
2766
2767 self.assertFalse(remaining_fds & open_fds,
2768 "Some fds were left open")
2769 self.assertIn(1, remaining_fds, "Subprocess failed")
2770
Gregory P. Smith8facece2012-01-21 14:01:08 -08002771 # Keep some of the fd's we opened open in the subprocess.
2772 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2773 fds_to_keep = set(open_fds.pop() for _ in range(8))
2774 p = subprocess.Popen([sys.executable, fd_status],
2775 stdout=subprocess.PIPE, close_fds=True,
izbyshev2d8f0632017-12-19 03:26:49 +07002776 pass_fds=fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002777 output, ignored = p.communicate()
2778 remaining_fds = set(map(int, output.split(b',')))
2779
izbyshev2d8f0632017-12-19 03:26:49 +07002780 self.assertFalse((remaining_fds - fds_to_keep) & open_fds,
Gregory P. Smith8facece2012-01-21 14:01:08 -08002781 "Some fds not in pass_fds were left open")
2782 self.assertIn(1, remaining_fds, "Subprocess failed")
2783
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002784
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002785 @unittest.skipIf(sys.platform.startswith("freebsd") and
2786 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2787 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002788 def test_close_fds_when_max_fd_is_lowered(self):
2789 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2790 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2791
Gregory P. Smith634aa682014-06-15 17:51:04 -07002792 # This launches the meat of the test in a child process to
2793 # avoid messing with the larger unittest processes maximum
2794 # number of file descriptors.
2795 # This process launches:
2796 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2797 # a bunch of high open fds above the new lower rlimit.
2798 # Those are reported via stdout before launching a new
2799 # process with close_fds=False to run the actual test:
2800 # +--> The TEST: This one launches a fd_status.py
2801 # subprocess with close_fds=True so we can find out if
2802 # any of the fds above the lowered rlimit are still open.
2803 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2804 '''
2805 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002806 open_fds = set()
2807 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002808 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002809 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002810 open_fds.add(fd)
2811
2812 # Leave a two pairs of low ones available for use by the
2813 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002814 # We also leave 10 more open as some Python buildbots run into
2815 # "too many open files" errors during the test if we do not.
2816 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002817 os.close(fd)
2818 open_fds.remove(fd)
2819
2820 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002821 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002822 os.set_inheritable(fd, True)
2823
2824 max_fd_open = max(open_fds)
2825
Gregory P. Smith634aa682014-06-15 17:51:04 -07002826 # Communicate the open_fds to the parent unittest.TestCase process.
2827 print(','.join(map(str, sorted(open_fds))))
2828 sys.stdout.flush()
2829
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002830 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2831 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002832 # 29 is lower than the highest fds we are leaving open.
2833 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002834 # Launch a new Python interpreter with our low fd rlim_cur that
2835 # inherits open fds above that limit. It then uses subprocess
2836 # with close_fds=True to get a report of open fds in the child.
2837 # An explicit list of fds to check is passed to fd_status.py as
2838 # letting fd_status rely on its default logic would miss the
2839 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002840 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002841 [sys.executable, '-c',
2842 textwrap.dedent("""
2843 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002844 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002845 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002846 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002847 """.format(max_fd=max_fd_open+1))],
2848 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002849 finally:
2850 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002851 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002852
2853 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002854 output_lines = output.splitlines()
2855 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002856 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002857 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2858 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002859
Gregory P. Smith634aa682014-06-15 17:51:04 -07002860 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002861 msg="Some fds were left open.")
2862
2863
Victor Stinner88701e22011-06-01 13:13:04 +02002864 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2865 # descriptor of a pipe closed in the parent process is valid in the
2866 # child process according to fstat(), but the mode of the file
2867 # descriptor is invalid, and read or write raise an error.
2868 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002869 def test_pass_fds(self):
2870 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2871
2872 open_fds = set()
2873
2874 for x in range(5):
2875 fds = os.pipe()
2876 self.addCleanup(os.close, fds[0])
2877 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002878 os.set_inheritable(fds[0], True)
2879 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002880 open_fds.update(fds)
2881
2882 for fd in open_fds:
2883 p = subprocess.Popen([sys.executable, fd_status],
2884 stdout=subprocess.PIPE, close_fds=True,
2885 pass_fds=(fd, ))
2886 output, ignored = p.communicate()
2887
2888 remaining_fds = set(map(int, output.split(b',')))
2889 to_be_closed = open_fds - {fd}
2890
2891 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2892 self.assertFalse(remaining_fds & to_be_closed,
2893 "fd to be closed passed")
2894
2895 # pass_fds overrides close_fds with a warning.
2896 with self.assertWarns(RuntimeWarning) as context:
2897 self.assertFalse(subprocess.call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002898 ZERO_RETURN_CMD,
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002899 close_fds=False, pass_fds=(fd, )))
2900 self.assertIn('overriding close_fds', str(context.warning))
2901
Victor Stinnerdaf45552013-08-28 00:53:59 +02002902 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002903 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002904
2905 inheritable, non_inheritable = os.pipe()
2906 self.addCleanup(os.close, inheritable)
2907 self.addCleanup(os.close, non_inheritable)
2908 os.set_inheritable(inheritable, True)
2909 os.set_inheritable(non_inheritable, False)
2910 pass_fds = (inheritable, non_inheritable)
2911 args = [sys.executable, script]
2912 args += list(map(str, pass_fds))
2913
2914 p = subprocess.Popen(args,
2915 stdout=subprocess.PIPE, close_fds=True,
2916 pass_fds=pass_fds)
2917 output, ignored = p.communicate()
2918 fds = set(map(int, output.split(b',')))
2919
2920 # the inheritable file descriptor must be inherited, so its inheritable
2921 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002922 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002923
2924 # inheritable flag must not be changed in the parent process
2925 self.assertEqual(os.get_inheritable(inheritable), True)
2926 self.assertEqual(os.get_inheritable(non_inheritable), False)
2927
Gregory P. Smithce344102018-09-10 17:46:22 -07002928
2929 # bpo-32270: Ensure that descriptors specified in pass_fds
2930 # are inherited even if they are used in redirections.
2931 # Contributed by @izbyshev.
2932 def test_pass_fds_redirected(self):
2933 """Regression test for https://bugs.python.org/issue32270."""
2934 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2935 pass_fds = []
2936 for _ in range(2):
2937 fd = os.open(os.devnull, os.O_RDWR)
2938 self.addCleanup(os.close, fd)
2939 pass_fds.append(fd)
2940
2941 stdout_r, stdout_w = os.pipe()
2942 self.addCleanup(os.close, stdout_r)
2943 self.addCleanup(os.close, stdout_w)
2944 pass_fds.insert(1, stdout_w)
2945
2946 with subprocess.Popen([sys.executable, fd_status],
2947 stdin=pass_fds[0],
2948 stdout=pass_fds[1],
2949 stderr=pass_fds[2],
2950 close_fds=True,
2951 pass_fds=pass_fds):
2952 output = os.read(stdout_r, 1024)
2953 fds = {int(num) for num in output.split(b',')}
2954
2955 self.assertEqual(fds, {0, 1, 2} | frozenset(pass_fds), f"output={output!a}")
2956
2957
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002958 def test_stdout_stdin_are_single_inout_fd(self):
2959 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002960 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002961 stdout=inout, stdin=inout)
2962 p.wait()
2963
2964 def test_stdout_stderr_are_single_inout_fd(self):
2965 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002966 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002967 stdout=inout, stderr=inout)
2968 p.wait()
2969
2970 def test_stderr_stdin_are_single_inout_fd(self):
2971 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002972 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002973 stderr=inout, stdin=inout)
2974 p.wait()
2975
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002976 def test_wait_when_sigchild_ignored(self):
2977 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2978 sigchild_ignore = support.findfile("sigchild_ignore.py",
2979 subdir="subprocessdata")
2980 p = subprocess.Popen([sys.executable, sigchild_ignore],
2981 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2982 stdout, stderr = p.communicate()
2983 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002984 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002985 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002986
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002987 def test_select_unbuffered(self):
2988 # Issue #11459: bufsize=0 should really set the pipes as
2989 # unbuffered (and therefore let select() work properly).
Hai Shi0c4f0f32020-06-30 21:46:31 +08002990 select = import_helper.import_module("select")
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002991 p = subprocess.Popen([sys.executable, "-c",
2992 'import sys;'
2993 'sys.stdout.write("apple")'],
2994 stdout=subprocess.PIPE,
2995 bufsize=0)
2996 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002997 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002998 try:
2999 self.assertEqual(f.read(4), b"appl")
3000 self.assertIn(f, select.select([f], [], [], 0.0)[0])
3001 finally:
3002 p.wait()
3003
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003004 def test_zombie_fast_process_del(self):
3005 # Issue #12650: on Unix, if Popen.__del__() was called before the
3006 # process exited, it wouldn't be added to subprocess._active, and would
3007 # remain a zombie.
3008 # spawn a Popen, and delete its reference before it exits
3009 p = subprocess.Popen([sys.executable, "-c",
3010 'import sys, time;'
3011 'time.sleep(0.2)'],
3012 stdout=subprocess.PIPE,
3013 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02003014 self.addCleanup(p.stdout.close)
3015 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003016 ident = id(p)
3017 pid = p.pid
Hai Shi0c4f0f32020-06-30 21:46:31 +08003018 with warnings_helper.check_warnings(('', ResourceWarning)):
Victor Stinner5a48e212016-05-20 12:11:15 +02003019 p = None
3020
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03003021 if mswindows:
3022 # subprocess._active is not used on Windows and is set to None.
3023 self.assertIsNone(subprocess._active)
3024 else:
3025 # check that p is in the active processes list
3026 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003027
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003028 def test_leak_fast_process_del_killed(self):
3029 # Issue #12650: on Unix, if Popen.__del__() was called before the
3030 # process exited, and the process got killed by a signal, it would never
3031 # be removed from subprocess._active, which triggered a FD and memory
3032 # leak.
3033 # spawn a Popen, delete its reference and kill it
3034 p = subprocess.Popen([sys.executable, "-c",
3035 'import time;'
3036 'time.sleep(3)'],
3037 stdout=subprocess.PIPE,
3038 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02003039 self.addCleanup(p.stdout.close)
3040 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003041 ident = id(p)
3042 pid = p.pid
Hai Shi0c4f0f32020-06-30 21:46:31 +08003043 with warnings_helper.check_warnings(('', ResourceWarning)):
Victor Stinner5a48e212016-05-20 12:11:15 +02003044 p = None
3045
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003046 os.kill(pid, signal.SIGKILL)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03003047 if mswindows:
3048 # subprocess._active is not used on Windows and is set to None.
3049 self.assertIsNone(subprocess._active)
3050 else:
3051 # check that p is in the active processes list
3052 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003053
3054 # let some time for the process to exit, and create a new Popen: this
3055 # should trigger the wait() of p
3056 time.sleep(0.2)
Victor Stinnerb31206a2018-01-25 19:06:05 +01003057 with self.assertRaises(OSError):
Victor Stinner9a83f652017-08-21 23:51:31 +02003058 with subprocess.Popen(NONEXISTING_CMD,
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003059 stdout=subprocess.PIPE,
3060 stderr=subprocess.PIPE) as proc:
3061 pass
3062 # p should have been wait()ed on, and removed from the _active list
3063 self.assertRaises(OSError, os.waitpid, pid, 0)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03003064 if mswindows:
3065 # subprocess._active is not used on Windows and is set to None.
3066 self.assertIsNone(subprocess._active)
3067 else:
3068 self.assertNotIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003069
Charles-François Natali249cdc32013-08-25 18:24:45 +02003070 def test_close_fds_after_preexec(self):
3071 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
3072
3073 # this FD is used as dup2() target by preexec_fn, and should be closed
3074 # in the child process
3075 fd = os.dup(1)
3076 self.addCleanup(os.close, fd)
3077
3078 p = subprocess.Popen([sys.executable, fd_status],
3079 stdout=subprocess.PIPE, close_fds=True,
3080 preexec_fn=lambda: os.dup2(1, fd))
3081 output, ignored = p.communicate()
3082
3083 remaining_fds = set(map(int, output.split(b',')))
3084
3085 self.assertNotIn(fd, remaining_fds)
3086
Victor Stinner8f437aa2014-10-05 17:25:19 +02003087 @support.cpython_only
3088 def test_fork_exec(self):
3089 # Issue #22290: fork_exec() must not crash on memory allocation failure
3090 # or other errors
3091 import _posixsubprocess
3092 gc_enabled = gc.isenabled()
3093 try:
3094 # Use a preexec function and enable the garbage collector
3095 # to force fork_exec() to re-enable the garbage collector
3096 # on error.
3097 func = lambda: None
3098 gc.enable()
3099
Victor Stinner8f437aa2014-10-05 17:25:19 +02003100 for args, exe_list, cwd, env_list in (
3101 (123, [b"exe"], None, [b"env"]),
3102 ([b"arg"], 123, None, [b"env"]),
3103 ([b"arg"], [b"exe"], 123, [b"env"]),
3104 ([b"arg"], [b"exe"], None, 123),
3105 ):
Patrick McLean2b2ead72019-09-12 10:15:44 -07003106 with self.assertRaises(TypeError) as err:
Victor Stinner8f437aa2014-10-05 17:25:19 +02003107 _posixsubprocess.fork_exec(
3108 args, exe_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003109 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02003110 -1, -1, -1, -1,
3111 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003112 True, True,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07003113 False, [], 0, -1,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003114 func)
3115 # Attempt to prevent
3116 # "TypeError: fork_exec() takes exactly N arguments (M given)"
3117 # from passing the test. More refactoring to have us start
3118 # with a valid *args list, confirm a good call with that works
3119 # before mutating it in various ways to ensure that bad calls
3120 # with individual arg type errors raise a typeerror would be
3121 # ideal. Saving that for a future PR...
3122 self.assertNotIn('takes exactly', str(err.exception))
Victor Stinner8f437aa2014-10-05 17:25:19 +02003123 finally:
3124 if not gc_enabled:
3125 gc.disable()
3126
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003127 @support.cpython_only
3128 def test_fork_exec_sorted_fd_sanity_check(self):
3129 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
3130 import _posixsubprocess
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003131 class BadInt:
3132 first = True
3133 def __init__(self, value):
3134 self.value = value
3135 def __int__(self):
3136 if self.first:
3137 self.first = False
3138 return self.value
3139 raise ValueError
3140
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003141 gc_enabled = gc.isenabled()
3142 try:
3143 gc.enable()
3144
3145 for fds_to_keep in (
3146 (-1, 2, 3, 4, 5), # Negative number.
3147 ('str', 4), # Not an int.
3148 (18, 23, 42, 2**63), # Out of range.
3149 (5, 4), # Not sorted.
3150 (6, 7, 7, 8), # Duplicate.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003151 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003152 ):
3153 with self.assertRaises(
3154 ValueError,
3155 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
3156 _posixsubprocess.fork_exec(
3157 [b"false"], [b"false"],
3158 True, fds_to_keep, None, [b"env"],
3159 -1, -1, -1, -1,
3160 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003161 True, True,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07003162 None, None, None, -1,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003163 None)
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003164 self.assertIn('fds_to_keep', str(c.exception))
3165 finally:
3166 if not gc_enabled:
3167 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02003168
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003169 def test_communicate_BrokenPipeError_stdin_close(self):
3170 # By not setting stdout or stderr or a timeout we force the fast path
3171 # that just calls _stdin_write() internally due to our mock.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003172 proc = subprocess.Popen(ZERO_RETURN_CMD)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003173 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3174 mock_proc_stdin.close.side_effect = BrokenPipeError
3175 proc.communicate() # Should swallow BrokenPipeError from close.
3176 mock_proc_stdin.close.assert_called_with()
3177
3178 def test_communicate_BrokenPipeError_stdin_write(self):
3179 # By not setting stdout or stderr or a timeout we force the fast path
3180 # that just calls _stdin_write() internally due to our mock.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003181 proc = subprocess.Popen(ZERO_RETURN_CMD)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003182 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3183 mock_proc_stdin.write.side_effect = BrokenPipeError
3184 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
3185 mock_proc_stdin.write.assert_called_once_with(b'stuff')
3186 mock_proc_stdin.close.assert_called_once_with()
3187
3188 def test_communicate_BrokenPipeError_stdin_flush(self):
3189 # Setting stdin and stdout forces the ._communicate() code path.
3190 # python -h exits faster than python -c pass (but spams stdout).
3191 proc = subprocess.Popen([sys.executable, '-h'],
3192 stdin=subprocess.PIPE,
3193 stdout=subprocess.PIPE)
3194 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
3195 open(os.devnull, 'wb') as dev_null:
3196 mock_proc_stdin.flush.side_effect = BrokenPipeError
3197 # because _communicate registers a selector using proc.stdin...
3198 mock_proc_stdin.fileno.return_value = dev_null.fileno()
3199 # _communicate() should swallow BrokenPipeError from flush.
3200 proc.communicate(b'stuff')
3201 mock_proc_stdin.flush.assert_called_once_with()
3202
3203 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
3204 # Setting stdin and stdout forces the ._communicate() code path.
3205 # python -h exits faster than python -c pass (but spams stdout).
3206 proc = subprocess.Popen([sys.executable, '-h'],
3207 stdin=subprocess.PIPE,
3208 stdout=subprocess.PIPE)
3209 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3210 mock_proc_stdin.close.side_effect = BrokenPipeError
3211 # _communicate() should swallow BrokenPipeError from close.
3212 proc.communicate(timeout=999)
3213 mock_proc_stdin.close.assert_called_once_with()
3214
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003215 @unittest.skipUnless(_testcapi is not None
3216 and hasattr(_testcapi, 'W_STOPCODE'),
3217 'need _testcapi.W_STOPCODE')
3218 def test_stopped(self):
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003219 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003220 args = ZERO_RETURN_CMD
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003221 proc = subprocess.Popen(args)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003222
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003223 # Wait until the real process completes to avoid zombie process
Victor Stinner278c1e12020-03-31 20:08:12 +02003224 support.wait_process(proc.pid, exitcode=0)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003225
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003226 status = _testcapi.W_STOPCODE(3)
Victor Stinner278c1e12020-03-31 20:08:12 +02003227 with mock.patch('subprocess.os.waitpid', return_value=(proc.pid, status)):
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003228 returncode = proc.wait()
Victor Stinnercdee3f12017-06-26 17:23:03 +02003229
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003230 self.assertEqual(returncode, -3)
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003231
Victor Stinnere85a3052020-01-15 17:38:55 +01003232 def test_send_signal_race(self):
3233 # bpo-38630: send_signal() must poll the process exit status to reduce
3234 # the risk of sending the signal to the wrong process.
3235 proc = subprocess.Popen(ZERO_RETURN_CMD)
3236
3237 # wait until the process completes without using the Popen APIs.
Victor Stinner278c1e12020-03-31 20:08:12 +02003238 support.wait_process(proc.pid, exitcode=0)
Victor Stinnere85a3052020-01-15 17:38:55 +01003239
3240 # returncode is still None but the process completed.
3241 self.assertIsNone(proc.returncode)
3242
3243 with mock.patch("os.kill") as mock_kill:
3244 proc.send_signal(signal.SIGTERM)
3245
3246 # send_signal() didn't call os.kill() since the process already
3247 # completed.
3248 mock_kill.assert_not_called()
3249
3250 # Don't check the returncode value: the test reads the exit status,
3251 # so Popen failed to read it and uses a default returncode instead.
3252 self.assertIsNotNone(proc.returncode)
3253
Filipe Laíns01a202a2020-11-21 09:22:08 +00003254 def test_send_signal_race2(self):
3255 # bpo-40550: the process might exist between the returncode check and
3256 # the kill operation
3257 p = subprocess.Popen([sys.executable, '-c', 'exit(1)'])
3258
3259 # wait for process to exit
3260 while not p.returncode:
3261 p.poll()
3262
3263 with mock.patch.object(p, 'poll', new=lambda: None):
3264 p.returncode = None
3265 p.send_signal(signal.SIGTERM)
3266
Alex Rebertd3ae95e2020-01-22 18:28:31 -05003267 def test_communicate_repeated_call_after_stdout_close(self):
3268 proc = subprocess.Popen([sys.executable, '-c',
3269 'import os, time; os.close(1), time.sleep(2)'],
3270 stdout=subprocess.PIPE)
3271 while True:
3272 try:
3273 proc.communicate(timeout=0.1)
3274 return
3275 except subprocess.TimeoutExpired:
3276 pass
3277
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003278
Victor Stinner937ee9e2018-06-26 02:11:06 +02003279@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00003280class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00003281
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003282 def test_startupinfo(self):
3283 # startupinfo argument
3284 # We uses hardcoded constants, because we do not want to
3285 # depend on win32all.
3286 STARTF_USESHOWWINDOW = 1
3287 SW_MAXIMIZE = 3
3288 startupinfo = subprocess.STARTUPINFO()
3289 startupinfo.dwFlags = STARTF_USESHOWWINDOW
3290 startupinfo.wShowWindow = SW_MAXIMIZE
3291 # Since Python is a console process, it won't be affected
3292 # by wShowWindow, but the argument should be silently
3293 # ignored
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003294 subprocess.call(ZERO_RETURN_CMD,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003295 startupinfo=startupinfo)
3296
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05303297 def test_startupinfo_keywords(self):
3298 # startupinfo argument
3299 # We use hardcoded constants, because we do not want to
3300 # depend on win32all.
3301 STARTF_USERSHOWWINDOW = 1
3302 SW_MAXIMIZE = 3
3303 startupinfo = subprocess.STARTUPINFO(
3304 dwFlags=STARTF_USERSHOWWINDOW,
3305 wShowWindow=SW_MAXIMIZE
3306 )
3307 # Since Python is a console process, it won't be affected
3308 # by wShowWindow, but the argument should be silently
3309 # ignored
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003310 subprocess.call(ZERO_RETURN_CMD,
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05303311 startupinfo=startupinfo)
3312
Victor Stinner483422f2018-07-05 22:54:17 +02003313 def test_startupinfo_copy(self):
3314 # bpo-34044: Popen must not modify input STARTUPINFO structure
3315 startupinfo = subprocess.STARTUPINFO()
3316 startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
3317 startupinfo.wShowWindow = subprocess.SW_HIDE
3318
3319 # Call Popen() twice with the same startupinfo object to make sure
3320 # that it's not modified
3321 for _ in range(2):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003322 cmd = ZERO_RETURN_CMD
Victor Stinner483422f2018-07-05 22:54:17 +02003323 with open(os.devnull, 'w') as null:
3324 proc = subprocess.Popen(cmd,
3325 stdout=null,
3326 stderr=subprocess.STDOUT,
3327 startupinfo=startupinfo)
3328 with proc:
3329 proc.communicate()
3330 self.assertEqual(proc.returncode, 0)
3331
3332 self.assertEqual(startupinfo.dwFlags,
3333 subprocess.STARTF_USESHOWWINDOW)
3334 self.assertIsNone(startupinfo.hStdInput)
3335 self.assertIsNone(startupinfo.hStdOutput)
3336 self.assertIsNone(startupinfo.hStdError)
3337 self.assertEqual(startupinfo.wShowWindow, subprocess.SW_HIDE)
3338 self.assertEqual(startupinfo.lpAttributeList, {"handle_list": []})
3339
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003340 def test_creationflags(self):
3341 # creationflags argument
3342 CREATE_NEW_CONSOLE = 16
3343 sys.stderr.write(" a DOS box should flash briefly ...\n")
3344 subprocess.call(sys.executable +
3345 ' -c "import time; time.sleep(0.25)"',
3346 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003347
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003348 def test_invalid_args(self):
3349 # invalid arguments should raise ValueError
3350 self.assertRaises(ValueError, subprocess.call,
3351 [sys.executable, "-c",
3352 "import sys; sys.exit(47)"],
3353 preexec_fn=lambda: 1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003354
Oren Milman0b3a87e2017-09-14 22:30:28 +03003355 @support.cpython_only
3356 def test_issue31471(self):
3357 # There shouldn't be an assertion failure in Popen() in case the env
3358 # argument has a bad keys() method.
3359 class BadEnv(dict):
3360 keys = None
3361 with self.assertRaises(TypeError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003362 subprocess.Popen(ZERO_RETURN_CMD, env=BadEnv())
Oren Milman0b3a87e2017-09-14 22:30:28 +03003363
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003364 def test_close_fds(self):
3365 # close file descriptors
3366 rc = subprocess.call([sys.executable, "-c",
3367 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003368 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003369 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003370
Segev Finerb2a60832017-12-18 11:28:19 +02003371 def test_close_fds_with_stdio(self):
3372 import msvcrt
3373
3374 fds = os.pipe()
3375 self.addCleanup(os.close, fds[0])
3376 self.addCleanup(os.close, fds[1])
3377
3378 handles = []
3379 for fd in fds:
3380 os.set_inheritable(fd, True)
3381 handles.append(msvcrt.get_osfhandle(fd))
3382
3383 p = subprocess.Popen([sys.executable, "-c",
3384 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3385 stdout=subprocess.PIPE, close_fds=False)
3386 stdout, stderr = p.communicate()
3387 self.assertEqual(p.returncode, 0)
3388 int(stdout.strip()) # Check that stdout is an integer
3389
3390 p = subprocess.Popen([sys.executable, "-c",
3391 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3392 stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
3393 stdout, stderr = p.communicate()
3394 self.assertEqual(p.returncode, 1)
3395 self.assertIn(b"OSError", stderr)
3396
3397 # The same as the previous call, but with an empty handle_list
3398 handle_list = []
3399 startupinfo = subprocess.STARTUPINFO()
3400 startupinfo.lpAttributeList = {"handle_list": handle_list}
3401 p = subprocess.Popen([sys.executable, "-c",
3402 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3403 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3404 startupinfo=startupinfo, close_fds=True)
3405 stdout, stderr = p.communicate()
3406 self.assertEqual(p.returncode, 1)
3407 self.assertIn(b"OSError", stderr)
3408
3409 # Check for a warning due to using handle_list and close_fds=False
Hai Shi0c4f0f32020-06-30 21:46:31 +08003410 with warnings_helper.check_warnings((".*overriding close_fds",
3411 RuntimeWarning)):
Segev Finerb2a60832017-12-18 11:28:19 +02003412 startupinfo = subprocess.STARTUPINFO()
3413 startupinfo.lpAttributeList = {"handle_list": handles[:]}
3414 p = subprocess.Popen([sys.executable, "-c",
3415 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3416 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3417 startupinfo=startupinfo, close_fds=False)
3418 stdout, stderr = p.communicate()
3419 self.assertEqual(p.returncode, 0)
3420
3421 def test_empty_attribute_list(self):
3422 startupinfo = subprocess.STARTUPINFO()
3423 startupinfo.lpAttributeList = {}
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003424 subprocess.call(ZERO_RETURN_CMD,
Segev Finerb2a60832017-12-18 11:28:19 +02003425 startupinfo=startupinfo)
3426
3427 def test_empty_handle_list(self):
3428 startupinfo = subprocess.STARTUPINFO()
3429 startupinfo.lpAttributeList = {"handle_list": []}
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003430 subprocess.call(ZERO_RETURN_CMD,
Segev Finerb2a60832017-12-18 11:28:19 +02003431 startupinfo=startupinfo)
3432
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003433 def test_shell_sequence(self):
3434 # Run command through the shell (sequence)
3435 newenv = os.environ.copy()
3436 newenv["FRUIT"] = "physalis"
3437 p = subprocess.Popen(["set"], shell=1,
3438 stdout=subprocess.PIPE,
3439 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003440 with p:
3441 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00003442
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003443 def test_shell_string(self):
3444 # Run command through the shell (string)
3445 newenv = os.environ.copy()
3446 newenv["FRUIT"] = "physalis"
3447 p = subprocess.Popen("set", shell=1,
3448 stdout=subprocess.PIPE,
3449 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003450 with p:
3451 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003452
Steve Dower050acae2016-09-06 20:16:17 -07003453 def test_shell_encodings(self):
3454 # Run command through the shell (string)
3455 for enc in ['ansi', 'oem']:
3456 newenv = os.environ.copy()
3457 newenv["FRUIT"] = "physalis"
3458 p = subprocess.Popen("set", shell=1,
3459 stdout=subprocess.PIPE,
3460 env=newenv,
3461 encoding=enc)
3462 with p:
3463 self.assertIn("physalis", p.stdout.read(), enc)
3464
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003465 def test_call_string(self):
3466 # call() function with string argument on Windows
3467 rc = subprocess.call(sys.executable +
3468 ' -c "import sys; sys.exit(47)"')
3469 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003470
Florent Xicluna4886d242010-03-08 13:27:26 +00003471 def _kill_process(self, method, *args):
3472 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00003473 p = subprocess.Popen([sys.executable, "-c", """if 1:
3474 import sys, time
3475 sys.stdout.write('x\\n')
3476 sys.stdout.flush()
3477 time.sleep(30)
3478 """],
3479 stdin=subprocess.PIPE,
3480 stdout=subprocess.PIPE,
3481 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003482 with p:
3483 # Wait for the interpreter to be completely initialized before
3484 # sending any signal.
3485 p.stdout.read(1)
3486 getattr(p, method)(*args)
3487 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01003488 self.assertEqual(stderr, b'')
Victor Stinner7438c612016-05-20 12:43:15 +02003489 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00003490 self.assertNotEqual(returncode, 0)
3491
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003492 def _kill_dead_process(self, method, *args):
3493 p = subprocess.Popen([sys.executable, "-c", """if 1:
3494 import sys, time
3495 sys.stdout.write('x\\n')
3496 sys.stdout.flush()
3497 sys.exit(42)
3498 """],
3499 stdin=subprocess.PIPE,
3500 stdout=subprocess.PIPE,
3501 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003502 with p:
3503 # Wait for the interpreter to be completely initialized before
3504 # sending any signal.
3505 p.stdout.read(1)
3506 # The process should end after this
3507 time.sleep(1)
3508 # This shouldn't raise even though the child is now dead
3509 getattr(p, method)(*args)
3510 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01003511 self.assertEqual(stderr, b'')
Victor Stinner7438c612016-05-20 12:43:15 +02003512 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003513 self.assertEqual(rc, 42)
3514
Florent Xicluna4886d242010-03-08 13:27:26 +00003515 def test_send_signal(self):
3516 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00003517
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003518 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003519 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00003520
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003521 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003522 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00003523
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003524 def test_send_signal_dead(self):
3525 self._kill_dead_process('send_signal', signal.SIGTERM)
3526
3527 def test_kill_dead(self):
3528 self._kill_dead_process('kill')
3529
3530 def test_terminate_dead(self):
3531 self._kill_dead_process('terminate')
3532
Martin Panter23172bd2016-04-16 11:28:10 +00003533class MiscTests(unittest.TestCase):
Gregory P. Smithf4d644f2018-01-29 21:27:39 -08003534
3535 class RecordingPopen(subprocess.Popen):
3536 """A Popen that saves a reference to each instance for testing."""
3537 instances_created = []
3538
3539 def __init__(self, *args, **kwargs):
3540 super().__init__(*args, **kwargs)
3541 self.instances_created.append(self)
3542
3543 @mock.patch.object(subprocess.Popen, "_communicate")
3544 def _test_keyboardinterrupt_no_kill(self, popener, mock__communicate,
3545 **kwargs):
3546 """Fake a SIGINT happening during Popen._communicate() and ._wait().
3547
3548 This avoids the need to actually try and get test environments to send
3549 and receive signals reliably across platforms. The net effect of a ^C
3550 happening during a blocking subprocess execution which we want to clean
3551 up from is a KeyboardInterrupt coming out of communicate() or wait().
3552 """
3553
3554 mock__communicate.side_effect = KeyboardInterrupt
3555 try:
3556 with mock.patch.object(subprocess.Popen, "_wait") as mock__wait:
3557 # We patch out _wait() as no signal was involved so the
3558 # child process isn't actually going to exit rapidly.
3559 mock__wait.side_effect = KeyboardInterrupt
3560 with mock.patch.object(subprocess, "Popen",
3561 self.RecordingPopen):
3562 with self.assertRaises(KeyboardInterrupt):
3563 popener([sys.executable, "-c",
3564 "import time\ntime.sleep(9)\nimport sys\n"
3565 "sys.stderr.write('\\n!runaway child!\\n')"],
3566 stdout=subprocess.DEVNULL, **kwargs)
3567 for call in mock__wait.call_args_list[1:]:
3568 self.assertNotEqual(
3569 call, mock.call(timeout=None),
3570 "no open-ended wait() after the first allowed: "
3571 f"{mock__wait.call_args_list}")
3572 sigint_calls = []
3573 for call in mock__wait.call_args_list:
3574 if call == mock.call(timeout=0.25): # from Popen.__init__
3575 sigint_calls.append(call)
3576 self.assertLessEqual(mock__wait.call_count, 2,
3577 msg=mock__wait.call_args_list)
3578 self.assertEqual(len(sigint_calls), 1,
3579 msg=mock__wait.call_args_list)
3580 finally:
3581 # cleanup the forgotten (due to our mocks) child process
3582 process = self.RecordingPopen.instances_created.pop()
3583 process.kill()
3584 process.wait()
3585 self.assertEqual([], self.RecordingPopen.instances_created)
3586
3587 def test_call_keyboardinterrupt_no_kill(self):
3588 self._test_keyboardinterrupt_no_kill(subprocess.call, timeout=6.282)
3589
3590 def test_run_keyboardinterrupt_no_kill(self):
3591 self._test_keyboardinterrupt_no_kill(subprocess.run, timeout=6.282)
3592
3593 def test_context_manager_keyboardinterrupt_no_kill(self):
3594 def popen_via_context_manager(*args, **kwargs):
3595 with subprocess.Popen(*args, **kwargs) as unused_process:
3596 raise KeyboardInterrupt # Test how __exit__ handles ^C.
3597 self._test_keyboardinterrupt_no_kill(popen_via_context_manager)
3598
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003599 def test_getoutput(self):
3600 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
3601 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
3602 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00003603
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003604 # we use mkdtemp in the next line to create an empty directory
3605 # under our exclusive control; from that, we can invent a pathname
3606 # that we _know_ won't exist. This is guaranteed to fail.
3607 dir = None
3608 try:
3609 dir = tempfile.mkdtemp()
3610 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00003611 status, output = subprocess.getstatusoutput(
Victor Stinner937ee9e2018-06-26 02:11:06 +02003612 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003613 self.assertNotEqual(status, 0)
3614 finally:
3615 if dir is not None:
3616 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00003617
Gregory P. Smithace55862015-04-07 15:57:54 -07003618 def test__all__(self):
3619 """Ensure that __all__ is populated properly."""
Ruben Vorderman23c0fb82020-10-20 01:30:02 +02003620 intentionally_excluded = {"list2cmdline", "Handle", "pwd", "grp", "fcntl"}
Gregory P. Smithace55862015-04-07 15:57:54 -07003621 exported = set(subprocess.__all__)
3622 possible_exports = set()
3623 import types
3624 for name, value in subprocess.__dict__.items():
3625 if name.startswith('_'):
3626 continue
3627 if isinstance(value, (types.ModuleType,)):
3628 continue
3629 possible_exports.add(name)
3630 self.assertEqual(exported, possible_exports - intentionally_excluded)
3631
3632
Martin Panter23172bd2016-04-16 11:28:10 +00003633@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
3634 "Test needs selectors.PollSelector")
3635class ProcessTestCaseNoPoll(ProcessTestCase):
3636 def setUp(self):
3637 self.orig_selector = subprocess._PopenSelector
3638 subprocess._PopenSelector = selectors.SelectSelector
3639 ProcessTestCase.setUp(self)
3640
3641 def tearDown(self):
3642 subprocess._PopenSelector = self.orig_selector
3643 ProcessTestCase.tearDown(self)
3644
Gregory P. Smithd06fa472009-07-04 02:46:54 +00003645
Victor Stinner937ee9e2018-06-26 02:11:06 +02003646@unittest.skipUnless(mswindows, "Windows-specific tests")
Tim Golden126c2962010-08-11 14:20:40 +00003647class CommandsWithSpaces (BaseTestCase):
3648
3649 def setUp(self):
3650 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03003651 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00003652 self.fname = fname.lower ()
3653 os.write(f, b"import sys;"
3654 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
3655 )
3656 os.close(f)
3657
3658 def tearDown(self):
3659 os.remove(self.fname)
3660 super().tearDown()
3661
3662 def with_spaces(self, *args, **kwargs):
3663 kwargs['stdout'] = subprocess.PIPE
3664 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02003665 with p:
3666 self.assertEqual(
3667 p.stdout.read ().decode("mbcs"),
3668 "2 [%r, 'ab cd']" % self.fname
3669 )
Tim Golden126c2962010-08-11 14:20:40 +00003670
3671 def test_shell_string_with_spaces(self):
3672 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003673 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3674 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003675
3676 def test_shell_sequence_with_spaces(self):
3677 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003678 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003679
3680 def test_noshell_string_with_spaces(self):
3681 # call() function with string argument with spaces on Windows
3682 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3683 "ab cd"))
3684
3685 def test_noshell_sequence_with_spaces(self):
3686 # call() function with sequence argument with spaces on Windows
3687 self.with_spaces([sys.executable, self.fname, "ab cd"])
3688
Brian Curtin79cdb662010-12-03 02:46:02 +00003689
Georg Brandla86b2622012-02-20 21:34:57 +01003690class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00003691
3692 def test_pipe(self):
3693 with subprocess.Popen([sys.executable, "-c",
3694 "import sys;"
3695 "sys.stdout.write('stdout');"
3696 "sys.stderr.write('stderr');"],
3697 stdout=subprocess.PIPE,
3698 stderr=subprocess.PIPE) as proc:
3699 self.assertEqual(proc.stdout.read(), b"stdout")
Victor Stinner6cac1132019-12-08 08:38:16 +01003700 self.assertEqual(proc.stderr.read(), b"stderr")
Brian Curtin79cdb662010-12-03 02:46:02 +00003701
3702 self.assertTrue(proc.stdout.closed)
3703 self.assertTrue(proc.stderr.closed)
3704
3705 def test_returncode(self):
3706 with subprocess.Popen([sys.executable, "-c",
3707 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07003708 pass
3709 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00003710 self.assertEqual(proc.returncode, 100)
3711
3712 def test_communicate_stdin(self):
3713 with subprocess.Popen([sys.executable, "-c",
3714 "import sys;"
3715 "sys.exit(sys.stdin.read() == 'context')"],
3716 stdin=subprocess.PIPE) as proc:
3717 proc.communicate(b"context")
3718 self.assertEqual(proc.returncode, 1)
3719
3720 def test_invalid_args(self):
Victor Stinnerb31206a2018-01-25 19:06:05 +01003721 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02003722 with subprocess.Popen(NONEXISTING_CMD,
Brian Curtin79cdb662010-12-03 02:46:02 +00003723 stdout=subprocess.PIPE,
3724 stderr=subprocess.PIPE) as proc:
3725 pass
3726
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003727 def test_broken_pipe_cleanup(self):
3728 """Broken pipe error should not prevent wait() (Issue 21619)"""
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003729 proc = subprocess.Popen(ZERO_RETURN_CMD,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003730 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003731 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003732 proc = proc.__enter__()
3733 # Prepare to send enough data to overflow any OS pipe buffering and
3734 # guarantee a broken pipe error. Data is held in BufferedWriter
3735 # buffer until closed.
3736 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003737 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003738 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02003739 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003740 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003741 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003742
Brian Curtin79cdb662010-12-03 02:46:02 +00003743
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003744if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04003745 unittest.main()