blob: 8b576c036ef0d2f4ee3891abc4d867c3ad760800 [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
Georg Brandlf9734072008-12-07 15:30:06 +0000207 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300208 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000209 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000210 output = subprocess.check_output(
211 [sys.executable, "-c", "print('will not be run')"],
212 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000213 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000214 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000215
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300216 def test_check_output_stdin_with_input_arg(self):
217 # check_output() refuses to accept 'stdin' with 'input'
218 tf = tempfile.TemporaryFile()
219 self.addCleanup(tf.close)
220 tf.write(b'pear')
221 tf.seek(0)
222 with self.assertRaises(ValueError) as c:
223 output = subprocess.check_output(
224 [sys.executable, "-c", "print('will not be run')"],
225 stdin=tf, input=b'hare')
226 self.fail("Expected ValueError when stdin and input args supplied.")
227 self.assertIn('stdin', c.exception.args[0])
228 self.assertIn('input', c.exception.args[0])
229
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400230 def test_check_output_timeout(self):
231 # check_output() function with timeout arg
232 with self.assertRaises(subprocess.TimeoutExpired) as c:
233 output = subprocess.check_output(
234 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200235 "import sys, time\n"
236 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400237 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200238 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400239 # Some heavily loaded buildbots (sparc Debian 3.x) require
240 # this much time to start and print.
241 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400242 self.fail("Expected TimeoutExpired.")
243 self.assertEqual(c.exception.output, b'BDFL')
244
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000245 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000246 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000247 newenv = os.environ.copy()
248 newenv["FRUIT"] = "banana"
249 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000250 'import sys, os;'
251 'sys.exit(os.getenv("FRUIT")=="banana")'],
252 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000253 self.assertEqual(rc, 1)
254
Victor Stinner87b9bc32011-06-01 00:57:47 +0200255 def test_invalid_args(self):
256 # Popen() called with invalid arguments should raise TypeError
257 # but Popen.__del__ should not complain (issue #12085)
258 with support.captured_stderr() as s:
259 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
260 argcount = subprocess.Popen.__init__.__code__.co_argcount
261 too_many_args = [0] * (argcount + 1)
262 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
263 self.assertEqual(s.getvalue(), '')
264
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000265 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000266 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000267 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000268 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000269 self.addCleanup(p.stdout.close)
270 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000271 p.wait()
272 self.assertEqual(p.stdin, None)
273
274 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200275 # .stdout is None when not redirected, and the child's stdout will
276 # be inherited from the parent. In order to test this we run a
277 # subprocess in a subprocess:
278 # this_test
279 # \-- subprocess created by this test (parent)
280 # \-- subprocess created by the parent subprocess (child)
281 # The parent doesn't specify stdout, so the child will use the
282 # parent's stdout. This test checks that the message printed by the
283 # child goes to the parent stdout. The parent also checks that the
284 # child's stdout is None. See #11963.
285 code = ('import sys; from subprocess import Popen, PIPE;'
286 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
287 ' stdin=PIPE, stderr=PIPE);'
288 'p.wait(); assert p.stdout is None;')
289 p = subprocess.Popen([sys.executable, "-c", code],
290 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
291 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000292 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200293 out, err = p.communicate()
294 self.assertEqual(p.returncode, 0, err)
295 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000296
297 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000298 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000299 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000300 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000301 self.addCleanup(p.stdout.close)
302 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000303 p.wait()
304 self.assertEqual(p.stderr, None)
305
Chris Jerdonek776cb192012-10-08 15:56:43 -0700306 def _assert_python(self, pre_args, **kwargs):
307 # We include sys.exit() to prevent the test runner from hanging
308 # whenever python is found.
309 args = pre_args + ["import sys; sys.exit(47)"]
310 p = subprocess.Popen(args, **kwargs)
311 p.wait()
312 self.assertEqual(47, p.returncode)
313
314 def test_executable(self):
315 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700316 #
317 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
318 # determine where its standard library is, so we need the directory
319 # of args[0] to be valid for the Popen() call to Python to succeed.
320 # See also issue #16170 and issue #7774.
321 doesnotexist = os.path.join(os.path.dirname(sys.executable),
322 "doesnotexist")
323 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700324
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300325 def test_bytes_executable(self):
326 doesnotexist = os.path.join(os.path.dirname(sys.executable),
327 "doesnotexist")
328 self._assert_python([doesnotexist, "-c"],
329 executable=os.fsencode(sys.executable))
330
331 def test_pathlike_executable(self):
332 doesnotexist = os.path.join(os.path.dirname(sys.executable),
333 "doesnotexist")
334 self._assert_python([doesnotexist, "-c"],
335 executable=FakePath(sys.executable))
336
Chris Jerdonek776cb192012-10-08 15:56:43 -0700337 def test_executable_takes_precedence(self):
338 # Check that the executable argument takes precedence over args[0].
339 #
340 # Verify first that the call succeeds without the executable arg.
341 pre_args = [sys.executable, "-c"]
342 self._assert_python(pre_args)
Victor Stinnerb31206a2018-01-25 19:06:05 +0100343 self.assertRaises(NONEXISTING_ERRORS,
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +0100344 self._assert_python, pre_args,
Victor Stinnerb31206a2018-01-25 19:06:05 +0100345 executable=NONEXISTING_CMD[0])
Chris Jerdonek776cb192012-10-08 15:56:43 -0700346
Victor Stinner937ee9e2018-06-26 02:11:06 +0200347 @unittest.skipIf(mswindows, "executable argument replaces shell")
Chris Jerdonek776cb192012-10-08 15:56:43 -0700348 def test_executable_replaces_shell(self):
349 # Check that the executable argument replaces the default shell
350 # when shell=True.
351 self._assert_python([], executable=sys.executable, shell=True)
352
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300353 @unittest.skipIf(mswindows, "executable argument replaces shell")
354 def test_bytes_executable_replaces_shell(self):
355 self._assert_python([], executable=os.fsencode(sys.executable),
356 shell=True)
357
358 @unittest.skipIf(mswindows, "executable argument replaces shell")
359 def test_pathlike_executable_replaces_shell(self):
360 self._assert_python([], executable=FakePath(sys.executable),
361 shell=True)
362
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700363 # For use in the test_cwd* tests below.
364 def _normalize_cwd(self, cwd):
365 # Normalize an expected cwd (for Tru64 support).
366 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
367 # strings. See bug #1063571.
Hai Shi0c4f0f32020-06-30 21:46:31 +0800368 with os_helper.change_cwd(cwd):
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300369 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700370
371 # For use in the test_cwd* tests below.
372 def _split_python_path(self):
373 # Return normalized (python_dir, python_base).
374 python_path = os.path.realpath(sys.executable)
375 return os.path.split(python_path)
376
377 # For use in the test_cwd* tests below.
378 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
379 # Invoke Python via Popen, and assert that (1) the call succeeds,
380 # and that (2) the current working directory of the child process
381 # matches *expected_cwd*.
382 p = subprocess.Popen([python_arg, "-c",
383 "import os, sys; "
Serhiy Storchakab1a87302020-07-26 10:21:39 +0300384 "buf = sys.stdout.buffer; "
385 "buf.write(os.getcwd().encode()); "
386 "buf.flush(); "
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700387 "sys.exit(47)"],
388 stdout=subprocess.PIPE,
389 **kwargs)
390 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000391 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700392 self.assertEqual(47, p.returncode)
393 normcase = os.path.normcase
394 self.assertEqual(normcase(expected_cwd),
Serhiy Storchakab1a87302020-07-26 10:21:39 +0300395 normcase(p.stdout.read().decode()))
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700396
397 def test_cwd(self):
398 # Check that cwd changes the cwd for the child process.
399 temp_dir = tempfile.gettempdir()
400 temp_dir = self._normalize_cwd(temp_dir)
401 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
402
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +0300403 def test_cwd_with_bytes(self):
404 temp_dir = tempfile.gettempdir()
405 temp_dir = self._normalize_cwd(temp_dir)
406 self._assert_cwd(temp_dir, sys.executable, cwd=os.fsencode(temp_dir))
407
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530408 def test_cwd_with_pathlike(self):
409 temp_dir = tempfile.gettempdir()
410 temp_dir = self._normalize_cwd(temp_dir)
Serhiy Storchakab21d1552018-03-02 11:53:51 +0200411 self._assert_cwd(temp_dir, sys.executable, cwd=FakePath(temp_dir))
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530412
Victor Stinner937ee9e2018-06-26 02:11:06 +0200413 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700414 def test_cwd_with_relative_arg(self):
415 # Check that Popen looks for args[0] relative to cwd if args[0]
416 # is relative.
417 python_dir, python_base = self._split_python_path()
418 rel_python = os.path.join(os.curdir, python_base)
Hai Shi0c4f0f32020-06-30 21:46:31 +0800419 with os_helper.temp_cwd() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700420 # Before calling with the correct cwd, confirm that the call fails
421 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700422 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700423 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700424 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700425 [rel_python], cwd=wrong_dir)
426 python_dir = self._normalize_cwd(python_dir)
427 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
428
Victor Stinner937ee9e2018-06-26 02:11:06 +0200429 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700430 def test_cwd_with_relative_executable(self):
431 # Check that Popen looks for executable relative to cwd if executable
432 # is relative (and that executable takes precedence over args[0]).
433 python_dir, python_base = self._split_python_path()
434 rel_python = os.path.join(os.curdir, python_base)
435 doesntexist = "somethingyoudonthave"
Hai Shi0c4f0f32020-06-30 21:46:31 +0800436 with os_helper.temp_cwd() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700437 # Before calling with the correct cwd, confirm that the call fails
438 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700439 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700440 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700441 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700442 [doesntexist], executable=rel_python,
443 cwd=wrong_dir)
444 python_dir = self._normalize_cwd(python_dir)
445 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
446 cwd=python_dir)
447
448 def test_cwd_with_absolute_arg(self):
449 # Check that Popen can find the executable when the cwd is wrong
450 # if args[0] is an absolute path.
451 python_dir, python_base = self._split_python_path()
452 abs_python = os.path.join(python_dir, python_base)
453 rel_python = os.path.join(os.curdir, python_base)
Hai Shi0c4f0f32020-06-30 21:46:31 +0800454 with os_helper.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700455 # Before calling with an absolute path, confirm that using a
456 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700457 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700458 [rel_python], cwd=wrong_dir)
459 wrong_dir = self._normalize_cwd(wrong_dir)
460 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
461
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100462 @unittest.skipIf(sys.base_prefix != sys.prefix,
463 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000464 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700465 python_dir, python_base = self._split_python_path()
466 python_dir = self._normalize_cwd(python_dir)
467 self._assert_cwd(python_dir, "somethingyoudonthave",
468 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000469
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100470 @unittest.skipIf(sys.base_prefix != sys.prefix,
471 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000472 @unittest.skipIf(sysconfig.is_python_build(),
473 "need an installed Python. See #7774")
474 def test_executable_without_cwd(self):
475 # For a normal installation, it should work without 'cwd'
476 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700477 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
478 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000479
480 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000481 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000482 p = subprocess.Popen([sys.executable, "-c",
483 'import sys; sys.exit(sys.stdin.read() == "pear")'],
484 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000485 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000486 p.stdin.close()
487 p.wait()
488 self.assertEqual(p.returncode, 1)
489
490 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000491 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000492 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000493 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000494 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000495 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000496 os.lseek(d, 0, 0)
497 p = subprocess.Popen([sys.executable, "-c",
498 'import sys; sys.exit(sys.stdin.read() == "pear")'],
499 stdin=d)
500 p.wait()
501 self.assertEqual(p.returncode, 1)
502
503 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000504 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000505 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000506 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000507 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000508 tf.seek(0)
509 p = subprocess.Popen([sys.executable, "-c",
510 'import sys; sys.exit(sys.stdin.read() == "pear")'],
511 stdin=tf)
512 p.wait()
513 self.assertEqual(p.returncode, 1)
514
515 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000516 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000517 p = subprocess.Popen([sys.executable, "-c",
518 'import sys; sys.stdout.write("orange")'],
519 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200520 with p:
521 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000522
523 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000524 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000525 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000526 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000527 d = tf.fileno()
528 p = subprocess.Popen([sys.executable, "-c",
529 'import sys; sys.stdout.write("orange")'],
530 stdout=d)
531 p.wait()
532 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000533 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000534
535 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000536 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000537 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000538 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000539 p = subprocess.Popen([sys.executable, "-c",
540 'import sys; sys.stdout.write("orange")'],
541 stdout=tf)
542 p.wait()
543 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000544 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000545
546 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000547 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000548 p = subprocess.Popen([sys.executable, "-c",
549 'import sys; sys.stderr.write("strawberry")'],
550 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200551 with p:
Victor Stinner6cac1132019-12-08 08:38:16 +0100552 self.assertEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000553
554 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000555 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000556 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000557 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000558 d = tf.fileno()
559 p = subprocess.Popen([sys.executable, "-c",
560 'import sys; sys.stderr.write("strawberry")'],
561 stderr=d)
562 p.wait()
563 os.lseek(d, 0, 0)
Victor Stinner6cac1132019-12-08 08:38:16 +0100564 self.assertEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000565
566 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000567 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000568 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000569 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000570 p = subprocess.Popen([sys.executable, "-c",
571 'import sys; sys.stderr.write("strawberry")'],
572 stderr=tf)
573 p.wait()
574 tf.seek(0)
Victor Stinner6cac1132019-12-08 08:38:16 +0100575 self.assertEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000576
Martin Panterc7635892016-05-13 01:54:44 +0000577 def test_stderr_redirect_with_no_stdout_redirect(self):
578 # test stderr=STDOUT while stdout=None (not set)
579
580 # - grandchild prints to stderr
581 # - child redirects grandchild's stderr to its stdout
582 # - the parent should get grandchild's stderr in child's stdout
583 p = subprocess.Popen([sys.executable, "-c",
584 'import sys, subprocess;'
585 'rc = subprocess.call([sys.executable, "-c",'
586 ' "import sys;"'
587 ' "sys.stderr.write(\'42\')"],'
588 ' stderr=subprocess.STDOUT);'
589 'sys.exit(rc)'],
590 stdout=subprocess.PIPE,
591 stderr=subprocess.PIPE)
592 stdout, stderr = p.communicate()
593 #NOTE: stdout should get stderr from grandchild
Victor Stinner6cac1132019-12-08 08:38:16 +0100594 self.assertEqual(stdout, b'42')
595 self.assertEqual(stderr, b'') # should be empty
Martin Panterc7635892016-05-13 01:54:44 +0000596 self.assertEqual(p.returncode, 0)
597
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000598 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000599 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000600 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000601 'import sys;'
602 'sys.stdout.write("apple");'
603 'sys.stdout.flush();'
604 'sys.stderr.write("orange")'],
605 stdout=subprocess.PIPE,
606 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200607 with p:
Victor Stinner6cac1132019-12-08 08:38:16 +0100608 self.assertEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000609
610 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000611 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000612 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000613 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000614 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000615 'import sys;'
616 'sys.stdout.write("apple");'
617 'sys.stdout.flush();'
618 'sys.stderr.write("orange")'],
619 stdout=tf,
620 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000621 p.wait()
622 tf.seek(0)
Victor Stinner6cac1132019-12-08 08:38:16 +0100623 self.assertEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000624
Thomas Wouters89f507f2006-12-13 04:49:30 +0000625 def test_stdout_filedes_of_stdout(self):
626 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200627 # To avoid printing the text on stdout, we do something similar to
628 # test_stdout_none (see above). The parent subprocess calls the child
629 # subprocess passing stdout=1, and this test uses stdout=PIPE in
630 # order to capture and check the output of the parent. See #11963.
631 code = ('import sys, subprocess; '
632 'rc = subprocess.call([sys.executable, "-c", '
633 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
634 'b\'test with stdout=1\'))"], stdout=1); '
635 'assert rc == 18')
636 p = subprocess.Popen([sys.executable, "-c", code],
637 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
638 self.addCleanup(p.stdout.close)
639 self.addCleanup(p.stderr.close)
640 out, err = p.communicate()
641 self.assertEqual(p.returncode, 0, err)
642 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000643
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200644 def test_stdout_devnull(self):
645 p = subprocess.Popen([sys.executable, "-c",
646 'for i in range(10240):'
647 'print("x" * 1024)'],
648 stdout=subprocess.DEVNULL)
649 p.wait()
650 self.assertEqual(p.stdout, None)
651
652 def test_stderr_devnull(self):
653 p = subprocess.Popen([sys.executable, "-c",
654 'import sys\n'
655 'for i in range(10240):'
656 'sys.stderr.write("x" * 1024)'],
657 stderr=subprocess.DEVNULL)
658 p.wait()
659 self.assertEqual(p.stderr, None)
660
661 def test_stdin_devnull(self):
662 p = subprocess.Popen([sys.executable, "-c",
663 'import sys;'
664 'sys.stdin.read(1)'],
665 stdin=subprocess.DEVNULL)
666 p.wait()
667 self.assertEqual(p.stdin, None)
668
Ruben Vorderman23c0fb82020-10-20 01:30:02 +0200669 def test_pipesizes(self):
670 # stdin redirection
671 pipesize = 16 * 1024
672 p = subprocess.Popen([sys.executable, "-c",
673 'import sys; sys.stdin.read(); sys.stdout.write("out"); sys.stderr.write("error!")'],
674 stdin=subprocess.PIPE,
675 stdout=subprocess.PIPE,
676 stderr=subprocess.PIPE,
677 pipesize=pipesize)
678 # We only assert pipe size has changed on platforms that support it.
679 if sys.platform != "win32" and hasattr(fcntl, "F_GETPIPE_SZ"):
680 for fifo in [p.stdin, p.stdout, p.stderr]:
681 self.assertEqual(fcntl.fcntl(fifo.fileno(), fcntl.F_GETPIPE_SZ), pipesize)
682 # Windows pipe size can be acquired with the GetNamedPipeInfoFunction
683 # https://docs.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-getnamedpipeinfo
684 # However, this function is not yet in _winapi.
685 p.stdin.write(b"pear")
686 p.stdin.close()
687 p.wait()
688
689 def test_pipesize_default(self):
690 p = subprocess.Popen([sys.executable, "-c",
691 'import sys; sys.stdin.read(); sys.stdout.write("out");'
692 ' sys.stderr.write("error!")'],
693 stdin=subprocess.PIPE,
694 stdout=subprocess.PIPE,
695 stderr=subprocess.PIPE,
696 pipesize=-1)
697 # UNIX tests using fcntl
698 if sys.platform != "win32" and hasattr(fcntl, "F_GETPIPE_SZ"):
699 fp_r, fp_w = os.pipe()
700 default_pipesize = fcntl.fcntl(fp_w, fcntl.F_GETPIPE_SZ)
701 for fifo in [p.stdin, p.stdout, p.stderr]:
702 self.assertEqual(
703 fcntl.fcntl(fifo.fileno(), fcntl.F_GETPIPE_SZ), default_pipesize)
704 # On other platforms we cannot test the pipe size (yet). But above code
705 # using pipesize=-1 should not crash.
706 p.stdin.close()
707 p.wait()
708
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000709 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000710 newenv = os.environ.copy()
711 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200712 with subprocess.Popen([sys.executable, "-c",
713 'import sys,os;'
714 'sys.stdout.write(os.getenv("FRUIT"))'],
715 stdout=subprocess.PIPE,
716 env=newenv) as p:
717 stdout, stderr = p.communicate()
718 self.assertEqual(stdout, b"orange")
719
Victor Stinner62d51182011-06-23 01:02:25 +0200720 # Windows requires at least the SYSTEMROOT environment variable to start
721 # Python
722 @unittest.skipIf(sys.platform == 'win32',
723 'cannot test an empty env on Windows')
Gregory P. Smithb3512482017-05-30 14:40:37 -0700724 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
725 'The Python shared library cannot be loaded '
726 'with an empty environment.')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200727 def test_empty_env(self):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700728 """Verify that env={} is as empty as possible."""
729
Gregory P. Smith85aba232017-05-30 16:21:47 -0700730 def is_env_var_to_ignore(n):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700731 """Determine if an environment variable is under our control."""
732 # This excludes some __CF_* and VERSIONER_* keys MacOS insists
733 # on adding even when the environment in exec is empty.
734 # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist.
Gregory P. Smith85aba232017-05-30 16:21:47 -0700735 return ('VERSIONER' in n or '__CF' in n or # MacOS
Nick Coghlan6ea41862017-06-11 13:16:15 +1000736 n == 'LD_PRELOAD' or n.startswith('SANDBOX') or # Gentoo
737 n == 'LC_CTYPE') # Locale coercion triggered
Gregory P. Smithb3512482017-05-30 14:40:37 -0700738
Victor Stinnerf1512a22011-06-21 17:18:38 +0200739 with subprocess.Popen([sys.executable, "-c",
Gregory P. Smithb3512482017-05-30 14:40:37 -0700740 'import os; print(list(os.environ.keys()))'],
741 stdout=subprocess.PIPE, env={}) as p:
Victor Stinnerf1512a22011-06-21 17:18:38 +0200742 stdout, stderr = p.communicate()
Gregory P. Smithb3512482017-05-30 14:40:37 -0700743 child_env_names = eval(stdout.strip())
744 self.assertIsInstance(child_env_names, list)
745 child_env_names = [k for k in child_env_names
746 if not is_env_var_to_ignore(k)]
747 self.assertEqual(child_env_names, [])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000748
Serhiy Storchakad174d242017-06-23 19:39:27 +0300749 def test_invalid_cmd(self):
750 # null character in the command name
751 cmd = sys.executable + '\0'
752 with self.assertRaises(ValueError):
753 subprocess.Popen([cmd, "-c", "pass"])
754
755 # null character in the command argument
756 with self.assertRaises(ValueError):
757 subprocess.Popen([sys.executable, "-c", "pass#\0"])
758
759 def test_invalid_env(self):
Ville Skyttä49b27342017-08-03 09:00:59 +0300760 # null character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300761 newenv = os.environ.copy()
762 newenv["FRUIT\0VEGETABLE"] = "cabbage"
763 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700764 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300765
Ville Skyttä49b27342017-08-03 09:00:59 +0300766 # null character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300767 newenv = os.environ.copy()
768 newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
769 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700770 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300771
Ville Skyttä49b27342017-08-03 09:00:59 +0300772 # equal character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300773 newenv = os.environ.copy()
774 newenv["FRUIT=ORANGE"] = "lemon"
775 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700776 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300777
Ville Skyttä49b27342017-08-03 09:00:59 +0300778 # equal character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300779 newenv = os.environ.copy()
780 newenv["FRUIT"] = "orange=lemon"
781 with subprocess.Popen([sys.executable, "-c",
782 'import sys, os;'
783 'sys.stdout.write(os.getenv("FRUIT"))'],
784 stdout=subprocess.PIPE,
785 env=newenv) as p:
786 stdout, stderr = p.communicate()
787 self.assertEqual(stdout, b"orange=lemon")
788
Peter Astrandcbac93c2005-03-03 20:24:28 +0000789 def test_communicate_stdin(self):
790 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000791 'import sys;'
792 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000793 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000794 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000795 self.assertEqual(p.returncode, 1)
796
797 def test_communicate_stdout(self):
798 p = subprocess.Popen([sys.executable, "-c",
799 'import sys; sys.stdout.write("pineapple")'],
800 stdout=subprocess.PIPE)
801 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000802 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000803 self.assertEqual(stderr, None)
804
805 def test_communicate_stderr(self):
806 p = subprocess.Popen([sys.executable, "-c",
807 'import sys; sys.stderr.write("pineapple")'],
808 stderr=subprocess.PIPE)
809 (stdout, stderr) = p.communicate()
810 self.assertEqual(stdout, None)
Victor Stinner6cac1132019-12-08 08:38:16 +0100811 self.assertEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000812
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000813 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000814 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000815 'import sys,os;'
816 'sys.stderr.write("pineapple");'
817 'sys.stdout.write(sys.stdin.read())'],
818 stdin=subprocess.PIPE,
819 stdout=subprocess.PIPE,
820 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000821 self.addCleanup(p.stdout.close)
822 self.addCleanup(p.stderr.close)
823 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000824 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000825 self.assertEqual(stdout, b"banana")
Victor Stinner6cac1132019-12-08 08:38:16 +0100826 self.assertEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000827
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400828 def test_communicate_timeout(self):
829 p = subprocess.Popen([sys.executable, "-c",
830 'import sys,os,time;'
831 'sys.stderr.write("pineapple\\n");'
832 'time.sleep(1);'
833 'sys.stderr.write("pear\\n");'
834 'sys.stdout.write(sys.stdin.read())'],
835 universal_newlines=True,
836 stdin=subprocess.PIPE,
837 stdout=subprocess.PIPE,
838 stderr=subprocess.PIPE)
839 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
840 timeout=0.3)
841 # Make sure we can keep waiting for it, and that we get the whole output
842 # after it completes.
843 (stdout, stderr) = p.communicate()
844 self.assertEqual(stdout, "banana")
Victor Stinner6cac1132019-12-08 08:38:16 +0100845 self.assertEqual(stderr.encode(), b"pineapple\npear\n")
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400846
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700847 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200848 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400849 p = subprocess.Popen([sys.executable, "-c",
850 'import sys,os,time;'
851 'sys.stdout.write("a" * (64 * 1024));'
852 'time.sleep(0.2);'
853 'sys.stdout.write("a" * (64 * 1024));'
854 'time.sleep(0.2);'
855 'sys.stdout.write("a" * (64 * 1024));'
856 'time.sleep(0.2);'
857 'sys.stdout.write("a" * (64 * 1024));'],
858 stdout=subprocess.PIPE)
859 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
860 (stdout, _) = p.communicate()
861 self.assertEqual(len(stdout), 4 * 64 * 1024)
862
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000863 # Test for the fd leak reported in http://bugs.python.org/issue2791.
864 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000865 for stdin_pipe in (False, True):
866 for stdout_pipe in (False, True):
867 for stderr_pipe in (False, True):
868 options = {}
869 if stdin_pipe:
870 options['stdin'] = subprocess.PIPE
871 if stdout_pipe:
872 options['stdout'] = subprocess.PIPE
873 if stderr_pipe:
874 options['stderr'] = subprocess.PIPE
875 if not options:
876 continue
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700877 p = subprocess.Popen(ZERO_RETURN_CMD, **options)
Victor Stinner667d4b52010-12-25 22:40:32 +0000878 p.communicate()
879 if p.stdin is not None:
880 self.assertTrue(p.stdin.closed)
881 if p.stdout is not None:
882 self.assertTrue(p.stdout.closed)
883 if p.stderr is not None:
884 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000885
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000886 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000887 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000888 p = subprocess.Popen([sys.executable, "-c",
889 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000890 (stdout, stderr) = p.communicate()
891 self.assertEqual(stdout, None)
892 self.assertEqual(stderr, None)
893
894 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000895 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000896 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000897 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000898 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000899 os.close(x)
900 os.close(y)
901 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000902 'import sys,os;'
903 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200904 'sys.stderr.write("x" * %d);'
905 'sys.stdout.write(sys.stdin.read())' %
906 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000907 stdin=subprocess.PIPE,
908 stdout=subprocess.PIPE,
909 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000910 self.addCleanup(p.stdout.close)
911 self.addCleanup(p.stderr.close)
912 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200913 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000914 (stdout, stderr) = p.communicate(string_to_write)
915 self.assertEqual(stdout, string_to_write)
916
917 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000918 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000919 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000920 'import sys,os;'
921 'sys.stdout.write(sys.stdin.read())'],
922 stdin=subprocess.PIPE,
923 stdout=subprocess.PIPE,
924 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000925 self.addCleanup(p.stdout.close)
926 self.addCleanup(p.stderr.close)
927 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000928 p.stdin.write(b"banana")
929 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000930 self.assertEqual(stdout, b"bananasplit")
Victor Stinner6cac1132019-12-08 08:38:16 +0100931 self.assertEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000932
andyclegg7fed7bd2017-10-23 03:01:19 +0100933 def test_universal_newlines_and_text(self):
934 args = [
935 sys.executable, "-c",
936 'import sys,os;' + SETBINARY +
937 'buf = sys.stdout.buffer;'
938 'buf.write(sys.stdin.readline().encode());'
939 'buf.flush();'
940 'buf.write(b"line2\\n");'
941 'buf.flush();'
942 'buf.write(sys.stdin.read().encode());'
943 'buf.flush();'
944 'buf.write(b"line4\\n");'
945 'buf.flush();'
946 'buf.write(b"line5\\r\\n");'
947 'buf.flush();'
948 'buf.write(b"line6\\r");'
949 'buf.flush();'
950 'buf.write(b"\\nline7");'
951 'buf.flush();'
952 'buf.write(b"\\nline8");']
953
954 for extra_kwarg in ('universal_newlines', 'text'):
955 p = subprocess.Popen(args, **{'stdin': subprocess.PIPE,
956 'stdout': subprocess.PIPE,
957 extra_kwarg: True})
958 with p:
959 p.stdin.write("line1\n")
960 p.stdin.flush()
961 self.assertEqual(p.stdout.readline(), "line1\n")
962 p.stdin.write("line3\n")
963 p.stdin.close()
964 self.addCleanup(p.stdout.close)
965 self.assertEqual(p.stdout.readline(),
966 "line2\n")
967 self.assertEqual(p.stdout.read(6),
968 "line3\n")
969 self.assertEqual(p.stdout.read(),
970 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000971
972 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000973 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000974 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000975 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200976 'buf = sys.stdout.buffer;'
977 'buf.write(b"line2\\n");'
978 'buf.flush();'
979 'buf.write(b"line4\\n");'
980 'buf.flush();'
981 'buf.write(b"line5\\r\\n");'
982 'buf.flush();'
983 'buf.write(b"line6\\r");'
984 'buf.flush();'
985 'buf.write(b"\\nline7");'
986 'buf.flush();'
987 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200988 stderr=subprocess.PIPE,
989 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000990 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000991 self.addCleanup(p.stdout.close)
992 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000993 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200994 self.assertEqual(stdout,
995 "line2\nline4\nline5\nline6\nline7\nline8")
996
997 def test_universal_newlines_communicate_stdin(self):
998 # universal newlines through communicate(), with only stdin
999 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +03001000 'import sys,os;' + SETBINARY + textwrap.dedent('''
1001 s = sys.stdin.readline()
1002 assert s == "line1\\n", repr(s)
1003 s = sys.stdin.read()
1004 assert s == "line3\\n", repr(s)
1005 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +02001006 stdin=subprocess.PIPE,
1007 universal_newlines=1)
1008 (stdout, stderr) = p.communicate("line1\nline3\n")
1009 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001010
Andrew Svetlovf3765072012-08-14 18:35:17 +03001011 def test_universal_newlines_communicate_input_none(self):
1012 # Test communicate(input=None) with universal newlines.
1013 #
1014 # We set stdout to PIPE because, as of this writing, a different
1015 # code path is tested when the number of pipes is zero or one.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001016 p = subprocess.Popen(ZERO_RETURN_CMD,
Andrew Svetlovf3765072012-08-14 18:35:17 +03001017 stdin=subprocess.PIPE,
1018 stdout=subprocess.PIPE,
1019 universal_newlines=True)
1020 p.communicate()
1021 self.assertEqual(p.returncode, 0)
1022
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001023 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +03001024 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001025 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +03001026 'import sys,os;' + SETBINARY + textwrap.dedent('''
1027 s = sys.stdin.buffer.readline()
1028 sys.stdout.buffer.write(s)
1029 sys.stdout.buffer.write(b"line2\\r")
1030 sys.stderr.buffer.write(b"eline2\\n")
1031 s = sys.stdin.buffer.read()
1032 sys.stdout.buffer.write(s)
1033 sys.stdout.buffer.write(b"line4\\n")
1034 sys.stdout.buffer.write(b"line5\\r\\n")
1035 sys.stderr.buffer.write(b"eline6\\r")
1036 sys.stderr.buffer.write(b"eline7\\r\\nz")
1037 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001038 stdin=subprocess.PIPE,
1039 stderr=subprocess.PIPE,
1040 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +03001041 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001042 self.addCleanup(p.stdout.close)
1043 self.addCleanup(p.stderr.close)
1044 (stdout, stderr) = p.communicate("line1\nline3\n")
1045 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +03001046 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001047 # Python debug build push something like "[42442 refs]\n"
1048 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +03001049 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001050
Andrew Svetlov82860712012-08-19 22:13:41 +03001051 def test_universal_newlines_communicate_encodings(self):
1052 # Check that universal newlines mode works for various encodings,
1053 # in particular for encodings in the UTF-16 and UTF-32 families.
1054 # See issue #15595.
1055 #
1056 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
1057 # without, and UTF-16 and UTF-32.
1058 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +03001059 code = ("import sys; "
1060 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
1061 encoding)
1062 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -07001063 # We set stdin to be non-None because, as of this writing,
1064 # a different code path is used when the number of pipes is
1065 # zero or one.
1066 popen = subprocess.Popen(args,
1067 stdin=subprocess.PIPE,
1068 stdout=subprocess.PIPE,
1069 encoding=encoding)
1070 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +03001071 self.assertEqual(stdout, '1\n2\n3\n4')
1072
Steve Dower050acae2016-09-06 20:16:17 -07001073 def test_communicate_errors(self):
1074 for errors, expected in [
1075 ('ignore', ''),
1076 ('replace', '\ufffd\ufffd'),
1077 ('surrogateescape', '\udc80\udc80'),
1078 ('backslashreplace', '\\x80\\x80'),
1079 ]:
1080 code = ("import sys; "
1081 r"sys.stdout.buffer.write(b'[\x80\x80]')")
1082 args = [sys.executable, '-c', code]
1083 # We set stdin to be non-None because, as of this writing,
1084 # a different code path is used when the number of pipes is
1085 # zero or one.
1086 popen = subprocess.Popen(args,
1087 stdin=subprocess.PIPE,
1088 stdout=subprocess.PIPE,
1089 encoding='utf-8',
1090 errors=errors)
1091 stdout, stderr = popen.communicate(input='')
1092 self.assertEqual(stdout, '[{}]'.format(expected))
1093
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001094 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +00001095 # Make sure we leak no resources
Victor Stinner937ee9e2018-06-26 02:11:06 +02001096 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +00001097 max_handles = 1026 # too much for most UNIX systems
1098 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +00001099 max_handles = 2050 # too much for (at least some) Windows setups
1100 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001101 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +00001102 try:
1103 for i in range(max_handles):
1104 try:
Hai Shi0c4f0f32020-06-30 21:46:31 +08001105 tmpfile = os.path.join(tmpdir, os_helper.TESTFN)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001106 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +00001107 except OSError as e:
1108 if e.errno != errno.EMFILE:
1109 raise
1110 break
1111 else:
1112 self.skipTest("failed to reach the file descriptor limit "
1113 "(tried %d)" % max_handles)
1114 # Close a couple of them (should be enough for a subprocess)
1115 for i in range(10):
1116 os.close(handles.pop())
1117 # Loop creating some subprocesses. If one of them leaks some fds,
1118 # the next loop iteration will fail by reaching the max fd limit.
1119 for i in range(15):
1120 p = subprocess.Popen([sys.executable, "-c",
1121 "import sys;"
1122 "sys.stdout.write(sys.stdin.read())"],
1123 stdin=subprocess.PIPE,
1124 stdout=subprocess.PIPE,
1125 stderr=subprocess.PIPE)
1126 data = p.communicate(b"lime")[0]
1127 self.assertEqual(data, b"lime")
1128 finally:
1129 for h in handles:
1130 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001131 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001132
1133 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001134 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
1135 '"a b c" d e')
1136 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
1137 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +00001138 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
1139 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001140 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
1141 'a\\\\\\b "de fg" h')
1142 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
1143 'a\\\\\\"b c d')
1144 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
1145 '"a\\\\b c" d e')
1146 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
1147 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001148 self.assertEqual(subprocess.list2cmdline(['ab', '']),
1149 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001150
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001151 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001152 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +02001153 "import os; os.read(0, 1)"],
1154 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001155 self.addCleanup(p.stdin.close)
1156 self.assertIsNone(p.poll())
1157 os.write(p.stdin.fileno(), b'A')
1158 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001159 # Subsequent invocations should just return the returncode
1160 self.assertEqual(p.poll(), 0)
1161
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001162 def test_wait(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001163 p = subprocess.Popen(ZERO_RETURN_CMD)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001164 self.assertEqual(p.wait(), 0)
1165 # Subsequent invocations should just return the returncode
1166 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001167
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001168 def test_wait_timeout(self):
1169 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001170 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001171 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001172 p.wait(timeout=0.0001)
1173 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Victor Stinner0d63bac2019-12-11 11:30:03 +01001174 self.assertEqual(p.wait(timeout=support.SHORT_TIMEOUT), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001175
Peter Astrand738131d2004-11-30 21:04:45 +00001176 def test_invalid_bufsize(self):
1177 # an invalid type of the bufsize argument should raise
1178 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001179 with self.assertRaises(TypeError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001180 subprocess.Popen(ZERO_RETURN_CMD, "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001181
Guido van Rossum46a05a72007-06-07 21:56:45 +00001182 def test_bufsize_is_none(self):
1183 # bufsize=None should be the same as bufsize=0.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001184 p = subprocess.Popen(ZERO_RETURN_CMD, None)
Guido van Rossum46a05a72007-06-07 21:56:45 +00001185 self.assertEqual(p.wait(), 0)
1186 # Again with keyword arg
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001187 p = subprocess.Popen(ZERO_RETURN_CMD, bufsize=None)
Guido van Rossum46a05a72007-06-07 21:56:45 +00001188 self.assertEqual(p.wait(), 0)
1189
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001190 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1191 # subprocess may deadlock with bufsize=1, see issue #21332
1192 with subprocess.Popen([sys.executable, "-c", "import sys;"
1193 "sys.stdout.write(sys.stdin.readline());"
1194 "sys.stdout.flush()"],
1195 stdin=subprocess.PIPE,
1196 stdout=subprocess.PIPE,
1197 stderr=subprocess.DEVNULL,
1198 bufsize=1,
1199 universal_newlines=universal_newlines) as p:
1200 p.stdin.write(line) # expect that it flushes the line in text mode
1201 os.close(p.stdin.fileno()) # close it without flushing the buffer
1202 read_line = p.stdout.readline()
Segev Finer4d385172017-08-18 16:18:13 +03001203 with support.SuppressCrashReport():
1204 try:
1205 p.stdin.close()
1206 except OSError:
1207 pass
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001208 p.stdin = None
1209 self.assertEqual(p.returncode, 0)
1210 self.assertEqual(read_line, expected)
1211
1212 def test_bufsize_equal_one_text_mode(self):
1213 # line is flushed in text mode with bufsize=1.
1214 # we should get the full line in return
1215 line = "line\n"
1216 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1217
1218 def test_bufsize_equal_one_binary_mode(self):
1219 # line is not flushed in binary mode with bufsize=1.
1220 # we should get empty response
1221 line = b'line' + os.linesep.encode() # assume ascii-based locale
Alexey Izbysheva2670562018-10-20 03:22:31 +03001222 with self.assertWarnsRegex(RuntimeWarning, 'line buffering'):
1223 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001224
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001225 def test_leaking_fds_on_error(self):
1226 # see bug #5179: Popen leaks file descriptors to PIPEs if
1227 # the child fails to execute; this will eventually exhaust
1228 # the maximum number of open fds. 1024 seems a very common
1229 # value for that limit, but Windows has 2048, so we loop
1230 # 1024 times (each call leaked two fds).
1231 for i in range(1024):
Victor Stinnerb31206a2018-01-25 19:06:05 +01001232 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02001233 subprocess.Popen(NONEXISTING_CMD,
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001234 stdout=subprocess.PIPE,
1235 stderr=subprocess.PIPE)
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001236
Victor Stinner9a83f652017-08-21 23:51:31 +02001237 def test_nonexisting_with_pipes(self):
1238 # bpo-30121: Popen with pipes must close properly pipes on error.
1239 # Previously, os.close() was called with a Windows handle which is not
1240 # a valid file descriptor.
1241 #
1242 # Run the test in a subprocess to control how the CRT reports errors
1243 # and to get stderr content.
1244 try:
1245 import msvcrt
1246 msvcrt.CrtSetReportMode
1247 except (AttributeError, ImportError):
1248 self.skipTest("need msvcrt.CrtSetReportMode")
1249
1250 code = textwrap.dedent(f"""
1251 import msvcrt
1252 import subprocess
1253
1254 cmd = {NONEXISTING_CMD!r}
1255
1256 for report_type in [msvcrt.CRT_WARN,
1257 msvcrt.CRT_ERROR,
1258 msvcrt.CRT_ASSERT]:
1259 msvcrt.CrtSetReportMode(report_type, msvcrt.CRTDBG_MODE_FILE)
1260 msvcrt.CrtSetReportFile(report_type, msvcrt.CRTDBG_FILE_STDERR)
1261
1262 try:
Zachary Ware55376462018-02-19 14:02:38 -06001263 subprocess.Popen(cmd,
Victor Stinner9a83f652017-08-21 23:51:31 +02001264 stdout=subprocess.PIPE,
1265 stderr=subprocess.PIPE)
1266 except OSError:
1267 pass
1268 """)
1269 cmd = [sys.executable, "-c", code]
1270 proc = subprocess.Popen(cmd,
1271 stderr=subprocess.PIPE,
1272 universal_newlines=True)
1273 with proc:
1274 stderr = proc.communicate()[1]
1275 self.assertEqual(stderr, "")
1276 self.assertEqual(proc.returncode, 0)
1277
Antoine Pitroua8392712013-08-30 23:38:13 +02001278 def test_double_close_on_error(self):
1279 # Issue #18851
1280 fds = []
1281 def open_fds():
1282 for i in range(20):
1283 fds.extend(os.pipe())
1284 time.sleep(0.001)
1285 t = threading.Thread(target=open_fds)
1286 t.start()
1287 try:
1288 with self.assertRaises(EnvironmentError):
Victor Stinner9a83f652017-08-21 23:51:31 +02001289 subprocess.Popen(NONEXISTING_CMD,
Antoine Pitroua8392712013-08-30 23:38:13 +02001290 stdin=subprocess.PIPE,
1291 stdout=subprocess.PIPE,
1292 stderr=subprocess.PIPE)
1293 finally:
1294 t.join()
1295 exc = None
1296 for fd in fds:
1297 # If a double close occurred, some of those fds will
1298 # already have been closed by mistake, and os.close()
1299 # here will raise.
1300 try:
1301 os.close(fd)
1302 except OSError as e:
1303 exc = e
1304 if exc is not None:
1305 raise exc
1306
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001307 def test_threadsafe_wait(self):
1308 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1309 proc = subprocess.Popen([sys.executable, '-c',
1310 'import time; time.sleep(12)'])
1311 self.assertEqual(proc.returncode, None)
1312 results = []
1313
1314 def kill_proc_timer_thread():
1315 results.append(('thread-start-poll-result', proc.poll()))
1316 # terminate it from the thread and wait for the result.
1317 proc.kill()
1318 proc.wait()
1319 results.append(('thread-after-kill-and-wait', proc.returncode))
1320 # this wait should be a no-op given the above.
1321 proc.wait()
1322 results.append(('thread-after-second-wait', proc.returncode))
1323
1324 # This is a timing sensitive test, the failure mode is
1325 # triggered when both the main thread and this thread are in
1326 # the wait() call at once. The delay here is to allow the
1327 # main thread to most likely be blocked in its wait() call.
1328 t = threading.Timer(0.2, kill_proc_timer_thread)
1329 t.start()
1330
Victor Stinner937ee9e2018-06-26 02:11:06 +02001331 if mswindows:
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001332 expected_errorcode = 1
1333 else:
1334 # Should be -9 because of the proc.kill() from the thread.
1335 expected_errorcode = -9
1336
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001337 # Wait for the process to finish; the thread should kill it
1338 # long before it finishes on its own. Supplying a timeout
1339 # triggers a different code path for better coverage.
Victor Stinner0d63bac2019-12-11 11:30:03 +01001340 proc.wait(timeout=support.SHORT_TIMEOUT)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001341 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001342 msg="unexpected result in wait from main thread")
1343
1344 # This should be a no-op with no change in returncode.
1345 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001346 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001347 msg="unexpected result in second main wait.")
1348
1349 t.join()
1350 # Ensure that all of the thread results are as expected.
1351 # When a race condition occurs in wait(), the returncode could
1352 # be set by the wrong thread that doesn't actually have it
1353 # leading to an incorrect value.
1354 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001355 ('thread-after-kill-and-wait', expected_errorcode),
1356 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001357 results)
1358
Victor Stinnerb3693582010-05-21 20:13:12 +00001359 def test_issue8780(self):
1360 # Ensure that stdout is inherited from the parent
1361 # if stdout=PIPE is not used
1362 code = ';'.join((
1363 'import subprocess, sys',
1364 'retcode = subprocess.call('
1365 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1366 'assert retcode == 0'))
1367 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001368 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001369
Tim Goldenaf5ac392010-08-06 13:03:56 +00001370 def test_handles_closed_on_exception(self):
1371 # If CreateProcess exits with an error, ensure the
1372 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001373 ifhandle, ifname = tempfile.mkstemp()
1374 ofhandle, ofname = tempfile.mkstemp()
1375 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001376 try:
1377 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1378 stderr=efhandle)
1379 except OSError:
1380 os.close(ifhandle)
1381 os.remove(ifname)
1382 os.close(ofhandle)
1383 os.remove(ofname)
1384 os.close(efhandle)
1385 os.remove(efname)
1386 self.assertFalse(os.path.exists(ifname))
1387 self.assertFalse(os.path.exists(ofname))
1388 self.assertFalse(os.path.exists(efname))
1389
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001390 def test_communicate_epipe(self):
1391 # Issue 10963: communicate() should hide EPIPE
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001392 p = subprocess.Popen(ZERO_RETURN_CMD,
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001393 stdin=subprocess.PIPE,
1394 stdout=subprocess.PIPE,
1395 stderr=subprocess.PIPE)
1396 self.addCleanup(p.stdout.close)
1397 self.addCleanup(p.stderr.close)
1398 self.addCleanup(p.stdin.close)
1399 p.communicate(b"x" * 2**20)
1400
Andrey Doroschenko645005e2019-11-17 17:08:31 +03001401 def test_repr(self):
1402 # Run a command that waits for user input, to check the repr() of
1403 # a Proc object while and after the sub-process runs.
1404 code = 'import sys; input(); sys.exit(57)'
1405 cmd = [sys.executable, '-c', code]
1406 result = "<Popen: returncode: {}"
1407
1408 with subprocess.Popen(
1409 cmd, stdin=subprocess.PIPE, universal_newlines=True) as proc:
1410 self.assertIsNone(proc.returncode)
1411 self.assertTrue(
1412 repr(proc).startswith(result.format(proc.returncode)) and
1413 repr(proc).endswith('>')
1414 )
1415
1416 proc.communicate(input='exit...\n')
1417 proc.wait()
1418
1419 self.assertIsNotNone(proc.returncode)
1420 self.assertTrue(
1421 repr(proc).startswith(result.format(proc.returncode)) and
1422 repr(proc).endswith('>')
1423 )
1424
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001425 def test_communicate_epipe_only_stdin(self):
1426 # Issue 10963: communicate() should hide EPIPE
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001427 p = subprocess.Popen(ZERO_RETURN_CMD,
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001428 stdin=subprocess.PIPE)
1429 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001430 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001431 p.communicate(b"x" * 2**20)
1432
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001433 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1434 "Requires signal.SIGUSR1")
1435 @unittest.skipUnless(hasattr(os, 'kill'),
1436 "Requires os.kill")
1437 @unittest.skipUnless(hasattr(os, 'getppid'),
1438 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001439 def test_communicate_eintr(self):
1440 # Issue #12493: communicate() should handle EINTR
1441 def handler(signum, frame):
1442 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001443 old_handler = signal.signal(signal.SIGUSR1, handler)
1444 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001445
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001446 args = [sys.executable, "-c",
1447 'import os, signal;'
1448 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001449 for stream in ('stdout', 'stderr'):
1450 kw = {stream: subprocess.PIPE}
1451 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001452 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001453 process.communicate()
1454
Tim Peterse718f612004-10-12 21:51:32 +00001455
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001456 # This test is Linux-ish specific for simplicity to at least have
1457 # some coverage. It is not a platform specific bug.
1458 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1459 "Linux specific")
1460 def test_failed_child_execute_fd_leak(self):
1461 """Test for the fork() failure fd leak reported in issue16327."""
1462 fd_directory = '/proc/%d/fd' % os.getpid()
1463 fds_before_popen = os.listdir(fd_directory)
1464 with self.assertRaises(PopenTestException):
1465 PopenExecuteChildRaises(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001466 ZERO_RETURN_CMD, stdin=subprocess.PIPE,
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001467 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1468
1469 # NOTE: This test doesn't verify that the real _execute_child
1470 # does not close the file descriptors itself on the way out
1471 # during an exception. Code inspection has confirmed that.
1472
1473 fds_after_exception = os.listdir(fd_directory)
1474 self.assertEqual(fds_before_popen, fds_after_exception)
1475
Victor Stinner937ee9e2018-06-26 02:11:06 +02001476 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001477 def test_file_not_found_includes_filename(self):
1478 with self.assertRaises(FileNotFoundError) as c:
1479 subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args'])
1480 self.assertEqual(c.exception.filename, '/opt/nonexistent_binary')
1481
Victor Stinner937ee9e2018-06-26 02:11:06 +02001482 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001483 def test_file_not_found_with_bad_cwd(self):
1484 with self.assertRaises(FileNotFoundError) as c:
1485 subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory')
1486 self.assertEqual(c.exception.filename, '/some/nonexistent/directory')
1487
Batuhan Taşkaya4dc5a9d2019-12-30 19:02:04 +03001488 def test_class_getitems(self):
Guido van Rossum48b069a2020-04-07 09:50:06 -07001489 self.assertIsInstance(subprocess.Popen[bytes], types.GenericAlias)
1490 self.assertIsInstance(subprocess.CompletedProcess[str], types.GenericAlias)
Gregory P. Smith6e730002015-04-14 16:14:25 -07001491
1492class RunFuncTestCase(BaseTestCase):
1493 def run_python(self, code, **kwargs):
1494 """Run Python code in a subprocess using subprocess.run"""
1495 argv = [sys.executable, "-c", code]
1496 return subprocess.run(argv, **kwargs)
1497
1498 def test_returncode(self):
1499 # call() function with sequence argument
1500 cp = self.run_python("import sys; sys.exit(47)")
1501 self.assertEqual(cp.returncode, 47)
1502 with self.assertRaises(subprocess.CalledProcessError):
1503 cp.check_returncode()
1504
1505 def test_check(self):
1506 with self.assertRaises(subprocess.CalledProcessError) as c:
1507 self.run_python("import sys; sys.exit(47)", check=True)
1508 self.assertEqual(c.exception.returncode, 47)
1509
1510 def test_check_zero(self):
1511 # check_returncode shouldn't raise when returncode is zero
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001512 cp = subprocess.run(ZERO_RETURN_CMD, check=True)
Gregory P. Smith6e730002015-04-14 16:14:25 -07001513 self.assertEqual(cp.returncode, 0)
1514
1515 def test_timeout(self):
1516 # run() function with timeout argument; we want to test that the child
1517 # process gets killed when the timeout expires. If the child isn't
1518 # killed, this call will deadlock since subprocess.run waits for the
1519 # child.
1520 with self.assertRaises(subprocess.TimeoutExpired):
1521 self.run_python("while True: pass", timeout=0.0001)
1522
1523 def test_capture_stdout(self):
1524 # capture stdout with zero return code
1525 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1526 self.assertIn(b'BDFL', cp.stdout)
1527
1528 def test_capture_stderr(self):
1529 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1530 stderr=subprocess.PIPE)
1531 self.assertIn(b'BDFL', cp.stderr)
1532
1533 def test_check_output_stdin_arg(self):
1534 # run() can be called with stdin set to a file
1535 tf = tempfile.TemporaryFile()
1536 self.addCleanup(tf.close)
1537 tf.write(b'pear')
1538 tf.seek(0)
1539 cp = self.run_python(
1540 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1541 stdin=tf, stdout=subprocess.PIPE)
1542 self.assertIn(b'PEAR', cp.stdout)
1543
1544 def test_check_output_input_arg(self):
1545 # check_output() can be called with input set to a string
1546 cp = self.run_python(
1547 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1548 input=b'pear', stdout=subprocess.PIPE)
1549 self.assertIn(b'PEAR', cp.stdout)
1550
1551 def test_check_output_stdin_with_input_arg(self):
1552 # run() refuses to accept 'stdin' with 'input'
1553 tf = tempfile.TemporaryFile()
1554 self.addCleanup(tf.close)
1555 tf.write(b'pear')
1556 tf.seek(0)
1557 with self.assertRaises(ValueError,
1558 msg="Expected ValueError when stdin and input args supplied.") as c:
1559 output = self.run_python("print('will not be run')",
1560 stdin=tf, input=b'hare')
1561 self.assertIn('stdin', c.exception.args[0])
1562 self.assertIn('input', c.exception.args[0])
1563
1564 def test_check_output_timeout(self):
1565 with self.assertRaises(subprocess.TimeoutExpired) as c:
1566 cp = self.run_python((
1567 "import sys, time\n"
1568 "sys.stdout.write('BDFL')\n"
1569 "sys.stdout.flush()\n"
1570 "time.sleep(3600)"),
1571 # Some heavily loaded buildbots (sparc Debian 3.x) require
1572 # this much time to start and print.
1573 timeout=3, stdout=subprocess.PIPE)
1574 self.assertEqual(c.exception.output, b'BDFL')
1575 # output is aliased to stdout
1576 self.assertEqual(c.exception.stdout, b'BDFL')
1577
1578 def test_run_kwargs(self):
1579 newenv = os.environ.copy()
1580 newenv["FRUIT"] = "banana"
1581 cp = self.run_python(('import sys, os;'
1582 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1583 env=newenv)
1584 self.assertEqual(cp.returncode, 33)
1585
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001586 def test_run_with_pathlike_path(self):
1587 # bpo-31961: test run(pathlike_object)
1588 # the name of a command that can be run without
Min ho Kimc4cacc82019-07-31 08:16:13 +10001589 # any arguments that exit fast
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001590 prog = 'tree.com' if mswindows else 'ls'
1591 path = shutil.which(prog)
1592 if path is None:
1593 self.skipTest(f'{prog} required for this test')
1594 path = FakePath(path)
1595 res = subprocess.run(path, stdout=subprocess.DEVNULL)
1596 self.assertEqual(res.returncode, 0)
1597 with self.assertRaises(TypeError):
1598 subprocess.run(path, stdout=subprocess.DEVNULL, shell=True)
1599
1600 def test_run_with_bytes_path_and_arguments(self):
1601 # bpo-31961: test run([bytes_object, b'additional arguments'])
1602 path = os.fsencode(sys.executable)
1603 args = [path, '-c', b'import sys; sys.exit(57)']
1604 res = subprocess.run(args)
1605 self.assertEqual(res.returncode, 57)
1606
1607 def test_run_with_pathlike_path_and_arguments(self):
1608 # bpo-31961: test run([pathlike_object, 'additional arguments'])
1609 path = FakePath(sys.executable)
1610 args = [path, '-c', 'import sys; sys.exit(57)']
1611 res = subprocess.run(args)
1612 self.assertEqual(res.returncode, 57)
1613
Bo Baylesce0f33d2018-01-30 00:40:39 -06001614 def test_capture_output(self):
1615 cp = self.run_python(("import sys;"
1616 "sys.stdout.write('BDFL'); "
1617 "sys.stderr.write('FLUFL')"),
1618 capture_output=True)
1619 self.assertIn(b'BDFL', cp.stdout)
1620 self.assertIn(b'FLUFL', cp.stderr)
1621
1622 def test_stdout_with_capture_output_arg(self):
1623 # run() refuses to accept 'stdout' with 'capture_output'
1624 tf = tempfile.TemporaryFile()
1625 self.addCleanup(tf.close)
1626 with self.assertRaises(ValueError,
1627 msg=("Expected ValueError when stdout and capture_output "
1628 "args supplied.")) as c:
1629 output = self.run_python("print('will not be run')",
1630 capture_output=True, stdout=tf)
1631 self.assertIn('stdout', c.exception.args[0])
1632 self.assertIn('capture_output', c.exception.args[0])
1633
1634 def test_stderr_with_capture_output_arg(self):
1635 # run() refuses to accept 'stderr' with 'capture_output'
1636 tf = tempfile.TemporaryFile()
1637 self.addCleanup(tf.close)
1638 with self.assertRaises(ValueError,
1639 msg=("Expected ValueError when stderr and capture_output "
1640 "args supplied.")) as c:
1641 output = self.run_python("print('will not be run')",
1642 capture_output=True, stderr=tf)
1643 self.assertIn('stderr', c.exception.args[0])
1644 self.assertIn('capture_output', c.exception.args[0])
1645
Gregory P. Smith580d2782019-09-11 04:23:05 -05001646 # This test _might_ wind up a bit fragile on loaded build+test machines
1647 # as it depends on the timing with wide enough margins for normal situations
1648 # but does assert that it happened "soon enough" to believe the right thing
1649 # happened.
1650 @unittest.skipIf(mswindows, "requires posix like 'sleep' shell command")
1651 def test_run_with_shell_timeout_and_capture_output(self):
1652 """Output capturing after a timeout mustn't hang forever on open filehandles."""
1653 before_secs = time.monotonic()
1654 try:
1655 subprocess.run('sleep 3', shell=True, timeout=0.1,
1656 capture_output=True) # New session unspecified.
1657 except subprocess.TimeoutExpired as exc:
1658 after_secs = time.monotonic()
1659 stacks = traceback.format_exc() # assertRaises doesn't give this.
1660 else:
1661 self.fail("TimeoutExpired not raised.")
1662 self.assertLess(after_secs - before_secs, 1.5,
1663 msg="TimeoutExpired was delayed! Bad traceback:\n```\n"
1664 f"{stacks}```")
1665
Gregory P. Smith6e730002015-04-14 16:14:25 -07001666
Gregory P. Smith693aa802019-09-13 14:43:35 +01001667def _get_test_grp_name():
Victor Stinnerfaca8552019-09-25 15:52:49 +02001668 for name_group in ('staff', 'nogroup', 'grp', 'nobody', 'nfsnobody'):
Gregory P. Smith693aa802019-09-13 14:43:35 +01001669 if grp:
1670 try:
1671 grp.getgrnam(name_group)
1672 except KeyError:
1673 continue
1674 return name_group
1675 else:
1676 raise unittest.SkipTest('No identified group name to use for this test on this platform.')
1677
1678
Victor Stinner937ee9e2018-06-26 02:11:06 +02001679@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001680class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001681
Gregory P. Smith5591b022012-10-10 03:34:47 -07001682 def setUp(self):
1683 super().setUp()
1684 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1685
1686 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001687 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001688 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001689 except OSError as e:
1690 # This avoids hard coding the errno value or the OS perror()
1691 # string and instead capture the exception that we want to see
1692 # below for comparison.
1693 desired_exception = e
1694 else:
Martin Pantereb995702016-07-28 01:11:04 +00001695 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001696 self._nonexistent_dir)
1697 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001698
Gregory P. Smith5591b022012-10-10 03:34:47 -07001699 def test_exception_cwd(self):
1700 """Test error in the child raised in the parent for a bad cwd."""
1701 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001702 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001703 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001704 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001705 except OSError as e:
1706 # Test that the child process chdir failure actually makes
1707 # it up to the parent process as the correct exception.
1708 self.assertEqual(desired_exception.errno, e.errno)
1709 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001710 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001711 else:
1712 self.fail("Expected OSError: %s" % desired_exception)
1713
Gregory P. Smith5591b022012-10-10 03:34:47 -07001714 def test_exception_bad_executable(self):
1715 """Test error in the child raised in the parent for a bad executable."""
1716 desired_exception = self._get_chdir_exception()
1717 try:
1718 p = subprocess.Popen([sys.executable, "-c", ""],
1719 executable=self._nonexistent_dir)
1720 except OSError as e:
1721 # Test that the child process exec failure actually makes
1722 # it up to the parent process as the correct exception.
1723 self.assertEqual(desired_exception.errno, e.errno)
1724 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001725 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001726 else:
1727 self.fail("Expected OSError: %s" % desired_exception)
1728
1729 def test_exception_bad_args_0(self):
1730 """Test error in the child raised in the parent for a bad args[0]."""
1731 desired_exception = self._get_chdir_exception()
1732 try:
1733 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1734 except OSError as e:
1735 # Test that the child process exec failure actually makes
1736 # it up to the parent process as the correct exception.
1737 self.assertEqual(desired_exception.errno, e.errno)
1738 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001739 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001740 else:
1741 self.fail("Expected OSError: %s" % desired_exception)
1742
Ammar Askar3fc499b2017-09-06 02:41:30 -04001743 # We mock the __del__ method for Popen in the next two tests
1744 # because it does cleanup based on the pid returned by fork_exec
1745 # along with issuing a resource warning if it still exists. Since
1746 # we don't actually spawn a process in these tests we can forego
1747 # the destructor. An alternative would be to set _child_created to
1748 # False before the destructor is called but there is no easy way
1749 # to do that
1750 class PopenNoDestructor(subprocess.Popen):
1751 def __del__(self):
1752 pass
1753
1754 @mock.patch("subprocess._posixsubprocess.fork_exec")
1755 def test_exception_errpipe_normal(self, fork_exec):
1756 """Test error passing done through errpipe_write in the good case"""
1757 def proper_error(*args):
1758 errpipe_write = args[13]
1759 # Write the hex for the error code EISDIR: 'is a directory'
1760 err_code = '{:x}'.format(errno.EISDIR).encode()
1761 os.write(errpipe_write, b"OSError:" + err_code + b":")
1762 return 0
1763
1764 fork_exec.side_effect = proper_error
1765
Victor Stinner11045c92017-10-05 06:32:53 -07001766 with mock.patch("subprocess.os.waitpid",
1767 side_effect=ChildProcessError):
1768 with self.assertRaises(IsADirectoryError):
1769 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001770
1771 @mock.patch("subprocess._posixsubprocess.fork_exec")
1772 def test_exception_errpipe_bad_data(self, fork_exec):
1773 """Test error passing done through errpipe_write where its not
1774 in the expected format"""
1775 error_data = b"\xFF\x00\xDE\xAD"
1776 def bad_error(*args):
1777 errpipe_write = args[13]
1778 # Anything can be in the pipe, no assumptions should
1779 # be made about its encoding, so we'll write some
1780 # arbitrary hex bytes to test it out
1781 os.write(errpipe_write, error_data)
1782 return 0
1783
1784 fork_exec.side_effect = bad_error
1785
Victor Stinner11045c92017-10-05 06:32:53 -07001786 with mock.patch("subprocess.os.waitpid",
1787 side_effect=ChildProcessError):
1788 with self.assertRaises(subprocess.SubprocessError) as e:
1789 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001790
1791 self.assertIn(repr(error_data), str(e.exception))
1792
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001793 @unittest.skipIf(not os.path.exists('/proc/self/status'),
1794 "need /proc/self/status")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001795 def test_restore_signals(self):
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001796 # Blindly assume that cat exists on systems with /proc/self/status...
1797 default_proc_status = subprocess.check_output(
1798 ['cat', '/proc/self/status'],
1799 restore_signals=False)
1800 for line in default_proc_status.splitlines():
1801 if line.startswith(b'SigIgn'):
1802 default_sig_ign_mask = line
1803 break
1804 else:
1805 self.skipTest("SigIgn not found in /proc/self/status.")
1806 restored_proc_status = subprocess.check_output(
1807 ['cat', '/proc/self/status'],
1808 restore_signals=True)
1809 for line in restored_proc_status.splitlines():
1810 if line.startswith(b'SigIgn'):
1811 restored_sig_ign_mask = line
1812 break
1813 self.assertNotEqual(default_sig_ign_mask, restored_sig_ign_mask,
1814 msg="restore_signals=True should've unblocked "
1815 "SIGPIPE and friends.")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001816
1817 def test_start_new_session(self):
1818 # For code coverage of calling setsid(). We don't care if we get an
1819 # EPERM error from it depending on the test execution environment, that
1820 # still indicates that it was called.
1821 try:
1822 output = subprocess.check_output(
Victor Stinner58840432019-06-14 19:31:43 +02001823 [sys.executable, "-c", "import os; print(os.getsid(0))"],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001824 start_new_session=True)
1825 except OSError as e:
1826 if e.errno != errno.EPERM:
1827 raise
1828 else:
Victor Stinner58840432019-06-14 19:31:43 +02001829 parent_sid = os.getsid(0)
1830 child_sid = int(output)
1831 self.assertNotEqual(parent_sid, child_sid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001832
Patrick McLean2b2ead72019-09-12 10:15:44 -07001833 @unittest.skipUnless(hasattr(os, 'setreuid'), 'no setreuid on platform')
1834 def test_user(self):
1835 # For code coverage of the user parameter. We don't care if we get an
1836 # EPERM error from it depending on the test execution environment, that
1837 # still indicates that it was called.
1838
1839 uid = os.geteuid()
1840 test_users = [65534 if uid != 65534 else 65533, uid]
1841 name_uid = "nobody" if sys.platform != 'darwin' else "unknown"
1842
1843 if pwd is not None:
Victor Stinnerf7b5d412020-03-05 14:28:40 +01001844 try:
1845 pwd.getpwnam(name_uid)
1846 test_users.append(name_uid)
1847 except KeyError:
1848 # unknown user name
1849 name_uid = None
Patrick McLean2b2ead72019-09-12 10:15:44 -07001850
1851 for user in test_users:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001852 # posix_spawn() may be used with close_fds=False
1853 for close_fds in (False, True):
1854 with self.subTest(user=user, close_fds=close_fds):
1855 try:
1856 output = subprocess.check_output(
1857 [sys.executable, "-c",
1858 "import os; print(os.getuid())"],
1859 user=user,
1860 close_fds=close_fds)
1861 except PermissionError: # (EACCES, EPERM)
1862 pass
1863 except OSError as e:
1864 if e.errno not in (errno.EACCES, errno.EPERM):
1865 raise
Patrick McLean2b2ead72019-09-12 10:15:44 -07001866 else:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001867 if isinstance(user, str):
1868 user_uid = pwd.getpwnam(user).pw_uid
1869 else:
1870 user_uid = user
1871 child_user = int(output)
1872 self.assertEqual(child_user, user_uid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001873
1874 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001875 subprocess.check_call(ZERO_RETURN_CMD, user=-1)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001876
Victor Stinnerf7b5d412020-03-05 14:28:40 +01001877 if pwd is None and name_uid is not None:
Patrick McLean2b2ead72019-09-12 10:15:44 -07001878 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001879 subprocess.check_call(ZERO_RETURN_CMD, user=name_uid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001880
1881 @unittest.skipIf(hasattr(os, 'setreuid'), 'setreuid() available on platform')
1882 def test_user_error(self):
1883 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001884 subprocess.check_call(ZERO_RETURN_CMD, user=65535)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001885
1886 @unittest.skipUnless(hasattr(os, 'setregid'), 'no setregid() on platform')
1887 def test_group(self):
1888 gid = os.getegid()
1889 group_list = [65534 if gid != 65534 else 65533]
Gregory P. Smith693aa802019-09-13 14:43:35 +01001890 name_group = _get_test_grp_name()
Patrick McLean2b2ead72019-09-12 10:15:44 -07001891
1892 if grp is not None:
1893 group_list.append(name_group)
1894
1895 for group in group_list + [gid]:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001896 # posix_spawn() may be used with close_fds=False
1897 for close_fds in (False, True):
1898 with self.subTest(group=group, close_fds=close_fds):
1899 try:
1900 output = subprocess.check_output(
1901 [sys.executable, "-c",
1902 "import os; print(os.getgid())"],
1903 group=group,
1904 close_fds=close_fds)
1905 except PermissionError: # (EACCES, EPERM)
1906 pass
Patrick McLean2b2ead72019-09-12 10:15:44 -07001907 else:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001908 if isinstance(group, str):
1909 group_gid = grp.getgrnam(group).gr_gid
1910 else:
1911 group_gid = group
Patrick McLean2b2ead72019-09-12 10:15:44 -07001912
Victor Stinnerfaca8552019-09-25 15:52:49 +02001913 child_group = int(output)
1914 self.assertEqual(child_group, group_gid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001915
1916 # make sure we bomb on negative values
1917 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001918 subprocess.check_call(ZERO_RETURN_CMD, group=-1)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001919
1920 if grp is None:
1921 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001922 subprocess.check_call(ZERO_RETURN_CMD, group=name_group)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001923
1924 @unittest.skipIf(hasattr(os, 'setregid'), 'setregid() available on platform')
1925 def test_group_error(self):
1926 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001927 subprocess.check_call(ZERO_RETURN_CMD, group=65535)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001928
1929 @unittest.skipUnless(hasattr(os, 'setgroups'), 'no setgroups() on platform')
1930 def test_extra_groups(self):
1931 gid = os.getegid()
1932 group_list = [65534 if gid != 65534 else 65533]
Gregory P. Smith693aa802019-09-13 14:43:35 +01001933 name_group = _get_test_grp_name()
Patrick McLean2b2ead72019-09-12 10:15:44 -07001934 perm_error = False
1935
1936 if grp is not None:
1937 group_list.append(name_group)
1938
1939 try:
1940 output = subprocess.check_output(
1941 [sys.executable, "-c",
1942 "import os, sys, json; json.dump(os.getgroups(), sys.stdout)"],
1943 extra_groups=group_list)
1944 except OSError as ex:
1945 if ex.errno != errno.EPERM:
1946 raise
1947 perm_error = True
1948
1949 else:
1950 parent_groups = os.getgroups()
1951 child_groups = json.loads(output)
1952
1953 if grp is not None:
1954 desired_gids = [grp.getgrnam(g).gr_gid if isinstance(g, str) else g
1955 for g in group_list]
1956 else:
1957 desired_gids = group_list
1958
1959 if perm_error:
1960 self.assertEqual(set(child_groups), set(parent_groups))
1961 else:
1962 self.assertEqual(set(desired_gids), set(child_groups))
1963
1964 # make sure we bomb on negative values
1965 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001966 subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[-1])
Patrick McLean2b2ead72019-09-12 10:15:44 -07001967
1968 if grp is None:
1969 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001970 subprocess.check_call(ZERO_RETURN_CMD,
Patrick McLean2b2ead72019-09-12 10:15:44 -07001971 extra_groups=[name_group])
1972
1973 @unittest.skipIf(hasattr(os, 'setgroups'), 'setgroups() available on platform')
1974 def test_extra_groups_error(self):
1975 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001976 subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[])
Patrick McLean2b2ead72019-09-12 10:15:44 -07001977
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07001978 @unittest.skipIf(mswindows or not hasattr(os, 'umask'),
1979 'POSIX umask() is not available.')
1980 def test_umask(self):
1981 tmpdir = None
1982 try:
1983 tmpdir = tempfile.mkdtemp()
1984 name = os.path.join(tmpdir, "beans")
1985 # We set an unusual umask in the child so as a unique mode
1986 # for us to test the child's touched file for.
1987 subprocess.check_call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001988 [sys.executable, "-c", f"open({name!r}, 'w').close()"],
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07001989 umask=0o053)
1990 # Ignore execute permissions entirely in our test,
1991 # filesystems could be mounted to ignore or force that.
1992 st_mode = os.stat(name).st_mode & 0o666
1993 expected_mode = 0o624
1994 self.assertEqual(expected_mode, st_mode,
1995 msg=f'{oct(expected_mode)} != {oct(st_mode)}')
1996 finally:
1997 if tmpdir is not None:
1998 shutil.rmtree(tmpdir)
1999
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002000 def test_run_abort(self):
2001 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02002002 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002003 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002004 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002005 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002006 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002007
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00002008 def test_CalledProcessError_str_signal(self):
2009 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
2010 error_string = str(err)
2011 # We're relying on the repr() of the signal.Signals intenum to provide
2012 # the word signal, the signal name and the numeric value.
2013 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00002014 # We're not being specific about the signal name as some signals have
2015 # multiple names and which name is revealed can vary.
2016 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00002017 self.assertIn(str(signal.SIGABRT), error_string)
2018
2019 def test_CalledProcessError_str_unknown_signal(self):
2020 err = subprocess.CalledProcessError(-9876543, "fake cmd")
2021 error_string = str(err)
2022 self.assertIn("unknown signal 9876543.", error_string)
2023
2024 def test_CalledProcessError_str_non_zero(self):
2025 err = subprocess.CalledProcessError(2, "fake cmd")
2026 error_string = str(err)
2027 self.assertIn("non-zero exit status 2.", error_string)
2028
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002029 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002030 # DISCLAIMER: Setting environment variables is *not* a good use
2031 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002032 p = subprocess.Popen([sys.executable, "-c",
2033 'import sys,os;'
2034 'sys.stdout.write(os.getenv("FRUIT"))'],
2035 stdout=subprocess.PIPE,
2036 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02002037 with p:
2038 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002039
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002040 def test_preexec_exception(self):
2041 def raise_it():
2042 raise ValueError("What if two swallows carried a coconut?")
2043 try:
2044 p = subprocess.Popen([sys.executable, "-c", ""],
2045 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002046 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002047 self.assertTrue(
2048 subprocess._posixsubprocess,
2049 "Expected a ValueError from the preexec_fn")
2050 except ValueError as e:
2051 self.assertIn("coconut", e.args[0])
2052 else:
2053 self.fail("Exception raised by preexec_fn did not make it "
2054 "to the parent process.")
2055
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002056 class _TestExecuteChildPopen(subprocess.Popen):
2057 """Used to test behavior at the end of _execute_child."""
2058 def __init__(self, testcase, *args, **kwargs):
2059 self._testcase = testcase
2060 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002061
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002062 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08002063 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002064 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002065 finally:
2066 # Open a bunch of file descriptors and verify that
2067 # none of them are the same as the ones the Popen
2068 # instance is using for stdin/stdout/stderr.
2069 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
2070 for _ in range(8)]
2071 try:
2072 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002073 self._testcase.assertNotIn(
2074 fd, (self.stdin.fileno(), self.stdout.fileno(),
2075 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08002076 msg="At least one fd was closed early.")
2077 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01002078 for fd in devzero_fds:
2079 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002080
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002081 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
2082 def test_preexec_errpipe_does_not_double_close_pipes(self):
2083 """Issue16140: Don't double close pipes on preexec error."""
2084
2085 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08002086 raise subprocess.SubprocessError(
2087 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08002088
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08002089 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002090 self._TestExecuteChildPopen(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002091 self, ZERO_RETURN_CMD,
Gregory P. Smith12489d92012-11-11 01:37:02 -08002092 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2093 stderr=subprocess.PIPE, preexec_fn=raise_it)
2094
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00002095 def test_preexec_gc_module_failure(self):
2096 # This tests the code that disables garbage collection if the child
2097 # process will execute any Python.
2098 def raise_runtime_error():
2099 raise RuntimeError("this shouldn't escape")
2100 enabled = gc.isenabled()
2101 orig_gc_disable = gc.disable
2102 orig_gc_isenabled = gc.isenabled
2103 try:
2104 gc.disable()
2105 self.assertFalse(gc.isenabled())
2106 subprocess.call([sys.executable, '-c', ''],
2107 preexec_fn=lambda: None)
2108 self.assertFalse(gc.isenabled(),
2109 "Popen enabled gc when it shouldn't.")
2110
2111 gc.enable()
2112 self.assertTrue(gc.isenabled())
2113 subprocess.call([sys.executable, '-c', ''],
2114 preexec_fn=lambda: None)
2115 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
2116
2117 gc.disable = raise_runtime_error
2118 self.assertRaises(RuntimeError, subprocess.Popen,
2119 [sys.executable, '-c', ''],
2120 preexec_fn=lambda: None)
2121
2122 del gc.isenabled # force an AttributeError
2123 self.assertRaises(AttributeError, subprocess.Popen,
2124 [sys.executable, '-c', ''],
2125 preexec_fn=lambda: None)
2126 finally:
2127 gc.disable = orig_gc_disable
2128 gc.isenabled = orig_gc_isenabled
2129 if not enabled:
2130 gc.disable()
2131
Martin Panterf7fdbda2015-12-05 09:51:52 +00002132 @unittest.skipIf(
2133 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00002134 def test_preexec_fork_failure(self):
2135 # The internal code did not preserve the previous exception when
2136 # re-enabling garbage collection
2137 try:
2138 from resource import getrlimit, setrlimit, RLIMIT_NPROC
2139 except ImportError as err:
2140 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
2141 limits = getrlimit(RLIMIT_NPROC)
2142 [_, hard] = limits
2143 setrlimit(RLIMIT_NPROC, (0, hard))
2144 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00002145 try:
Martin Panterafdd5132015-11-30 02:21:41 +00002146 subprocess.call([sys.executable, '-c', ''],
2147 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00002148 except BlockingIOError:
2149 # Forking should raise EAGAIN, translated to BlockingIOError
2150 pass
2151 else:
2152 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00002153
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002154 def test_args_string(self):
2155 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03002156 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002157 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002158 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002159 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002160 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2161 sys.executable)
2162 os.chmod(fname, 0o700)
2163 p = subprocess.Popen(fname)
2164 p.wait()
2165 os.remove(fname)
2166 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002167
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002168 def test_invalid_args(self):
2169 # invalid arguments should raise ValueError
2170 self.assertRaises(ValueError, subprocess.call,
2171 [sys.executable, "-c",
2172 "import sys; sys.exit(47)"],
2173 startupinfo=47)
2174 self.assertRaises(ValueError, subprocess.call,
2175 [sys.executable, "-c",
2176 "import sys; sys.exit(47)"],
2177 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002178
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002179 def test_shell_sequence(self):
2180 # Run command through the shell (sequence)
2181 newenv = os.environ.copy()
2182 newenv["FRUIT"] = "apple"
2183 p = subprocess.Popen(["echo $FRUIT"], shell=1,
2184 stdout=subprocess.PIPE,
2185 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002186 with p:
2187 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002188
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002189 def test_shell_string(self):
2190 # Run command through the shell (string)
2191 newenv = os.environ.copy()
2192 newenv["FRUIT"] = "apple"
2193 p = subprocess.Popen("echo $FRUIT", shell=1,
2194 stdout=subprocess.PIPE,
2195 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002196 with p:
2197 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00002198
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002199 def test_call_string(self):
2200 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03002201 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002202 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002203 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002204 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002205 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2206 sys.executable)
2207 os.chmod(fname, 0o700)
2208 rc = subprocess.call(fname)
2209 os.remove(fname)
2210 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00002211
Stefan Krah9542cc62010-07-19 14:20:53 +00002212 def test_specific_shell(self):
2213 # Issue #9265: Incorrect name passed as arg[0].
2214 shells = []
2215 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
2216 for name in ['bash', 'ksh']:
2217 sh = os.path.join(prefix, name)
2218 if os.path.isfile(sh):
2219 shells.append(sh)
2220 if not shells: # Will probably work for any shell but csh.
2221 self.skipTest("bash or ksh required for this test")
2222 sh = '/bin/sh'
2223 if os.path.isfile(sh) and not os.path.islink(sh):
2224 # Test will fail if /bin/sh is a symlink to csh.
2225 shells.append(sh)
2226 for sh in shells:
2227 p = subprocess.Popen("echo $0", executable=sh, shell=True,
2228 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002229 with p:
2230 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00002231
Florent Xicluna4886d242010-03-08 13:27:26 +00002232 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00002233 # Do not inherit file handles from the parent.
2234 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07002235 # Also set the SIGINT handler to the default to make sure it's not
2236 # being ignored (some tests rely on that.)
2237 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
2238 try:
2239 p = subprocess.Popen([sys.executable, "-c", """if 1:
2240 import sys, time
2241 sys.stdout.write('x\\n')
2242 sys.stdout.flush()
2243 time.sleep(30)
2244 """],
2245 close_fds=True,
2246 stdin=subprocess.PIPE,
2247 stdout=subprocess.PIPE,
2248 stderr=subprocess.PIPE)
2249 finally:
2250 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00002251 # Wait for the interpreter to be completely initialized before
2252 # sending any signal.
2253 p.stdout.read(1)
2254 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00002255 return p
2256
Charles-François Natali53221e32013-01-12 16:52:20 +01002257 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
2258 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002259 def _kill_dead_process(self, method, *args):
2260 # Do not inherit file handles from the parent.
2261 # It should fix failures on some platforms.
2262 p = subprocess.Popen([sys.executable, "-c", """if 1:
2263 import sys, time
2264 sys.stdout.write('x\\n')
2265 sys.stdout.flush()
2266 """],
2267 close_fds=True,
2268 stdin=subprocess.PIPE,
2269 stdout=subprocess.PIPE,
2270 stderr=subprocess.PIPE)
2271 # Wait for the interpreter to be completely initialized before
2272 # sending any signal.
2273 p.stdout.read(1)
2274 # The process should end after this
2275 time.sleep(1)
2276 # This shouldn't raise even though the child is now dead
2277 getattr(p, method)(*args)
2278 p.communicate()
2279
Florent Xicluna4886d242010-03-08 13:27:26 +00002280 def test_send_signal(self):
2281 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00002282 _, stderr = p.communicate()
2283 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002284 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00002285
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002286 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002287 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00002288 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002289 self.assertEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002290 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00002291
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002292 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002293 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00002294 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002295 self.assertEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002296 self.assertEqual(p.wait(), -signal.SIGTERM)
2297
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002298 def test_send_signal_dead(self):
2299 # Sending a signal to a dead process
2300 self._kill_dead_process('send_signal', signal.SIGINT)
2301
2302 def test_kill_dead(self):
2303 # Killing a dead process
2304 self._kill_dead_process('kill')
2305
2306 def test_terminate_dead(self):
2307 # Terminating a dead process
2308 self._kill_dead_process('terminate')
2309
Victor Stinnerdaf45552013-08-28 00:53:59 +02002310 def _save_fds(self, save_fds):
2311 fds = []
2312 for fd in save_fds:
2313 inheritable = os.get_inheritable(fd)
2314 saved = os.dup(fd)
2315 fds.append((fd, saved, inheritable))
2316 return fds
2317
2318 def _restore_fds(self, fds):
2319 for fd, saved, inheritable in fds:
2320 os.dup2(saved, fd, inheritable=inheritable)
2321 os.close(saved)
2322
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002323 def check_close_std_fds(self, fds):
2324 # Issue #9905: test that subprocess pipes still work properly with
2325 # some standard fds closed
2326 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02002327 saved_fds = self._save_fds(fds)
2328 for fd, saved, inheritable in saved_fds:
2329 if fd == 0:
2330 stdin = saved
2331 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002332 try:
2333 for fd in fds:
2334 os.close(fd)
2335 out, err = subprocess.Popen([sys.executable, "-c",
2336 'import sys;'
2337 'sys.stdout.write("apple");'
2338 'sys.stdout.flush();'
2339 'sys.stderr.write("orange")'],
2340 stdin=stdin,
2341 stdout=subprocess.PIPE,
2342 stderr=subprocess.PIPE).communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002343 self.assertEqual(out, b'apple')
2344 self.assertEqual(err, b'orange')
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002345 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002346 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002347
2348 def test_close_fd_0(self):
2349 self.check_close_std_fds([0])
2350
2351 def test_close_fd_1(self):
2352 self.check_close_std_fds([1])
2353
2354 def test_close_fd_2(self):
2355 self.check_close_std_fds([2])
2356
2357 def test_close_fds_0_1(self):
2358 self.check_close_std_fds([0, 1])
2359
2360 def test_close_fds_0_2(self):
2361 self.check_close_std_fds([0, 2])
2362
2363 def test_close_fds_1_2(self):
2364 self.check_close_std_fds([1, 2])
2365
2366 def test_close_fds_0_1_2(self):
2367 # Issue #10806: test that subprocess pipes still work properly with
2368 # all standard fds closed.
2369 self.check_close_std_fds([0, 1, 2])
2370
Gregory P. Smith53dd8162013-12-01 16:03:24 -08002371 def test_small_errpipe_write_fd(self):
2372 """Issue #15798: Popen should work when stdio fds are available."""
2373 new_stdin = os.dup(0)
2374 new_stdout = os.dup(1)
2375 try:
2376 os.close(0)
2377 os.close(1)
2378
2379 # Side test: if errpipe_write fails to have its CLOEXEC
2380 # flag set this should cause the parent to think the exec
2381 # failed. Extremely unlikely: everyone supports CLOEXEC.
2382 subprocess.Popen([
2383 sys.executable, "-c",
2384 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
2385 finally:
2386 # Restore original stdin and stdout
2387 os.dup2(new_stdin, 0)
2388 os.dup2(new_stdout, 1)
2389 os.close(new_stdin)
2390 os.close(new_stdout)
2391
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002392 def test_remapping_std_fds(self):
2393 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002394 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002395 try:
2396 temp_fds = [fd for fd, fname in temps]
2397
2398 # unlink the files -- we won't need to reopen them
2399 for fd, fname in temps:
2400 os.unlink(fname)
2401
2402 # write some data to what will become stdin, and rewind
2403 os.write(temp_fds[1], b"STDIN")
2404 os.lseek(temp_fds[1], 0, 0)
2405
2406 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02002407 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002408 try:
2409 # duplicate the file objects over the standard fd's
2410 for fd, temp_fd in enumerate(temp_fds):
2411 os.dup2(temp_fd, fd)
2412
2413 # now use those files in the "wrong" order, so that subprocess
2414 # has to rearrange them in the child
2415 p = subprocess.Popen([sys.executable, "-c",
2416 'import sys; got = sys.stdin.read();'
2417 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2418 stdin=temp_fds[1],
2419 stdout=temp_fds[2],
2420 stderr=temp_fds[0])
2421 p.wait()
2422 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002423 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002424
2425 for fd in temp_fds:
2426 os.lseek(fd, 0, 0)
2427
2428 out = os.read(temp_fds[2], 1024)
Victor Stinner6cac1132019-12-08 08:38:16 +01002429 err = os.read(temp_fds[0], 1024).strip()
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002430 self.assertEqual(out, b"got STDIN")
2431 self.assertEqual(err, b"err")
2432
2433 finally:
2434 for fd in temp_fds:
2435 os.close(fd)
2436
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002437 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
2438 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002439 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002440 temp_fds = [fd for fd, fname in temps]
2441 try:
2442 # unlink the files -- we won't need to reopen them
2443 for fd, fname in temps:
2444 os.unlink(fname)
2445
2446 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02002447 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002448 try:
2449 # duplicate the temp files over the standard fd's 0, 1, 2
2450 for fd, temp_fd in enumerate(temp_fds):
2451 os.dup2(temp_fd, fd)
2452
2453 # write some data to what will become stdin, and rewind
2454 os.write(stdin_no, b"STDIN")
2455 os.lseek(stdin_no, 0, 0)
2456
2457 # now use those files in the given order, so that subprocess
2458 # has to rearrange them in the child
2459 p = subprocess.Popen([sys.executable, "-c",
2460 'import sys; got = sys.stdin.read();'
2461 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2462 stdin=stdin_no,
2463 stdout=stdout_no,
2464 stderr=stderr_no)
2465 p.wait()
2466
2467 for fd in temp_fds:
2468 os.lseek(fd, 0, 0)
2469
2470 out = os.read(stdout_no, 1024)
Victor Stinner6cac1132019-12-08 08:38:16 +01002471 err = os.read(stderr_no, 1024).strip()
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002472 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002473 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002474
2475 self.assertEqual(out, b"got STDIN")
2476 self.assertEqual(err, b"err")
2477
2478 finally:
2479 for fd in temp_fds:
2480 os.close(fd)
2481
2482 # When duping fds, if there arises a situation where one of the fds is
2483 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
2484 # This tests all combinations of this.
2485 def test_swap_fds(self):
2486 self.check_swap_fds(0, 1, 2)
2487 self.check_swap_fds(0, 2, 1)
2488 self.check_swap_fds(1, 0, 2)
2489 self.check_swap_fds(1, 2, 0)
2490 self.check_swap_fds(2, 0, 1)
2491 self.check_swap_fds(2, 1, 0)
2492
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +03002493 def _check_swap_std_fds_with_one_closed(self, from_fds, to_fds):
2494 saved_fds = self._save_fds(range(3))
2495 try:
2496 for from_fd in from_fds:
2497 with tempfile.TemporaryFile() as f:
2498 os.dup2(f.fileno(), from_fd)
2499
2500 fd_to_close = (set(range(3)) - set(from_fds)).pop()
2501 os.close(fd_to_close)
2502
2503 arg_names = ['stdin', 'stdout', 'stderr']
2504 kwargs = {}
2505 for from_fd, to_fd in zip(from_fds, to_fds):
2506 kwargs[arg_names[to_fd]] = from_fd
2507
2508 code = textwrap.dedent(r'''
2509 import os, sys
2510 skipped_fd = int(sys.argv[1])
2511 for fd in range(3):
2512 if fd != skipped_fd:
2513 os.write(fd, str(fd).encode('ascii'))
2514 ''')
2515
2516 skipped_fd = (set(range(3)) - set(to_fds)).pop()
2517
2518 rc = subprocess.call([sys.executable, '-c', code, str(skipped_fd)],
2519 **kwargs)
2520 self.assertEqual(rc, 0)
2521
2522 for from_fd, to_fd in zip(from_fds, to_fds):
2523 os.lseek(from_fd, 0, os.SEEK_SET)
2524 read_bytes = os.read(from_fd, 1024)
2525 read_fds = list(map(int, read_bytes.decode('ascii')))
2526 msg = textwrap.dedent(f"""
2527 When testing {from_fds} to {to_fds} redirection,
2528 parent descriptor {from_fd} got redirected
2529 to descriptor(s) {read_fds} instead of descriptor {to_fd}.
2530 """)
2531 self.assertEqual([to_fd], read_fds, msg)
2532 finally:
2533 self._restore_fds(saved_fds)
2534
2535 # Check that subprocess can remap std fds correctly even
2536 # if one of them is closed (#32844).
2537 def test_swap_std_fds_with_one_closed(self):
2538 for from_fds in itertools.combinations(range(3), 2):
2539 for to_fds in itertools.permutations(range(3), 2):
2540 self._check_swap_std_fds_with_one_closed(from_fds, to_fds)
2541
Victor Stinner13bb71c2010-04-23 21:41:56 +00002542 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00002543 def prepare():
2544 raise ValueError("surrogate:\uDCff")
2545
2546 try:
2547 subprocess.call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002548 ZERO_RETURN_CMD,
Victor Stinner4d078042010-04-23 19:28:32 +00002549 preexec_fn=prepare)
2550 except ValueError as err:
2551 # Pure Python implementations keeps the message
2552 self.assertIsNone(subprocess._posixsubprocess)
2553 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002554 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00002555 # _posixsubprocess uses a default message
2556 self.assertIsNotNone(subprocess._posixsubprocess)
2557 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
2558 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002559 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00002560
Victor Stinner13bb71c2010-04-23 21:41:56 +00002561 def test_undecodable_env(self):
2562 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01002563 encoded_value = value.encode("ascii", "surrogateescape")
2564
Victor Stinner13bb71c2010-04-23 21:41:56 +00002565 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002566 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002567 env = os.environ.copy()
2568 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01002569 # Use C locale to get ASCII for the locale encoding to force
Michael Felt89d79b12018-08-26 19:29:36 +02002570 # surrogate-escaping of \xFF in the child process
Victor Stinnerebc78d22010-10-14 10:38:17 +00002571 env['LC_ALL'] = 'C'
Michael Felt89d79b12018-08-26 19:29:36 +02002572 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002573 stdout = subprocess.check_output(
2574 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002575 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002576 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002577 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002578
2579 # test bytes
2580 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002581 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002582 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01002583 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002584 stdout = subprocess.check_output(
2585 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002586 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002587 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002588 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002589
Victor Stinnerb745a742010-05-18 17:17:23 +00002590 def test_bytes_program(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002591 abs_program = os.fsencode(ZERO_RETURN_CMD[0])
2592 args = list(ZERO_RETURN_CMD[1:])
2593 path, program = os.path.split(ZERO_RETURN_CMD[0])
Victor Stinnerb745a742010-05-18 17:17:23 +00002594 program = os.fsencode(program)
2595
2596 # absolute bytes path
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002597 exitcode = subprocess.call([abs_program]+args)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002598 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002599
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002600 # absolute bytes path as a string
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002601 cmd = b"'%s' %s" % (abs_program, " ".join(args).encode("utf-8"))
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002602 exitcode = subprocess.call(cmd, shell=True)
2603 self.assertEqual(exitcode, 0)
2604
Victor Stinnerb745a742010-05-18 17:17:23 +00002605 # bytes program, unicode PATH
2606 env = os.environ.copy()
2607 env["PATH"] = path
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002608 exitcode = subprocess.call([program]+args, env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002609 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002610
2611 # bytes program, bytes PATH
2612 envb = os.environb.copy()
2613 envb[b"PATH"] = os.fsencode(path)
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002614 exitcode = subprocess.call([program]+args, env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002615 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002616
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002617 def test_pipe_cloexec(self):
2618 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2619 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2620
2621 p1 = subprocess.Popen([sys.executable, sleeper],
2622 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2623 stderr=subprocess.PIPE, close_fds=False)
2624
2625 self.addCleanup(p1.communicate, b'')
2626
2627 p2 = subprocess.Popen([sys.executable, fd_status],
2628 stdout=subprocess.PIPE, close_fds=False)
2629
2630 output, error = p2.communicate()
2631 result_fds = set(map(int, output.split(b',')))
2632 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2633 p1.stderr.fileno()])
2634
2635 self.assertFalse(result_fds & unwanted_fds,
2636 "Expected no fds from %r to be open in child, "
2637 "found %r" %
2638 (unwanted_fds, result_fds & unwanted_fds))
2639
2640 def test_pipe_cloexec_real_tools(self):
2641 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2642 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2643
2644 subdata = b'zxcvbn'
2645 data = subdata * 4 + b'\n'
2646
2647 p1 = subprocess.Popen([sys.executable, qcat],
2648 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2649 close_fds=False)
2650
2651 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2652 stdin=p1.stdout, stdout=subprocess.PIPE,
2653 close_fds=False)
2654
2655 self.addCleanup(p1.wait)
2656 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002657 def kill_p1():
2658 try:
2659 p1.terminate()
2660 except ProcessLookupError:
2661 pass
2662 def kill_p2():
2663 try:
2664 p2.terminate()
2665 except ProcessLookupError:
2666 pass
2667 self.addCleanup(kill_p1)
2668 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002669
2670 p1.stdin.write(data)
2671 p1.stdin.close()
2672
2673 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2674
2675 self.assertTrue(readfiles, "The child hung")
2676 self.assertEqual(p2.stdout.read(), data)
2677
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002678 p1.stdout.close()
2679 p2.stdout.close()
2680
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002681 def test_close_fds(self):
2682 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2683
2684 fds = os.pipe()
2685 self.addCleanup(os.close, fds[0])
2686 self.addCleanup(os.close, fds[1])
2687
2688 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002689 # add a bunch more fds
2690 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002691 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002692 self.addCleanup(os.close, fd)
2693 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002694
Victor Stinnerdaf45552013-08-28 00:53:59 +02002695 for fd in open_fds:
2696 os.set_inheritable(fd, True)
2697
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002698 p = subprocess.Popen([sys.executable, fd_status],
2699 stdout=subprocess.PIPE, close_fds=False)
2700 output, ignored = p.communicate()
2701 remaining_fds = set(map(int, output.split(b',')))
2702
2703 self.assertEqual(remaining_fds & open_fds, open_fds,
2704 "Some fds were closed")
2705
2706 p = subprocess.Popen([sys.executable, fd_status],
2707 stdout=subprocess.PIPE, close_fds=True)
2708 output, ignored = p.communicate()
2709 remaining_fds = set(map(int, output.split(b',')))
2710
2711 self.assertFalse(remaining_fds & open_fds,
2712 "Some fds were left open")
2713 self.assertIn(1, remaining_fds, "Subprocess failed")
2714
Gregory P. Smith8facece2012-01-21 14:01:08 -08002715 # Keep some of the fd's we opened open in the subprocess.
2716 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2717 fds_to_keep = set(open_fds.pop() for _ in range(8))
2718 p = subprocess.Popen([sys.executable, fd_status],
2719 stdout=subprocess.PIPE, close_fds=True,
izbyshev2d8f0632017-12-19 03:26:49 +07002720 pass_fds=fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002721 output, ignored = p.communicate()
2722 remaining_fds = set(map(int, output.split(b',')))
2723
izbyshev2d8f0632017-12-19 03:26:49 +07002724 self.assertFalse((remaining_fds - fds_to_keep) & open_fds,
Gregory P. Smith8facece2012-01-21 14:01:08 -08002725 "Some fds not in pass_fds were left open")
2726 self.assertIn(1, remaining_fds, "Subprocess failed")
2727
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002728
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002729 @unittest.skipIf(sys.platform.startswith("freebsd") and
2730 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2731 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002732 def test_close_fds_when_max_fd_is_lowered(self):
2733 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2734 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2735
Gregory P. Smith634aa682014-06-15 17:51:04 -07002736 # This launches the meat of the test in a child process to
2737 # avoid messing with the larger unittest processes maximum
2738 # number of file descriptors.
2739 # This process launches:
2740 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2741 # a bunch of high open fds above the new lower rlimit.
2742 # Those are reported via stdout before launching a new
2743 # process with close_fds=False to run the actual test:
2744 # +--> The TEST: This one launches a fd_status.py
2745 # subprocess with close_fds=True so we can find out if
2746 # any of the fds above the lowered rlimit are still open.
2747 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2748 '''
2749 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002750 open_fds = set()
2751 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002752 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002753 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002754 open_fds.add(fd)
2755
2756 # Leave a two pairs of low ones available for use by the
2757 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002758 # We also leave 10 more open as some Python buildbots run into
2759 # "too many open files" errors during the test if we do not.
2760 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002761 os.close(fd)
2762 open_fds.remove(fd)
2763
2764 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002765 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002766 os.set_inheritable(fd, True)
2767
2768 max_fd_open = max(open_fds)
2769
Gregory P. Smith634aa682014-06-15 17:51:04 -07002770 # Communicate the open_fds to the parent unittest.TestCase process.
2771 print(','.join(map(str, sorted(open_fds))))
2772 sys.stdout.flush()
2773
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002774 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2775 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002776 # 29 is lower than the highest fds we are leaving open.
2777 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002778 # Launch a new Python interpreter with our low fd rlim_cur that
2779 # inherits open fds above that limit. It then uses subprocess
2780 # with close_fds=True to get a report of open fds in the child.
2781 # An explicit list of fds to check is passed to fd_status.py as
2782 # letting fd_status rely on its default logic would miss the
2783 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002784 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002785 [sys.executable, '-c',
2786 textwrap.dedent("""
2787 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002788 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002789 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002790 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002791 """.format(max_fd=max_fd_open+1))],
2792 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002793 finally:
2794 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002795 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002796
2797 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002798 output_lines = output.splitlines()
2799 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002800 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002801 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2802 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002803
Gregory P. Smith634aa682014-06-15 17:51:04 -07002804 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002805 msg="Some fds were left open.")
2806
2807
Victor Stinner88701e22011-06-01 13:13:04 +02002808 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2809 # descriptor of a pipe closed in the parent process is valid in the
2810 # child process according to fstat(), but the mode of the file
2811 # descriptor is invalid, and read or write raise an error.
2812 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002813 def test_pass_fds(self):
2814 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2815
2816 open_fds = set()
2817
2818 for x in range(5):
2819 fds = os.pipe()
2820 self.addCleanup(os.close, fds[0])
2821 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002822 os.set_inheritable(fds[0], True)
2823 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002824 open_fds.update(fds)
2825
2826 for fd in open_fds:
2827 p = subprocess.Popen([sys.executable, fd_status],
2828 stdout=subprocess.PIPE, close_fds=True,
2829 pass_fds=(fd, ))
2830 output, ignored = p.communicate()
2831
2832 remaining_fds = set(map(int, output.split(b',')))
2833 to_be_closed = open_fds - {fd}
2834
2835 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2836 self.assertFalse(remaining_fds & to_be_closed,
2837 "fd to be closed passed")
2838
2839 # pass_fds overrides close_fds with a warning.
2840 with self.assertWarns(RuntimeWarning) as context:
2841 self.assertFalse(subprocess.call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002842 ZERO_RETURN_CMD,
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002843 close_fds=False, pass_fds=(fd, )))
2844 self.assertIn('overriding close_fds', str(context.warning))
2845
Victor Stinnerdaf45552013-08-28 00:53:59 +02002846 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002847 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002848
2849 inheritable, non_inheritable = os.pipe()
2850 self.addCleanup(os.close, inheritable)
2851 self.addCleanup(os.close, non_inheritable)
2852 os.set_inheritable(inheritable, True)
2853 os.set_inheritable(non_inheritable, False)
2854 pass_fds = (inheritable, non_inheritable)
2855 args = [sys.executable, script]
2856 args += list(map(str, pass_fds))
2857
2858 p = subprocess.Popen(args,
2859 stdout=subprocess.PIPE, close_fds=True,
2860 pass_fds=pass_fds)
2861 output, ignored = p.communicate()
2862 fds = set(map(int, output.split(b',')))
2863
2864 # the inheritable file descriptor must be inherited, so its inheritable
2865 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002866 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002867
2868 # inheritable flag must not be changed in the parent process
2869 self.assertEqual(os.get_inheritable(inheritable), True)
2870 self.assertEqual(os.get_inheritable(non_inheritable), False)
2871
Gregory P. Smithce344102018-09-10 17:46:22 -07002872
2873 # bpo-32270: Ensure that descriptors specified in pass_fds
2874 # are inherited even if they are used in redirections.
2875 # Contributed by @izbyshev.
2876 def test_pass_fds_redirected(self):
2877 """Regression test for https://bugs.python.org/issue32270."""
2878 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2879 pass_fds = []
2880 for _ in range(2):
2881 fd = os.open(os.devnull, os.O_RDWR)
2882 self.addCleanup(os.close, fd)
2883 pass_fds.append(fd)
2884
2885 stdout_r, stdout_w = os.pipe()
2886 self.addCleanup(os.close, stdout_r)
2887 self.addCleanup(os.close, stdout_w)
2888 pass_fds.insert(1, stdout_w)
2889
2890 with subprocess.Popen([sys.executable, fd_status],
2891 stdin=pass_fds[0],
2892 stdout=pass_fds[1],
2893 stderr=pass_fds[2],
2894 close_fds=True,
2895 pass_fds=pass_fds):
2896 output = os.read(stdout_r, 1024)
2897 fds = {int(num) for num in output.split(b',')}
2898
2899 self.assertEqual(fds, {0, 1, 2} | frozenset(pass_fds), f"output={output!a}")
2900
2901
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002902 def test_stdout_stdin_are_single_inout_fd(self):
2903 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002904 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002905 stdout=inout, stdin=inout)
2906 p.wait()
2907
2908 def test_stdout_stderr_are_single_inout_fd(self):
2909 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002910 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002911 stdout=inout, stderr=inout)
2912 p.wait()
2913
2914 def test_stderr_stdin_are_single_inout_fd(self):
2915 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002916 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002917 stderr=inout, stdin=inout)
2918 p.wait()
2919
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002920 def test_wait_when_sigchild_ignored(self):
2921 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2922 sigchild_ignore = support.findfile("sigchild_ignore.py",
2923 subdir="subprocessdata")
2924 p = subprocess.Popen([sys.executable, sigchild_ignore],
2925 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2926 stdout, stderr = p.communicate()
2927 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002928 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002929 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002930
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002931 def test_select_unbuffered(self):
2932 # Issue #11459: bufsize=0 should really set the pipes as
2933 # unbuffered (and therefore let select() work properly).
Hai Shi0c4f0f32020-06-30 21:46:31 +08002934 select = import_helper.import_module("select")
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002935 p = subprocess.Popen([sys.executable, "-c",
2936 'import sys;'
2937 'sys.stdout.write("apple")'],
2938 stdout=subprocess.PIPE,
2939 bufsize=0)
2940 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002941 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002942 try:
2943 self.assertEqual(f.read(4), b"appl")
2944 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2945 finally:
2946 p.wait()
2947
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002948 def test_zombie_fast_process_del(self):
2949 # Issue #12650: on Unix, if Popen.__del__() was called before the
2950 # process exited, it wouldn't be added to subprocess._active, and would
2951 # remain a zombie.
2952 # spawn a Popen, and delete its reference before it exits
2953 p = subprocess.Popen([sys.executable, "-c",
2954 'import sys, time;'
2955 'time.sleep(0.2)'],
2956 stdout=subprocess.PIPE,
2957 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002958 self.addCleanup(p.stdout.close)
2959 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002960 ident = id(p)
2961 pid = p.pid
Hai Shi0c4f0f32020-06-30 21:46:31 +08002962 with warnings_helper.check_warnings(('', ResourceWarning)):
Victor Stinner5a48e212016-05-20 12:11:15 +02002963 p = None
2964
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002965 if mswindows:
2966 # subprocess._active is not used on Windows and is set to None.
2967 self.assertIsNone(subprocess._active)
2968 else:
2969 # check that p is in the active processes list
2970 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002971
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002972 def test_leak_fast_process_del_killed(self):
2973 # Issue #12650: on Unix, if Popen.__del__() was called before the
2974 # process exited, and the process got killed by a signal, it would never
2975 # be removed from subprocess._active, which triggered a FD and memory
2976 # leak.
2977 # spawn a Popen, delete its reference and kill it
2978 p = subprocess.Popen([sys.executable, "-c",
2979 'import time;'
2980 'time.sleep(3)'],
2981 stdout=subprocess.PIPE,
2982 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002983 self.addCleanup(p.stdout.close)
2984 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002985 ident = id(p)
2986 pid = p.pid
Hai Shi0c4f0f32020-06-30 21:46:31 +08002987 with warnings_helper.check_warnings(('', ResourceWarning)):
Victor Stinner5a48e212016-05-20 12:11:15 +02002988 p = None
2989
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002990 os.kill(pid, signal.SIGKILL)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002991 if mswindows:
2992 # subprocess._active is not used on Windows and is set to None.
2993 self.assertIsNone(subprocess._active)
2994 else:
2995 # check that p is in the active processes list
2996 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002997
2998 # let some time for the process to exit, and create a new Popen: this
2999 # should trigger the wait() of p
3000 time.sleep(0.2)
Victor Stinnerb31206a2018-01-25 19:06:05 +01003001 with self.assertRaises(OSError):
Victor Stinner9a83f652017-08-21 23:51:31 +02003002 with subprocess.Popen(NONEXISTING_CMD,
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003003 stdout=subprocess.PIPE,
3004 stderr=subprocess.PIPE) as proc:
3005 pass
3006 # p should have been wait()ed on, and removed from the _active list
3007 self.assertRaises(OSError, os.waitpid, pid, 0)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03003008 if mswindows:
3009 # subprocess._active is not used on Windows and is set to None.
3010 self.assertIsNone(subprocess._active)
3011 else:
3012 self.assertNotIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003013
Charles-François Natali249cdc32013-08-25 18:24:45 +02003014 def test_close_fds_after_preexec(self):
3015 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
3016
3017 # this FD is used as dup2() target by preexec_fn, and should be closed
3018 # in the child process
3019 fd = os.dup(1)
3020 self.addCleanup(os.close, fd)
3021
3022 p = subprocess.Popen([sys.executable, fd_status],
3023 stdout=subprocess.PIPE, close_fds=True,
3024 preexec_fn=lambda: os.dup2(1, fd))
3025 output, ignored = p.communicate()
3026
3027 remaining_fds = set(map(int, output.split(b',')))
3028
3029 self.assertNotIn(fd, remaining_fds)
3030
Victor Stinner8f437aa2014-10-05 17:25:19 +02003031 @support.cpython_only
3032 def test_fork_exec(self):
3033 # Issue #22290: fork_exec() must not crash on memory allocation failure
3034 # or other errors
3035 import _posixsubprocess
3036 gc_enabled = gc.isenabled()
3037 try:
3038 # Use a preexec function and enable the garbage collector
3039 # to force fork_exec() to re-enable the garbage collector
3040 # on error.
3041 func = lambda: None
3042 gc.enable()
3043
Victor Stinner8f437aa2014-10-05 17:25:19 +02003044 for args, exe_list, cwd, env_list in (
3045 (123, [b"exe"], None, [b"env"]),
3046 ([b"arg"], 123, None, [b"env"]),
3047 ([b"arg"], [b"exe"], 123, [b"env"]),
3048 ([b"arg"], [b"exe"], None, 123),
3049 ):
Patrick McLean2b2ead72019-09-12 10:15:44 -07003050 with self.assertRaises(TypeError) as err:
Victor Stinner8f437aa2014-10-05 17:25:19 +02003051 _posixsubprocess.fork_exec(
3052 args, exe_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003053 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02003054 -1, -1, -1, -1,
3055 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003056 True, True,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07003057 False, [], 0, -1,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003058 func)
3059 # Attempt to prevent
3060 # "TypeError: fork_exec() takes exactly N arguments (M given)"
3061 # from passing the test. More refactoring to have us start
3062 # with a valid *args list, confirm a good call with that works
3063 # before mutating it in various ways to ensure that bad calls
3064 # with individual arg type errors raise a typeerror would be
3065 # ideal. Saving that for a future PR...
3066 self.assertNotIn('takes exactly', str(err.exception))
Victor Stinner8f437aa2014-10-05 17:25:19 +02003067 finally:
3068 if not gc_enabled:
3069 gc.disable()
3070
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003071 @support.cpython_only
3072 def test_fork_exec_sorted_fd_sanity_check(self):
3073 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
3074 import _posixsubprocess
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003075 class BadInt:
3076 first = True
3077 def __init__(self, value):
3078 self.value = value
3079 def __int__(self):
3080 if self.first:
3081 self.first = False
3082 return self.value
3083 raise ValueError
3084
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003085 gc_enabled = gc.isenabled()
3086 try:
3087 gc.enable()
3088
3089 for fds_to_keep in (
3090 (-1, 2, 3, 4, 5), # Negative number.
3091 ('str', 4), # Not an int.
3092 (18, 23, 42, 2**63), # Out of range.
3093 (5, 4), # Not sorted.
3094 (6, 7, 7, 8), # Duplicate.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003095 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003096 ):
3097 with self.assertRaises(
3098 ValueError,
3099 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
3100 _posixsubprocess.fork_exec(
3101 [b"false"], [b"false"],
3102 True, fds_to_keep, None, [b"env"],
3103 -1, -1, -1, -1,
3104 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003105 True, True,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07003106 None, None, None, -1,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003107 None)
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003108 self.assertIn('fds_to_keep', str(c.exception))
3109 finally:
3110 if not gc_enabled:
3111 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02003112
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003113 def test_communicate_BrokenPipeError_stdin_close(self):
3114 # By not setting stdout or stderr or a timeout we force the fast path
3115 # that just calls _stdin_write() internally due to our mock.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003116 proc = subprocess.Popen(ZERO_RETURN_CMD)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003117 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3118 mock_proc_stdin.close.side_effect = BrokenPipeError
3119 proc.communicate() # Should swallow BrokenPipeError from close.
3120 mock_proc_stdin.close.assert_called_with()
3121
3122 def test_communicate_BrokenPipeError_stdin_write(self):
3123 # By not setting stdout or stderr or a timeout we force the fast path
3124 # that just calls _stdin_write() internally due to our mock.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003125 proc = subprocess.Popen(ZERO_RETURN_CMD)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003126 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3127 mock_proc_stdin.write.side_effect = BrokenPipeError
3128 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
3129 mock_proc_stdin.write.assert_called_once_with(b'stuff')
3130 mock_proc_stdin.close.assert_called_once_with()
3131
3132 def test_communicate_BrokenPipeError_stdin_flush(self):
3133 # Setting stdin and stdout forces the ._communicate() code path.
3134 # python -h exits faster than python -c pass (but spams stdout).
3135 proc = subprocess.Popen([sys.executable, '-h'],
3136 stdin=subprocess.PIPE,
3137 stdout=subprocess.PIPE)
3138 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
3139 open(os.devnull, 'wb') as dev_null:
3140 mock_proc_stdin.flush.side_effect = BrokenPipeError
3141 # because _communicate registers a selector using proc.stdin...
3142 mock_proc_stdin.fileno.return_value = dev_null.fileno()
3143 # _communicate() should swallow BrokenPipeError from flush.
3144 proc.communicate(b'stuff')
3145 mock_proc_stdin.flush.assert_called_once_with()
3146
3147 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
3148 # Setting stdin and stdout forces the ._communicate() code path.
3149 # python -h exits faster than python -c pass (but spams stdout).
3150 proc = subprocess.Popen([sys.executable, '-h'],
3151 stdin=subprocess.PIPE,
3152 stdout=subprocess.PIPE)
3153 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3154 mock_proc_stdin.close.side_effect = BrokenPipeError
3155 # _communicate() should swallow BrokenPipeError from close.
3156 proc.communicate(timeout=999)
3157 mock_proc_stdin.close.assert_called_once_with()
3158
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003159 @unittest.skipUnless(_testcapi is not None
3160 and hasattr(_testcapi, 'W_STOPCODE'),
3161 'need _testcapi.W_STOPCODE')
3162 def test_stopped(self):
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003163 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003164 args = ZERO_RETURN_CMD
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003165 proc = subprocess.Popen(args)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003166
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003167 # Wait until the real process completes to avoid zombie process
Victor Stinner278c1e12020-03-31 20:08:12 +02003168 support.wait_process(proc.pid, exitcode=0)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003169
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003170 status = _testcapi.W_STOPCODE(3)
Victor Stinner278c1e12020-03-31 20:08:12 +02003171 with mock.patch('subprocess.os.waitpid', return_value=(proc.pid, status)):
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003172 returncode = proc.wait()
Victor Stinnercdee3f12017-06-26 17:23:03 +02003173
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003174 self.assertEqual(returncode, -3)
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003175
Victor Stinnere85a3052020-01-15 17:38:55 +01003176 def test_send_signal_race(self):
3177 # bpo-38630: send_signal() must poll the process exit status to reduce
3178 # the risk of sending the signal to the wrong process.
3179 proc = subprocess.Popen(ZERO_RETURN_CMD)
3180
3181 # wait until the process completes without using the Popen APIs.
Victor Stinner278c1e12020-03-31 20:08:12 +02003182 support.wait_process(proc.pid, exitcode=0)
Victor Stinnere85a3052020-01-15 17:38:55 +01003183
3184 # returncode is still None but the process completed.
3185 self.assertIsNone(proc.returncode)
3186
3187 with mock.patch("os.kill") as mock_kill:
3188 proc.send_signal(signal.SIGTERM)
3189
3190 # send_signal() didn't call os.kill() since the process already
3191 # completed.
3192 mock_kill.assert_not_called()
3193
3194 # Don't check the returncode value: the test reads the exit status,
3195 # so Popen failed to read it and uses a default returncode instead.
3196 self.assertIsNotNone(proc.returncode)
3197
Alex Rebertd3ae95e2020-01-22 18:28:31 -05003198 def test_communicate_repeated_call_after_stdout_close(self):
3199 proc = subprocess.Popen([sys.executable, '-c',
3200 'import os, time; os.close(1), time.sleep(2)'],
3201 stdout=subprocess.PIPE)
3202 while True:
3203 try:
3204 proc.communicate(timeout=0.1)
3205 return
3206 except subprocess.TimeoutExpired:
3207 pass
3208
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003209
Victor Stinner937ee9e2018-06-26 02:11:06 +02003210@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00003211class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00003212
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003213 def test_startupinfo(self):
3214 # startupinfo argument
3215 # We uses hardcoded constants, because we do not want to
3216 # depend on win32all.
3217 STARTF_USESHOWWINDOW = 1
3218 SW_MAXIMIZE = 3
3219 startupinfo = subprocess.STARTUPINFO()
3220 startupinfo.dwFlags = STARTF_USESHOWWINDOW
3221 startupinfo.wShowWindow = SW_MAXIMIZE
3222 # Since Python is a console process, it won't be affected
3223 # by wShowWindow, but the argument should be silently
3224 # ignored
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003225 subprocess.call(ZERO_RETURN_CMD,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003226 startupinfo=startupinfo)
3227
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05303228 def test_startupinfo_keywords(self):
3229 # startupinfo argument
3230 # We use hardcoded constants, because we do not want to
3231 # depend on win32all.
3232 STARTF_USERSHOWWINDOW = 1
3233 SW_MAXIMIZE = 3
3234 startupinfo = subprocess.STARTUPINFO(
3235 dwFlags=STARTF_USERSHOWWINDOW,
3236 wShowWindow=SW_MAXIMIZE
3237 )
3238 # Since Python is a console process, it won't be affected
3239 # by wShowWindow, but the argument should be silently
3240 # ignored
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003241 subprocess.call(ZERO_RETURN_CMD,
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05303242 startupinfo=startupinfo)
3243
Victor Stinner483422f2018-07-05 22:54:17 +02003244 def test_startupinfo_copy(self):
3245 # bpo-34044: Popen must not modify input STARTUPINFO structure
3246 startupinfo = subprocess.STARTUPINFO()
3247 startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
3248 startupinfo.wShowWindow = subprocess.SW_HIDE
3249
3250 # Call Popen() twice with the same startupinfo object to make sure
3251 # that it's not modified
3252 for _ in range(2):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003253 cmd = ZERO_RETURN_CMD
Victor Stinner483422f2018-07-05 22:54:17 +02003254 with open(os.devnull, 'w') as null:
3255 proc = subprocess.Popen(cmd,
3256 stdout=null,
3257 stderr=subprocess.STDOUT,
3258 startupinfo=startupinfo)
3259 with proc:
3260 proc.communicate()
3261 self.assertEqual(proc.returncode, 0)
3262
3263 self.assertEqual(startupinfo.dwFlags,
3264 subprocess.STARTF_USESHOWWINDOW)
3265 self.assertIsNone(startupinfo.hStdInput)
3266 self.assertIsNone(startupinfo.hStdOutput)
3267 self.assertIsNone(startupinfo.hStdError)
3268 self.assertEqual(startupinfo.wShowWindow, subprocess.SW_HIDE)
3269 self.assertEqual(startupinfo.lpAttributeList, {"handle_list": []})
3270
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003271 def test_creationflags(self):
3272 # creationflags argument
3273 CREATE_NEW_CONSOLE = 16
3274 sys.stderr.write(" a DOS box should flash briefly ...\n")
3275 subprocess.call(sys.executable +
3276 ' -c "import time; time.sleep(0.25)"',
3277 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003278
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003279 def test_invalid_args(self):
3280 # invalid arguments should raise ValueError
3281 self.assertRaises(ValueError, subprocess.call,
3282 [sys.executable, "-c",
3283 "import sys; sys.exit(47)"],
3284 preexec_fn=lambda: 1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003285
Oren Milman0b3a87e2017-09-14 22:30:28 +03003286 @support.cpython_only
3287 def test_issue31471(self):
3288 # There shouldn't be an assertion failure in Popen() in case the env
3289 # argument has a bad keys() method.
3290 class BadEnv(dict):
3291 keys = None
3292 with self.assertRaises(TypeError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003293 subprocess.Popen(ZERO_RETURN_CMD, env=BadEnv())
Oren Milman0b3a87e2017-09-14 22:30:28 +03003294
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003295 def test_close_fds(self):
3296 # close file descriptors
3297 rc = subprocess.call([sys.executable, "-c",
3298 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003299 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003300 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003301
Segev Finerb2a60832017-12-18 11:28:19 +02003302 def test_close_fds_with_stdio(self):
3303 import msvcrt
3304
3305 fds = os.pipe()
3306 self.addCleanup(os.close, fds[0])
3307 self.addCleanup(os.close, fds[1])
3308
3309 handles = []
3310 for fd in fds:
3311 os.set_inheritable(fd, True)
3312 handles.append(msvcrt.get_osfhandle(fd))
3313
3314 p = subprocess.Popen([sys.executable, "-c",
3315 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3316 stdout=subprocess.PIPE, close_fds=False)
3317 stdout, stderr = p.communicate()
3318 self.assertEqual(p.returncode, 0)
3319 int(stdout.strip()) # Check that stdout is an integer
3320
3321 p = subprocess.Popen([sys.executable, "-c",
3322 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3323 stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
3324 stdout, stderr = p.communicate()
3325 self.assertEqual(p.returncode, 1)
3326 self.assertIn(b"OSError", stderr)
3327
3328 # The same as the previous call, but with an empty handle_list
3329 handle_list = []
3330 startupinfo = subprocess.STARTUPINFO()
3331 startupinfo.lpAttributeList = {"handle_list": handle_list}
3332 p = subprocess.Popen([sys.executable, "-c",
3333 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3334 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3335 startupinfo=startupinfo, close_fds=True)
3336 stdout, stderr = p.communicate()
3337 self.assertEqual(p.returncode, 1)
3338 self.assertIn(b"OSError", stderr)
3339
3340 # Check for a warning due to using handle_list and close_fds=False
Hai Shi0c4f0f32020-06-30 21:46:31 +08003341 with warnings_helper.check_warnings((".*overriding close_fds",
3342 RuntimeWarning)):
Segev Finerb2a60832017-12-18 11:28:19 +02003343 startupinfo = subprocess.STARTUPINFO()
3344 startupinfo.lpAttributeList = {"handle_list": handles[:]}
3345 p = subprocess.Popen([sys.executable, "-c",
3346 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3347 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3348 startupinfo=startupinfo, close_fds=False)
3349 stdout, stderr = p.communicate()
3350 self.assertEqual(p.returncode, 0)
3351
3352 def test_empty_attribute_list(self):
3353 startupinfo = subprocess.STARTUPINFO()
3354 startupinfo.lpAttributeList = {}
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003355 subprocess.call(ZERO_RETURN_CMD,
Segev Finerb2a60832017-12-18 11:28:19 +02003356 startupinfo=startupinfo)
3357
3358 def test_empty_handle_list(self):
3359 startupinfo = subprocess.STARTUPINFO()
3360 startupinfo.lpAttributeList = {"handle_list": []}
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003361 subprocess.call(ZERO_RETURN_CMD,
Segev Finerb2a60832017-12-18 11:28:19 +02003362 startupinfo=startupinfo)
3363
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003364 def test_shell_sequence(self):
3365 # Run command through the shell (sequence)
3366 newenv = os.environ.copy()
3367 newenv["FRUIT"] = "physalis"
3368 p = subprocess.Popen(["set"], shell=1,
3369 stdout=subprocess.PIPE,
3370 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003371 with p:
3372 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00003373
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003374 def test_shell_string(self):
3375 # Run command through the shell (string)
3376 newenv = os.environ.copy()
3377 newenv["FRUIT"] = "physalis"
3378 p = subprocess.Popen("set", shell=1,
3379 stdout=subprocess.PIPE,
3380 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003381 with p:
3382 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003383
Steve Dower050acae2016-09-06 20:16:17 -07003384 def test_shell_encodings(self):
3385 # Run command through the shell (string)
3386 for enc in ['ansi', 'oem']:
3387 newenv = os.environ.copy()
3388 newenv["FRUIT"] = "physalis"
3389 p = subprocess.Popen("set", shell=1,
3390 stdout=subprocess.PIPE,
3391 env=newenv,
3392 encoding=enc)
3393 with p:
3394 self.assertIn("physalis", p.stdout.read(), enc)
3395
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003396 def test_call_string(self):
3397 # call() function with string argument on Windows
3398 rc = subprocess.call(sys.executable +
3399 ' -c "import sys; sys.exit(47)"')
3400 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003401
Florent Xicluna4886d242010-03-08 13:27:26 +00003402 def _kill_process(self, method, *args):
3403 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00003404 p = subprocess.Popen([sys.executable, "-c", """if 1:
3405 import sys, time
3406 sys.stdout.write('x\\n')
3407 sys.stdout.flush()
3408 time.sleep(30)
3409 """],
3410 stdin=subprocess.PIPE,
3411 stdout=subprocess.PIPE,
3412 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003413 with p:
3414 # Wait for the interpreter to be completely initialized before
3415 # sending any signal.
3416 p.stdout.read(1)
3417 getattr(p, method)(*args)
3418 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01003419 self.assertEqual(stderr, b'')
Victor Stinner7438c612016-05-20 12:43:15 +02003420 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00003421 self.assertNotEqual(returncode, 0)
3422
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003423 def _kill_dead_process(self, method, *args):
3424 p = subprocess.Popen([sys.executable, "-c", """if 1:
3425 import sys, time
3426 sys.stdout.write('x\\n')
3427 sys.stdout.flush()
3428 sys.exit(42)
3429 """],
3430 stdin=subprocess.PIPE,
3431 stdout=subprocess.PIPE,
3432 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003433 with p:
3434 # Wait for the interpreter to be completely initialized before
3435 # sending any signal.
3436 p.stdout.read(1)
3437 # The process should end after this
3438 time.sleep(1)
3439 # This shouldn't raise even though the child is now dead
3440 getattr(p, method)(*args)
3441 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01003442 self.assertEqual(stderr, b'')
Victor Stinner7438c612016-05-20 12:43:15 +02003443 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003444 self.assertEqual(rc, 42)
3445
Florent Xicluna4886d242010-03-08 13:27:26 +00003446 def test_send_signal(self):
3447 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00003448
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003449 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003450 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00003451
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003452 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003453 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00003454
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003455 def test_send_signal_dead(self):
3456 self._kill_dead_process('send_signal', signal.SIGTERM)
3457
3458 def test_kill_dead(self):
3459 self._kill_dead_process('kill')
3460
3461 def test_terminate_dead(self):
3462 self._kill_dead_process('terminate')
3463
Martin Panter23172bd2016-04-16 11:28:10 +00003464class MiscTests(unittest.TestCase):
Gregory P. Smithf4d644f2018-01-29 21:27:39 -08003465
3466 class RecordingPopen(subprocess.Popen):
3467 """A Popen that saves a reference to each instance for testing."""
3468 instances_created = []
3469
3470 def __init__(self, *args, **kwargs):
3471 super().__init__(*args, **kwargs)
3472 self.instances_created.append(self)
3473
3474 @mock.patch.object(subprocess.Popen, "_communicate")
3475 def _test_keyboardinterrupt_no_kill(self, popener, mock__communicate,
3476 **kwargs):
3477 """Fake a SIGINT happening during Popen._communicate() and ._wait().
3478
3479 This avoids the need to actually try and get test environments to send
3480 and receive signals reliably across platforms. The net effect of a ^C
3481 happening during a blocking subprocess execution which we want to clean
3482 up from is a KeyboardInterrupt coming out of communicate() or wait().
3483 """
3484
3485 mock__communicate.side_effect = KeyboardInterrupt
3486 try:
3487 with mock.patch.object(subprocess.Popen, "_wait") as mock__wait:
3488 # We patch out _wait() as no signal was involved so the
3489 # child process isn't actually going to exit rapidly.
3490 mock__wait.side_effect = KeyboardInterrupt
3491 with mock.patch.object(subprocess, "Popen",
3492 self.RecordingPopen):
3493 with self.assertRaises(KeyboardInterrupt):
3494 popener([sys.executable, "-c",
3495 "import time\ntime.sleep(9)\nimport sys\n"
3496 "sys.stderr.write('\\n!runaway child!\\n')"],
3497 stdout=subprocess.DEVNULL, **kwargs)
3498 for call in mock__wait.call_args_list[1:]:
3499 self.assertNotEqual(
3500 call, mock.call(timeout=None),
3501 "no open-ended wait() after the first allowed: "
3502 f"{mock__wait.call_args_list}")
3503 sigint_calls = []
3504 for call in mock__wait.call_args_list:
3505 if call == mock.call(timeout=0.25): # from Popen.__init__
3506 sigint_calls.append(call)
3507 self.assertLessEqual(mock__wait.call_count, 2,
3508 msg=mock__wait.call_args_list)
3509 self.assertEqual(len(sigint_calls), 1,
3510 msg=mock__wait.call_args_list)
3511 finally:
3512 # cleanup the forgotten (due to our mocks) child process
3513 process = self.RecordingPopen.instances_created.pop()
3514 process.kill()
3515 process.wait()
3516 self.assertEqual([], self.RecordingPopen.instances_created)
3517
3518 def test_call_keyboardinterrupt_no_kill(self):
3519 self._test_keyboardinterrupt_no_kill(subprocess.call, timeout=6.282)
3520
3521 def test_run_keyboardinterrupt_no_kill(self):
3522 self._test_keyboardinterrupt_no_kill(subprocess.run, timeout=6.282)
3523
3524 def test_context_manager_keyboardinterrupt_no_kill(self):
3525 def popen_via_context_manager(*args, **kwargs):
3526 with subprocess.Popen(*args, **kwargs) as unused_process:
3527 raise KeyboardInterrupt # Test how __exit__ handles ^C.
3528 self._test_keyboardinterrupt_no_kill(popen_via_context_manager)
3529
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003530 def test_getoutput(self):
3531 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
3532 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
3533 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00003534
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003535 # we use mkdtemp in the next line to create an empty directory
3536 # under our exclusive control; from that, we can invent a pathname
3537 # that we _know_ won't exist. This is guaranteed to fail.
3538 dir = None
3539 try:
3540 dir = tempfile.mkdtemp()
3541 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00003542 status, output = subprocess.getstatusoutput(
Victor Stinner937ee9e2018-06-26 02:11:06 +02003543 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003544 self.assertNotEqual(status, 0)
3545 finally:
3546 if dir is not None:
3547 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00003548
Gregory P. Smithace55862015-04-07 15:57:54 -07003549 def test__all__(self):
3550 """Ensure that __all__ is populated properly."""
Ruben Vorderman23c0fb82020-10-20 01:30:02 +02003551 intentionally_excluded = {"list2cmdline", "Handle", "pwd", "grp", "fcntl"}
Gregory P. Smithace55862015-04-07 15:57:54 -07003552 exported = set(subprocess.__all__)
3553 possible_exports = set()
3554 import types
3555 for name, value in subprocess.__dict__.items():
3556 if name.startswith('_'):
3557 continue
3558 if isinstance(value, (types.ModuleType,)):
3559 continue
3560 possible_exports.add(name)
3561 self.assertEqual(exported, possible_exports - intentionally_excluded)
3562
3563
Martin Panter23172bd2016-04-16 11:28:10 +00003564@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
3565 "Test needs selectors.PollSelector")
3566class ProcessTestCaseNoPoll(ProcessTestCase):
3567 def setUp(self):
3568 self.orig_selector = subprocess._PopenSelector
3569 subprocess._PopenSelector = selectors.SelectSelector
3570 ProcessTestCase.setUp(self)
3571
3572 def tearDown(self):
3573 subprocess._PopenSelector = self.orig_selector
3574 ProcessTestCase.tearDown(self)
3575
Gregory P. Smithd06fa472009-07-04 02:46:54 +00003576
Victor Stinner937ee9e2018-06-26 02:11:06 +02003577@unittest.skipUnless(mswindows, "Windows-specific tests")
Tim Golden126c2962010-08-11 14:20:40 +00003578class CommandsWithSpaces (BaseTestCase):
3579
3580 def setUp(self):
3581 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03003582 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00003583 self.fname = fname.lower ()
3584 os.write(f, b"import sys;"
3585 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
3586 )
3587 os.close(f)
3588
3589 def tearDown(self):
3590 os.remove(self.fname)
3591 super().tearDown()
3592
3593 def with_spaces(self, *args, **kwargs):
3594 kwargs['stdout'] = subprocess.PIPE
3595 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02003596 with p:
3597 self.assertEqual(
3598 p.stdout.read ().decode("mbcs"),
3599 "2 [%r, 'ab cd']" % self.fname
3600 )
Tim Golden126c2962010-08-11 14:20:40 +00003601
3602 def test_shell_string_with_spaces(self):
3603 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003604 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3605 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003606
3607 def test_shell_sequence_with_spaces(self):
3608 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003609 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003610
3611 def test_noshell_string_with_spaces(self):
3612 # call() function with string argument with spaces on Windows
3613 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3614 "ab cd"))
3615
3616 def test_noshell_sequence_with_spaces(self):
3617 # call() function with sequence argument with spaces on Windows
3618 self.with_spaces([sys.executable, self.fname, "ab cd"])
3619
Brian Curtin79cdb662010-12-03 02:46:02 +00003620
Georg Brandla86b2622012-02-20 21:34:57 +01003621class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00003622
3623 def test_pipe(self):
3624 with subprocess.Popen([sys.executable, "-c",
3625 "import sys;"
3626 "sys.stdout.write('stdout');"
3627 "sys.stderr.write('stderr');"],
3628 stdout=subprocess.PIPE,
3629 stderr=subprocess.PIPE) as proc:
3630 self.assertEqual(proc.stdout.read(), b"stdout")
Victor Stinner6cac1132019-12-08 08:38:16 +01003631 self.assertEqual(proc.stderr.read(), b"stderr")
Brian Curtin79cdb662010-12-03 02:46:02 +00003632
3633 self.assertTrue(proc.stdout.closed)
3634 self.assertTrue(proc.stderr.closed)
3635
3636 def test_returncode(self):
3637 with subprocess.Popen([sys.executable, "-c",
3638 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07003639 pass
3640 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00003641 self.assertEqual(proc.returncode, 100)
3642
3643 def test_communicate_stdin(self):
3644 with subprocess.Popen([sys.executable, "-c",
3645 "import sys;"
3646 "sys.exit(sys.stdin.read() == 'context')"],
3647 stdin=subprocess.PIPE) as proc:
3648 proc.communicate(b"context")
3649 self.assertEqual(proc.returncode, 1)
3650
3651 def test_invalid_args(self):
Victor Stinnerb31206a2018-01-25 19:06:05 +01003652 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02003653 with subprocess.Popen(NONEXISTING_CMD,
Brian Curtin79cdb662010-12-03 02:46:02 +00003654 stdout=subprocess.PIPE,
3655 stderr=subprocess.PIPE) as proc:
3656 pass
3657
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003658 def test_broken_pipe_cleanup(self):
3659 """Broken pipe error should not prevent wait() (Issue 21619)"""
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003660 proc = subprocess.Popen(ZERO_RETURN_CMD,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003661 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003662 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003663 proc = proc.__enter__()
3664 # Prepare to send enough data to overflow any OS pipe buffering and
3665 # guarantee a broken pipe error. Data is held in BufferedWriter
3666 # buffer until closed.
3667 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003668 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003669 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02003670 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003671 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003672 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003673
Brian Curtin79cdb662010-12-03 02:46:02 +00003674
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003675if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04003676 unittest.main()