blob: 2a4c47530e6a1bd3c29f83f3c21364e704254f71 [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
Gregory P. Smith786addd2020-10-20 17:37:20 -0700669 @unittest.skipUnless(fcntl and hasattr(fcntl, 'F_GETPIPE_SZ'),
670 'fcntl.F_GETPIPE_SZ required for test.')
Ruben Vorderman23c0fb82020-10-20 01:30:02 +0200671 def test_pipesizes(self):
Gregory P. Smith786addd2020-10-20 17:37:20 -0700672 test_pipe_r, test_pipe_w = os.pipe()
673 try:
674 # Get the default pipesize with F_GETPIPE_SZ
675 pipesize_default = fcntl.fcntl(test_pipe_w, fcntl.F_GETPIPE_SZ)
676 finally:
677 os.close(test_pipe_r)
678 os.close(test_pipe_w)
679 pipesize = pipesize_default // 2
680 if pipesize < 512: # the POSIX minimum
681 raise unittest.SkitTest(
682 'default pipesize too small to perform test.')
683 p = subprocess.Popen(
684 [sys.executable, "-c",
685 'import sys; sys.stdin.read(); sys.stdout.write("out"); '
686 'sys.stderr.write("error!")'],
687 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
688 stderr=subprocess.PIPE, pipesize=pipesize)
689 try:
Ruben Vorderman23c0fb82020-10-20 01:30:02 +0200690 for fifo in [p.stdin, p.stdout, p.stderr]:
691 self.assertEqual(
Gregory P. Smith786addd2020-10-20 17:37:20 -0700692 fcntl.fcntl(fifo.fileno(), fcntl.F_GETPIPE_SZ),
693 pipesize)
694 # Windows pipe size can be acquired via GetNamedPipeInfoFunction
695 # https://docs.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-getnamedpipeinfo
696 # However, this function is not yet in _winapi.
697 p.stdin.write(b"pear")
698 p.stdin.close()
699 finally:
700 p.kill()
701 p.wait()
702
703 @unittest.skipUnless(fcntl and hasattr(fcntl, 'F_GETPIPE_SZ'),
704 'fcntl.F_GETPIPE_SZ required for test.')
705 def test_pipesize_default(self):
706 p = subprocess.Popen(
707 [sys.executable, "-c",
708 'import sys; sys.stdin.read(); sys.stdout.write("out"); '
709 'sys.stderr.write("error!")'],
710 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
711 stderr=subprocess.PIPE, pipesize=-1)
712 try:
713 fp_r, fp_w = os.pipe()
714 try:
715 default_pipesize = fcntl.fcntl(fp_w, fcntl.F_GETPIPE_SZ)
716 for fifo in [p.stdin, p.stdout, p.stderr]:
717 self.assertEqual(
718 fcntl.fcntl(fifo.fileno(), fcntl.F_GETPIPE_SZ),
719 default_pipesize)
720 finally:
721 os.close(fp_r)
722 os.close(fp_w)
723 # On other platforms we cannot test the pipe size (yet). But above
724 # code using pipesize=-1 should not crash.
725 p.stdin.close()
726 finally:
727 p.kill()
728 p.wait()
Ruben Vorderman23c0fb82020-10-20 01:30:02 +0200729
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000730 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000731 newenv = os.environ.copy()
732 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200733 with subprocess.Popen([sys.executable, "-c",
734 'import sys,os;'
735 'sys.stdout.write(os.getenv("FRUIT"))'],
736 stdout=subprocess.PIPE,
737 env=newenv) as p:
738 stdout, stderr = p.communicate()
739 self.assertEqual(stdout, b"orange")
740
Victor Stinner62d51182011-06-23 01:02:25 +0200741 # Windows requires at least the SYSTEMROOT environment variable to start
742 # Python
743 @unittest.skipIf(sys.platform == 'win32',
744 'cannot test an empty env on Windows')
Gregory P. Smithb3512482017-05-30 14:40:37 -0700745 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
746 'The Python shared library cannot be loaded '
747 'with an empty environment.')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200748 def test_empty_env(self):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700749 """Verify that env={} is as empty as possible."""
750
Gregory P. Smith85aba232017-05-30 16:21:47 -0700751 def is_env_var_to_ignore(n):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700752 """Determine if an environment variable is under our control."""
753 # This excludes some __CF_* and VERSIONER_* keys MacOS insists
754 # on adding even when the environment in exec is empty.
755 # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist.
Gregory P. Smith85aba232017-05-30 16:21:47 -0700756 return ('VERSIONER' in n or '__CF' in n or # MacOS
Nick Coghlan6ea41862017-06-11 13:16:15 +1000757 n == 'LD_PRELOAD' or n.startswith('SANDBOX') or # Gentoo
758 n == 'LC_CTYPE') # Locale coercion triggered
Gregory P. Smithb3512482017-05-30 14:40:37 -0700759
Victor Stinnerf1512a22011-06-21 17:18:38 +0200760 with subprocess.Popen([sys.executable, "-c",
Gregory P. Smithb3512482017-05-30 14:40:37 -0700761 'import os; print(list(os.environ.keys()))'],
762 stdout=subprocess.PIPE, env={}) as p:
Victor Stinnerf1512a22011-06-21 17:18:38 +0200763 stdout, stderr = p.communicate()
Gregory P. Smithb3512482017-05-30 14:40:37 -0700764 child_env_names = eval(stdout.strip())
765 self.assertIsInstance(child_env_names, list)
766 child_env_names = [k for k in child_env_names
767 if not is_env_var_to_ignore(k)]
768 self.assertEqual(child_env_names, [])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000769
Serhiy Storchakad174d242017-06-23 19:39:27 +0300770 def test_invalid_cmd(self):
771 # null character in the command name
772 cmd = sys.executable + '\0'
773 with self.assertRaises(ValueError):
774 subprocess.Popen([cmd, "-c", "pass"])
775
776 # null character in the command argument
777 with self.assertRaises(ValueError):
778 subprocess.Popen([sys.executable, "-c", "pass#\0"])
779
780 def test_invalid_env(self):
Ville Skyttä49b27342017-08-03 09:00:59 +0300781 # null character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300782 newenv = os.environ.copy()
783 newenv["FRUIT\0VEGETABLE"] = "cabbage"
784 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700785 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300786
Ville Skyttä49b27342017-08-03 09:00:59 +0300787 # null character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300788 newenv = os.environ.copy()
789 newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
790 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700791 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300792
Ville Skyttä49b27342017-08-03 09:00:59 +0300793 # equal character in the environment variable name
Serhiy Storchakad174d242017-06-23 19:39:27 +0300794 newenv = os.environ.copy()
795 newenv["FRUIT=ORANGE"] = "lemon"
796 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700797 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
Serhiy Storchakad174d242017-06-23 19:39:27 +0300798
Ville Skyttä49b27342017-08-03 09:00:59 +0300799 # equal character in the environment variable value
Serhiy Storchakad174d242017-06-23 19:39:27 +0300800 newenv = os.environ.copy()
801 newenv["FRUIT"] = "orange=lemon"
802 with subprocess.Popen([sys.executable, "-c",
803 'import sys, os;'
804 'sys.stdout.write(os.getenv("FRUIT"))'],
805 stdout=subprocess.PIPE,
806 env=newenv) as p:
807 stdout, stderr = p.communicate()
808 self.assertEqual(stdout, b"orange=lemon")
809
Peter Astrandcbac93c2005-03-03 20:24:28 +0000810 def test_communicate_stdin(self):
811 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000812 'import sys;'
813 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000814 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000815 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000816 self.assertEqual(p.returncode, 1)
817
818 def test_communicate_stdout(self):
819 p = subprocess.Popen([sys.executable, "-c",
820 'import sys; sys.stdout.write("pineapple")'],
821 stdout=subprocess.PIPE)
822 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000823 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000824 self.assertEqual(stderr, None)
825
826 def test_communicate_stderr(self):
827 p = subprocess.Popen([sys.executable, "-c",
828 'import sys; sys.stderr.write("pineapple")'],
829 stderr=subprocess.PIPE)
830 (stdout, stderr) = p.communicate()
831 self.assertEqual(stdout, None)
Victor Stinner6cac1132019-12-08 08:38:16 +0100832 self.assertEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000833
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000834 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000835 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000836 'import sys,os;'
837 'sys.stderr.write("pineapple");'
838 'sys.stdout.write(sys.stdin.read())'],
839 stdin=subprocess.PIPE,
840 stdout=subprocess.PIPE,
841 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000842 self.addCleanup(p.stdout.close)
843 self.addCleanup(p.stderr.close)
844 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000845 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000846 self.assertEqual(stdout, b"banana")
Victor Stinner6cac1132019-12-08 08:38:16 +0100847 self.assertEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000848
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400849 def test_communicate_timeout(self):
850 p = subprocess.Popen([sys.executable, "-c",
851 'import sys,os,time;'
852 'sys.stderr.write("pineapple\\n");'
853 'time.sleep(1);'
854 'sys.stderr.write("pear\\n");'
855 'sys.stdout.write(sys.stdin.read())'],
856 universal_newlines=True,
857 stdin=subprocess.PIPE,
858 stdout=subprocess.PIPE,
859 stderr=subprocess.PIPE)
860 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
861 timeout=0.3)
862 # Make sure we can keep waiting for it, and that we get the whole output
863 # after it completes.
864 (stdout, stderr) = p.communicate()
865 self.assertEqual(stdout, "banana")
Victor Stinner6cac1132019-12-08 08:38:16 +0100866 self.assertEqual(stderr.encode(), b"pineapple\npear\n")
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400867
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700868 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200869 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400870 p = subprocess.Popen([sys.executable, "-c",
871 'import sys,os,time;'
872 'sys.stdout.write("a" * (64 * 1024));'
873 'time.sleep(0.2);'
874 'sys.stdout.write("a" * (64 * 1024));'
875 'time.sleep(0.2);'
876 'sys.stdout.write("a" * (64 * 1024));'
877 'time.sleep(0.2);'
878 'sys.stdout.write("a" * (64 * 1024));'],
879 stdout=subprocess.PIPE)
880 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
881 (stdout, _) = p.communicate()
882 self.assertEqual(len(stdout), 4 * 64 * 1024)
883
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000884 # Test for the fd leak reported in http://bugs.python.org/issue2791.
885 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000886 for stdin_pipe in (False, True):
887 for stdout_pipe in (False, True):
888 for stderr_pipe in (False, True):
889 options = {}
890 if stdin_pipe:
891 options['stdin'] = subprocess.PIPE
892 if stdout_pipe:
893 options['stdout'] = subprocess.PIPE
894 if stderr_pipe:
895 options['stderr'] = subprocess.PIPE
896 if not options:
897 continue
Gregory P. Smith67b93f82019-10-12 16:35:53 -0700898 p = subprocess.Popen(ZERO_RETURN_CMD, **options)
Victor Stinner667d4b52010-12-25 22:40:32 +0000899 p.communicate()
900 if p.stdin is not None:
901 self.assertTrue(p.stdin.closed)
902 if p.stdout is not None:
903 self.assertTrue(p.stdout.closed)
904 if p.stderr is not None:
905 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000906
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000907 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000908 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000909 p = subprocess.Popen([sys.executable, "-c",
910 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000911 (stdout, stderr) = p.communicate()
912 self.assertEqual(stdout, None)
913 self.assertEqual(stderr, None)
914
915 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000916 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000917 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000918 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000919 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000920 os.close(x)
921 os.close(y)
922 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000923 'import sys,os;'
924 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200925 'sys.stderr.write("x" * %d);'
926 'sys.stdout.write(sys.stdin.read())' %
927 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000928 stdin=subprocess.PIPE,
929 stdout=subprocess.PIPE,
930 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000931 self.addCleanup(p.stdout.close)
932 self.addCleanup(p.stderr.close)
933 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200934 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000935 (stdout, stderr) = p.communicate(string_to_write)
936 self.assertEqual(stdout, string_to_write)
937
938 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000939 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000940 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000941 'import sys,os;'
942 'sys.stdout.write(sys.stdin.read())'],
943 stdin=subprocess.PIPE,
944 stdout=subprocess.PIPE,
945 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000946 self.addCleanup(p.stdout.close)
947 self.addCleanup(p.stderr.close)
948 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000949 p.stdin.write(b"banana")
950 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000951 self.assertEqual(stdout, b"bananasplit")
Victor Stinner6cac1132019-12-08 08:38:16 +0100952 self.assertEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000953
andyclegg7fed7bd2017-10-23 03:01:19 +0100954 def test_universal_newlines_and_text(self):
955 args = [
956 sys.executable, "-c",
957 'import sys,os;' + SETBINARY +
958 'buf = sys.stdout.buffer;'
959 'buf.write(sys.stdin.readline().encode());'
960 'buf.flush();'
961 'buf.write(b"line2\\n");'
962 'buf.flush();'
963 'buf.write(sys.stdin.read().encode());'
964 'buf.flush();'
965 'buf.write(b"line4\\n");'
966 'buf.flush();'
967 'buf.write(b"line5\\r\\n");'
968 'buf.flush();'
969 'buf.write(b"line6\\r");'
970 'buf.flush();'
971 'buf.write(b"\\nline7");'
972 'buf.flush();'
973 'buf.write(b"\\nline8");']
974
975 for extra_kwarg in ('universal_newlines', 'text'):
976 p = subprocess.Popen(args, **{'stdin': subprocess.PIPE,
977 'stdout': subprocess.PIPE,
978 extra_kwarg: True})
979 with p:
980 p.stdin.write("line1\n")
981 p.stdin.flush()
982 self.assertEqual(p.stdout.readline(), "line1\n")
983 p.stdin.write("line3\n")
984 p.stdin.close()
985 self.addCleanup(p.stdout.close)
986 self.assertEqual(p.stdout.readline(),
987 "line2\n")
988 self.assertEqual(p.stdout.read(6),
989 "line3\n")
990 self.assertEqual(p.stdout.read(),
991 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000992
993 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000994 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000995 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000996 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200997 'buf = sys.stdout.buffer;'
998 'buf.write(b"line2\\n");'
999 'buf.flush();'
1000 'buf.write(b"line4\\n");'
1001 'buf.flush();'
1002 'buf.write(b"line5\\r\\n");'
1003 'buf.flush();'
1004 'buf.write(b"line6\\r");'
1005 'buf.flush();'
1006 'buf.write(b"\\nline7");'
1007 'buf.flush();'
1008 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +02001009 stderr=subprocess.PIPE,
1010 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +00001011 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +00001012 self.addCleanup(p.stdout.close)
1013 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001014 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +02001015 self.assertEqual(stdout,
1016 "line2\nline4\nline5\nline6\nline7\nline8")
1017
1018 def test_universal_newlines_communicate_stdin(self):
1019 # universal newlines through communicate(), with only stdin
1020 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +03001021 'import sys,os;' + SETBINARY + textwrap.dedent('''
1022 s = sys.stdin.readline()
1023 assert s == "line1\\n", repr(s)
1024 s = sys.stdin.read()
1025 assert s == "line3\\n", repr(s)
1026 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +02001027 stdin=subprocess.PIPE,
1028 universal_newlines=1)
1029 (stdout, stderr) = p.communicate("line1\nline3\n")
1030 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001031
Andrew Svetlovf3765072012-08-14 18:35:17 +03001032 def test_universal_newlines_communicate_input_none(self):
1033 # Test communicate(input=None) with universal newlines.
1034 #
1035 # We set stdout to PIPE because, as of this writing, a different
1036 # code path is tested when the number of pipes is zero or one.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001037 p = subprocess.Popen(ZERO_RETURN_CMD,
Andrew Svetlovf3765072012-08-14 18:35:17 +03001038 stdin=subprocess.PIPE,
1039 stdout=subprocess.PIPE,
1040 universal_newlines=True)
1041 p.communicate()
1042 self.assertEqual(p.returncode, 0)
1043
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001044 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +03001045 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001046 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +03001047 'import sys,os;' + SETBINARY + textwrap.dedent('''
1048 s = sys.stdin.buffer.readline()
1049 sys.stdout.buffer.write(s)
1050 sys.stdout.buffer.write(b"line2\\r")
1051 sys.stderr.buffer.write(b"eline2\\n")
1052 s = sys.stdin.buffer.read()
1053 sys.stdout.buffer.write(s)
1054 sys.stdout.buffer.write(b"line4\\n")
1055 sys.stdout.buffer.write(b"line5\\r\\n")
1056 sys.stderr.buffer.write(b"eline6\\r")
1057 sys.stderr.buffer.write(b"eline7\\r\\nz")
1058 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001059 stdin=subprocess.PIPE,
1060 stderr=subprocess.PIPE,
1061 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +03001062 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001063 self.addCleanup(p.stdout.close)
1064 self.addCleanup(p.stderr.close)
1065 (stdout, stderr) = p.communicate("line1\nline3\n")
1066 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +03001067 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001068 # Python debug build push something like "[42442 refs]\n"
1069 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +03001070 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +03001071
Andrew Svetlov82860712012-08-19 22:13:41 +03001072 def test_universal_newlines_communicate_encodings(self):
1073 # Check that universal newlines mode works for various encodings,
1074 # in particular for encodings in the UTF-16 and UTF-32 families.
1075 # See issue #15595.
1076 #
1077 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
1078 # without, and UTF-16 and UTF-32.
1079 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +03001080 code = ("import sys; "
1081 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
1082 encoding)
1083 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -07001084 # We set stdin to be non-None because, as of this writing,
1085 # a different code path is used when the number of pipes is
1086 # zero or one.
1087 popen = subprocess.Popen(args,
1088 stdin=subprocess.PIPE,
1089 stdout=subprocess.PIPE,
1090 encoding=encoding)
1091 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +03001092 self.assertEqual(stdout, '1\n2\n3\n4')
1093
Steve Dower050acae2016-09-06 20:16:17 -07001094 def test_communicate_errors(self):
1095 for errors, expected in [
1096 ('ignore', ''),
1097 ('replace', '\ufffd\ufffd'),
1098 ('surrogateescape', '\udc80\udc80'),
1099 ('backslashreplace', '\\x80\\x80'),
1100 ]:
1101 code = ("import sys; "
1102 r"sys.stdout.buffer.write(b'[\x80\x80]')")
1103 args = [sys.executable, '-c', code]
1104 # We set stdin to be non-None because, as of this writing,
1105 # a different code path is used when the number of pipes is
1106 # zero or one.
1107 popen = subprocess.Popen(args,
1108 stdin=subprocess.PIPE,
1109 stdout=subprocess.PIPE,
1110 encoding='utf-8',
1111 errors=errors)
1112 stdout, stderr = popen.communicate(input='')
1113 self.assertEqual(stdout, '[{}]'.format(expected))
1114
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001115 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +00001116 # Make sure we leak no resources
Victor Stinner937ee9e2018-06-26 02:11:06 +02001117 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +00001118 max_handles = 1026 # too much for most UNIX systems
1119 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +00001120 max_handles = 2050 # too much for (at least some) Windows setups
1121 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001122 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +00001123 try:
1124 for i in range(max_handles):
1125 try:
Hai Shi0c4f0f32020-06-30 21:46:31 +08001126 tmpfile = os.path.join(tmpdir, os_helper.TESTFN)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001127 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +00001128 except OSError as e:
1129 if e.errno != errno.EMFILE:
1130 raise
1131 break
1132 else:
1133 self.skipTest("failed to reach the file descriptor limit "
1134 "(tried %d)" % max_handles)
1135 # Close a couple of them (should be enough for a subprocess)
1136 for i in range(10):
1137 os.close(handles.pop())
1138 # Loop creating some subprocesses. If one of them leaks some fds,
1139 # the next loop iteration will fail by reaching the max fd limit.
1140 for i in range(15):
1141 p = subprocess.Popen([sys.executable, "-c",
1142 "import sys;"
1143 "sys.stdout.write(sys.stdin.read())"],
1144 stdin=subprocess.PIPE,
1145 stdout=subprocess.PIPE,
1146 stderr=subprocess.PIPE)
1147 data = p.communicate(b"lime")[0]
1148 self.assertEqual(data, b"lime")
1149 finally:
1150 for h in handles:
1151 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -04001152 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001153
1154 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001155 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
1156 '"a b c" d e')
1157 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
1158 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +00001159 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
1160 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001161 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
1162 'a\\\\\\b "de fg" h')
1163 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
1164 'a\\\\\\"b c d')
1165 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
1166 '"a\\\\b c" d e')
1167 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
1168 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001169 self.assertEqual(subprocess.list2cmdline(['ab', '']),
1170 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001171
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001172 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001173 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +02001174 "import os; os.read(0, 1)"],
1175 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001176 self.addCleanup(p.stdin.close)
1177 self.assertIsNone(p.poll())
1178 os.write(p.stdin.fileno(), b'A')
1179 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001180 # Subsequent invocations should just return the returncode
1181 self.assertEqual(p.poll(), 0)
1182
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001183 def test_wait(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001184 p = subprocess.Popen(ZERO_RETURN_CMD)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001185 self.assertEqual(p.wait(), 0)
1186 # Subsequent invocations should just return the returncode
1187 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001188
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001189 def test_wait_timeout(self):
1190 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001191 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001192 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001193 p.wait(timeout=0.0001)
1194 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Victor Stinner0d63bac2019-12-11 11:30:03 +01001195 self.assertEqual(p.wait(timeout=support.SHORT_TIMEOUT), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001196
Peter Astrand738131d2004-11-30 21:04:45 +00001197 def test_invalid_bufsize(self):
1198 # an invalid type of the bufsize argument should raise
1199 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001200 with self.assertRaises(TypeError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001201 subprocess.Popen(ZERO_RETURN_CMD, "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001202
Guido van Rossum46a05a72007-06-07 21:56:45 +00001203 def test_bufsize_is_none(self):
1204 # bufsize=None should be the same as bufsize=0.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001205 p = subprocess.Popen(ZERO_RETURN_CMD, None)
Guido van Rossum46a05a72007-06-07 21:56:45 +00001206 self.assertEqual(p.wait(), 0)
1207 # Again with keyword arg
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001208 p = subprocess.Popen(ZERO_RETURN_CMD, bufsize=None)
Guido van Rossum46a05a72007-06-07 21:56:45 +00001209 self.assertEqual(p.wait(), 0)
1210
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001211 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1212 # subprocess may deadlock with bufsize=1, see issue #21332
1213 with subprocess.Popen([sys.executable, "-c", "import sys;"
1214 "sys.stdout.write(sys.stdin.readline());"
1215 "sys.stdout.flush()"],
1216 stdin=subprocess.PIPE,
1217 stdout=subprocess.PIPE,
1218 stderr=subprocess.DEVNULL,
1219 bufsize=1,
1220 universal_newlines=universal_newlines) as p:
1221 p.stdin.write(line) # expect that it flushes the line in text mode
1222 os.close(p.stdin.fileno()) # close it without flushing the buffer
1223 read_line = p.stdout.readline()
Segev Finer4d385172017-08-18 16:18:13 +03001224 with support.SuppressCrashReport():
1225 try:
1226 p.stdin.close()
1227 except OSError:
1228 pass
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001229 p.stdin = None
1230 self.assertEqual(p.returncode, 0)
1231 self.assertEqual(read_line, expected)
1232
1233 def test_bufsize_equal_one_text_mode(self):
1234 # line is flushed in text mode with bufsize=1.
1235 # we should get the full line in return
1236 line = "line\n"
1237 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1238
1239 def test_bufsize_equal_one_binary_mode(self):
1240 # line is not flushed in binary mode with bufsize=1.
1241 # we should get empty response
1242 line = b'line' + os.linesep.encode() # assume ascii-based locale
Alexey Izbysheva2670562018-10-20 03:22:31 +03001243 with self.assertWarnsRegex(RuntimeWarning, 'line buffering'):
1244 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001245
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001246 def test_leaking_fds_on_error(self):
1247 # see bug #5179: Popen leaks file descriptors to PIPEs if
1248 # the child fails to execute; this will eventually exhaust
1249 # the maximum number of open fds. 1024 seems a very common
1250 # value for that limit, but Windows has 2048, so we loop
1251 # 1024 times (each call leaked two fds).
1252 for i in range(1024):
Victor Stinnerb31206a2018-01-25 19:06:05 +01001253 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02001254 subprocess.Popen(NONEXISTING_CMD,
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001255 stdout=subprocess.PIPE,
1256 stderr=subprocess.PIPE)
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001257
Victor Stinner9a83f652017-08-21 23:51:31 +02001258 def test_nonexisting_with_pipes(self):
1259 # bpo-30121: Popen with pipes must close properly pipes on error.
1260 # Previously, os.close() was called with a Windows handle which is not
1261 # a valid file descriptor.
1262 #
1263 # Run the test in a subprocess to control how the CRT reports errors
1264 # and to get stderr content.
1265 try:
1266 import msvcrt
1267 msvcrt.CrtSetReportMode
1268 except (AttributeError, ImportError):
1269 self.skipTest("need msvcrt.CrtSetReportMode")
1270
1271 code = textwrap.dedent(f"""
1272 import msvcrt
1273 import subprocess
1274
1275 cmd = {NONEXISTING_CMD!r}
1276
1277 for report_type in [msvcrt.CRT_WARN,
1278 msvcrt.CRT_ERROR,
1279 msvcrt.CRT_ASSERT]:
1280 msvcrt.CrtSetReportMode(report_type, msvcrt.CRTDBG_MODE_FILE)
1281 msvcrt.CrtSetReportFile(report_type, msvcrt.CRTDBG_FILE_STDERR)
1282
1283 try:
Zachary Ware55376462018-02-19 14:02:38 -06001284 subprocess.Popen(cmd,
Victor Stinner9a83f652017-08-21 23:51:31 +02001285 stdout=subprocess.PIPE,
1286 stderr=subprocess.PIPE)
1287 except OSError:
1288 pass
1289 """)
1290 cmd = [sys.executable, "-c", code]
1291 proc = subprocess.Popen(cmd,
1292 stderr=subprocess.PIPE,
1293 universal_newlines=True)
1294 with proc:
1295 stderr = proc.communicate()[1]
1296 self.assertEqual(stderr, "")
1297 self.assertEqual(proc.returncode, 0)
1298
Antoine Pitroua8392712013-08-30 23:38:13 +02001299 def test_double_close_on_error(self):
1300 # Issue #18851
1301 fds = []
1302 def open_fds():
1303 for i in range(20):
1304 fds.extend(os.pipe())
1305 time.sleep(0.001)
1306 t = threading.Thread(target=open_fds)
1307 t.start()
1308 try:
1309 with self.assertRaises(EnvironmentError):
Victor Stinner9a83f652017-08-21 23:51:31 +02001310 subprocess.Popen(NONEXISTING_CMD,
Antoine Pitroua8392712013-08-30 23:38:13 +02001311 stdin=subprocess.PIPE,
1312 stdout=subprocess.PIPE,
1313 stderr=subprocess.PIPE)
1314 finally:
1315 t.join()
1316 exc = None
1317 for fd in fds:
1318 # If a double close occurred, some of those fds will
1319 # already have been closed by mistake, and os.close()
1320 # here will raise.
1321 try:
1322 os.close(fd)
1323 except OSError as e:
1324 exc = e
1325 if exc is not None:
1326 raise exc
1327
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001328 def test_threadsafe_wait(self):
1329 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1330 proc = subprocess.Popen([sys.executable, '-c',
1331 'import time; time.sleep(12)'])
1332 self.assertEqual(proc.returncode, None)
1333 results = []
1334
1335 def kill_proc_timer_thread():
1336 results.append(('thread-start-poll-result', proc.poll()))
1337 # terminate it from the thread and wait for the result.
1338 proc.kill()
1339 proc.wait()
1340 results.append(('thread-after-kill-and-wait', proc.returncode))
1341 # this wait should be a no-op given the above.
1342 proc.wait()
1343 results.append(('thread-after-second-wait', proc.returncode))
1344
1345 # This is a timing sensitive test, the failure mode is
1346 # triggered when both the main thread and this thread are in
1347 # the wait() call at once. The delay here is to allow the
1348 # main thread to most likely be blocked in its wait() call.
1349 t = threading.Timer(0.2, kill_proc_timer_thread)
1350 t.start()
1351
Victor Stinner937ee9e2018-06-26 02:11:06 +02001352 if mswindows:
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001353 expected_errorcode = 1
1354 else:
1355 # Should be -9 because of the proc.kill() from the thread.
1356 expected_errorcode = -9
1357
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001358 # Wait for the process to finish; the thread should kill it
1359 # long before it finishes on its own. Supplying a timeout
1360 # triggers a different code path for better coverage.
Victor Stinner0d63bac2019-12-11 11:30:03 +01001361 proc.wait(timeout=support.SHORT_TIMEOUT)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001362 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001363 msg="unexpected result in wait from main thread")
1364
1365 # This should be a no-op with no change in returncode.
1366 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001367 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001368 msg="unexpected result in second main wait.")
1369
1370 t.join()
1371 # Ensure that all of the thread results are as expected.
1372 # When a race condition occurs in wait(), the returncode could
1373 # be set by the wrong thread that doesn't actually have it
1374 # leading to an incorrect value.
1375 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001376 ('thread-after-kill-and-wait', expected_errorcode),
1377 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001378 results)
1379
Victor Stinnerb3693582010-05-21 20:13:12 +00001380 def test_issue8780(self):
1381 # Ensure that stdout is inherited from the parent
1382 # if stdout=PIPE is not used
1383 code = ';'.join((
1384 'import subprocess, sys',
1385 'retcode = subprocess.call('
1386 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1387 'assert retcode == 0'))
1388 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001389 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001390
Tim Goldenaf5ac392010-08-06 13:03:56 +00001391 def test_handles_closed_on_exception(self):
1392 # If CreateProcess exits with an error, ensure the
1393 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001394 ifhandle, ifname = tempfile.mkstemp()
1395 ofhandle, ofname = tempfile.mkstemp()
1396 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001397 try:
1398 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1399 stderr=efhandle)
1400 except OSError:
1401 os.close(ifhandle)
1402 os.remove(ifname)
1403 os.close(ofhandle)
1404 os.remove(ofname)
1405 os.close(efhandle)
1406 os.remove(efname)
1407 self.assertFalse(os.path.exists(ifname))
1408 self.assertFalse(os.path.exists(ofname))
1409 self.assertFalse(os.path.exists(efname))
1410
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001411 def test_communicate_epipe(self):
1412 # Issue 10963: communicate() should hide EPIPE
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001413 p = subprocess.Popen(ZERO_RETURN_CMD,
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001414 stdin=subprocess.PIPE,
1415 stdout=subprocess.PIPE,
1416 stderr=subprocess.PIPE)
1417 self.addCleanup(p.stdout.close)
1418 self.addCleanup(p.stderr.close)
1419 self.addCleanup(p.stdin.close)
1420 p.communicate(b"x" * 2**20)
1421
Andrey Doroschenko645005e2019-11-17 17:08:31 +03001422 def test_repr(self):
1423 # Run a command that waits for user input, to check the repr() of
1424 # a Proc object while and after the sub-process runs.
1425 code = 'import sys; input(); sys.exit(57)'
1426 cmd = [sys.executable, '-c', code]
1427 result = "<Popen: returncode: {}"
1428
1429 with subprocess.Popen(
1430 cmd, stdin=subprocess.PIPE, universal_newlines=True) as proc:
1431 self.assertIsNone(proc.returncode)
1432 self.assertTrue(
1433 repr(proc).startswith(result.format(proc.returncode)) and
1434 repr(proc).endswith('>')
1435 )
1436
1437 proc.communicate(input='exit...\n')
1438 proc.wait()
1439
1440 self.assertIsNotNone(proc.returncode)
1441 self.assertTrue(
1442 repr(proc).startswith(result.format(proc.returncode)) and
1443 repr(proc).endswith('>')
1444 )
1445
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001446 def test_communicate_epipe_only_stdin(self):
1447 # Issue 10963: communicate() should hide EPIPE
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001448 p = subprocess.Popen(ZERO_RETURN_CMD,
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001449 stdin=subprocess.PIPE)
1450 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001451 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001452 p.communicate(b"x" * 2**20)
1453
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001454 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1455 "Requires signal.SIGUSR1")
1456 @unittest.skipUnless(hasattr(os, 'kill'),
1457 "Requires os.kill")
1458 @unittest.skipUnless(hasattr(os, 'getppid'),
1459 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001460 def test_communicate_eintr(self):
1461 # Issue #12493: communicate() should handle EINTR
1462 def handler(signum, frame):
1463 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001464 old_handler = signal.signal(signal.SIGUSR1, handler)
1465 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001466
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001467 args = [sys.executable, "-c",
1468 'import os, signal;'
1469 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001470 for stream in ('stdout', 'stderr'):
1471 kw = {stream: subprocess.PIPE}
1472 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001473 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001474 process.communicate()
1475
Tim Peterse718f612004-10-12 21:51:32 +00001476
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001477 # This test is Linux-ish specific for simplicity to at least have
1478 # some coverage. It is not a platform specific bug.
1479 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1480 "Linux specific")
1481 def test_failed_child_execute_fd_leak(self):
1482 """Test for the fork() failure fd leak reported in issue16327."""
1483 fd_directory = '/proc/%d/fd' % os.getpid()
1484 fds_before_popen = os.listdir(fd_directory)
1485 with self.assertRaises(PopenTestException):
1486 PopenExecuteChildRaises(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001487 ZERO_RETURN_CMD, stdin=subprocess.PIPE,
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001488 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1489
1490 # NOTE: This test doesn't verify that the real _execute_child
1491 # does not close the file descriptors itself on the way out
1492 # during an exception. Code inspection has confirmed that.
1493
1494 fds_after_exception = os.listdir(fd_directory)
1495 self.assertEqual(fds_before_popen, fds_after_exception)
1496
Victor Stinner937ee9e2018-06-26 02:11:06 +02001497 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001498 def test_file_not_found_includes_filename(self):
1499 with self.assertRaises(FileNotFoundError) as c:
1500 subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args'])
1501 self.assertEqual(c.exception.filename, '/opt/nonexistent_binary')
1502
Victor Stinner937ee9e2018-06-26 02:11:06 +02001503 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
Gregory P. Smith8621bb52017-08-24 14:58:25 -07001504 def test_file_not_found_with_bad_cwd(self):
1505 with self.assertRaises(FileNotFoundError) as c:
1506 subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory')
1507 self.assertEqual(c.exception.filename, '/some/nonexistent/directory')
1508
Batuhan Taşkaya4dc5a9d2019-12-30 19:02:04 +03001509 def test_class_getitems(self):
Guido van Rossum48b069a2020-04-07 09:50:06 -07001510 self.assertIsInstance(subprocess.Popen[bytes], types.GenericAlias)
1511 self.assertIsInstance(subprocess.CompletedProcess[str], types.GenericAlias)
Gregory P. Smith6e730002015-04-14 16:14:25 -07001512
1513class RunFuncTestCase(BaseTestCase):
1514 def run_python(self, code, **kwargs):
1515 """Run Python code in a subprocess using subprocess.run"""
1516 argv = [sys.executable, "-c", code]
1517 return subprocess.run(argv, **kwargs)
1518
1519 def test_returncode(self):
1520 # call() function with sequence argument
1521 cp = self.run_python("import sys; sys.exit(47)")
1522 self.assertEqual(cp.returncode, 47)
1523 with self.assertRaises(subprocess.CalledProcessError):
1524 cp.check_returncode()
1525
1526 def test_check(self):
1527 with self.assertRaises(subprocess.CalledProcessError) as c:
1528 self.run_python("import sys; sys.exit(47)", check=True)
1529 self.assertEqual(c.exception.returncode, 47)
1530
1531 def test_check_zero(self):
1532 # check_returncode shouldn't raise when returncode is zero
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001533 cp = subprocess.run(ZERO_RETURN_CMD, check=True)
Gregory P. Smith6e730002015-04-14 16:14:25 -07001534 self.assertEqual(cp.returncode, 0)
1535
1536 def test_timeout(self):
1537 # run() function with timeout argument; we want to test that the child
1538 # process gets killed when the timeout expires. If the child isn't
1539 # killed, this call will deadlock since subprocess.run waits for the
1540 # child.
1541 with self.assertRaises(subprocess.TimeoutExpired):
1542 self.run_python("while True: pass", timeout=0.0001)
1543
1544 def test_capture_stdout(self):
1545 # capture stdout with zero return code
1546 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1547 self.assertIn(b'BDFL', cp.stdout)
1548
1549 def test_capture_stderr(self):
1550 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1551 stderr=subprocess.PIPE)
1552 self.assertIn(b'BDFL', cp.stderr)
1553
1554 def test_check_output_stdin_arg(self):
1555 # run() can be called with stdin set to a file
1556 tf = tempfile.TemporaryFile()
1557 self.addCleanup(tf.close)
1558 tf.write(b'pear')
1559 tf.seek(0)
1560 cp = self.run_python(
1561 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1562 stdin=tf, stdout=subprocess.PIPE)
1563 self.assertIn(b'PEAR', cp.stdout)
1564
1565 def test_check_output_input_arg(self):
1566 # check_output() can be called with input set to a string
1567 cp = self.run_python(
1568 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1569 input=b'pear', stdout=subprocess.PIPE)
1570 self.assertIn(b'PEAR', cp.stdout)
1571
1572 def test_check_output_stdin_with_input_arg(self):
1573 # run() refuses to accept 'stdin' with 'input'
1574 tf = tempfile.TemporaryFile()
1575 self.addCleanup(tf.close)
1576 tf.write(b'pear')
1577 tf.seek(0)
1578 with self.assertRaises(ValueError,
1579 msg="Expected ValueError when stdin and input args supplied.") as c:
1580 output = self.run_python("print('will not be run')",
1581 stdin=tf, input=b'hare')
1582 self.assertIn('stdin', c.exception.args[0])
1583 self.assertIn('input', c.exception.args[0])
1584
1585 def test_check_output_timeout(self):
1586 with self.assertRaises(subprocess.TimeoutExpired) as c:
1587 cp = self.run_python((
1588 "import sys, time\n"
1589 "sys.stdout.write('BDFL')\n"
1590 "sys.stdout.flush()\n"
1591 "time.sleep(3600)"),
1592 # Some heavily loaded buildbots (sparc Debian 3.x) require
1593 # this much time to start and print.
1594 timeout=3, stdout=subprocess.PIPE)
1595 self.assertEqual(c.exception.output, b'BDFL')
1596 # output is aliased to stdout
1597 self.assertEqual(c.exception.stdout, b'BDFL')
1598
1599 def test_run_kwargs(self):
1600 newenv = os.environ.copy()
1601 newenv["FRUIT"] = "banana"
1602 cp = self.run_python(('import sys, os;'
1603 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1604 env=newenv)
1605 self.assertEqual(cp.returncode, 33)
1606
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001607 def test_run_with_pathlike_path(self):
1608 # bpo-31961: test run(pathlike_object)
1609 # the name of a command that can be run without
Min ho Kimc4cacc82019-07-31 08:16:13 +10001610 # any arguments that exit fast
Serhiy Storchaka9e3c4522019-05-28 22:49:35 +03001611 prog = 'tree.com' if mswindows else 'ls'
1612 path = shutil.which(prog)
1613 if path is None:
1614 self.skipTest(f'{prog} required for this test')
1615 path = FakePath(path)
1616 res = subprocess.run(path, stdout=subprocess.DEVNULL)
1617 self.assertEqual(res.returncode, 0)
1618 with self.assertRaises(TypeError):
1619 subprocess.run(path, stdout=subprocess.DEVNULL, shell=True)
1620
1621 def test_run_with_bytes_path_and_arguments(self):
1622 # bpo-31961: test run([bytes_object, b'additional arguments'])
1623 path = os.fsencode(sys.executable)
1624 args = [path, '-c', b'import sys; sys.exit(57)']
1625 res = subprocess.run(args)
1626 self.assertEqual(res.returncode, 57)
1627
1628 def test_run_with_pathlike_path_and_arguments(self):
1629 # bpo-31961: test run([pathlike_object, 'additional arguments'])
1630 path = FakePath(sys.executable)
1631 args = [path, '-c', 'import sys; sys.exit(57)']
1632 res = subprocess.run(args)
1633 self.assertEqual(res.returncode, 57)
1634
Bo Baylesce0f33d2018-01-30 00:40:39 -06001635 def test_capture_output(self):
1636 cp = self.run_python(("import sys;"
1637 "sys.stdout.write('BDFL'); "
1638 "sys.stderr.write('FLUFL')"),
1639 capture_output=True)
1640 self.assertIn(b'BDFL', cp.stdout)
1641 self.assertIn(b'FLUFL', cp.stderr)
1642
1643 def test_stdout_with_capture_output_arg(self):
1644 # run() refuses to accept 'stdout' with 'capture_output'
1645 tf = tempfile.TemporaryFile()
1646 self.addCleanup(tf.close)
1647 with self.assertRaises(ValueError,
1648 msg=("Expected ValueError when stdout and capture_output "
1649 "args supplied.")) as c:
1650 output = self.run_python("print('will not be run')",
1651 capture_output=True, stdout=tf)
1652 self.assertIn('stdout', c.exception.args[0])
1653 self.assertIn('capture_output', c.exception.args[0])
1654
1655 def test_stderr_with_capture_output_arg(self):
1656 # run() refuses to accept 'stderr' with 'capture_output'
1657 tf = tempfile.TemporaryFile()
1658 self.addCleanup(tf.close)
1659 with self.assertRaises(ValueError,
1660 msg=("Expected ValueError when stderr and capture_output "
1661 "args supplied.")) as c:
1662 output = self.run_python("print('will not be run')",
1663 capture_output=True, stderr=tf)
1664 self.assertIn('stderr', c.exception.args[0])
1665 self.assertIn('capture_output', c.exception.args[0])
1666
Gregory P. Smith580d2782019-09-11 04:23:05 -05001667 # This test _might_ wind up a bit fragile on loaded build+test machines
1668 # as it depends on the timing with wide enough margins for normal situations
1669 # but does assert that it happened "soon enough" to believe the right thing
1670 # happened.
1671 @unittest.skipIf(mswindows, "requires posix like 'sleep' shell command")
1672 def test_run_with_shell_timeout_and_capture_output(self):
1673 """Output capturing after a timeout mustn't hang forever on open filehandles."""
1674 before_secs = time.monotonic()
1675 try:
1676 subprocess.run('sleep 3', shell=True, timeout=0.1,
1677 capture_output=True) # New session unspecified.
1678 except subprocess.TimeoutExpired as exc:
1679 after_secs = time.monotonic()
1680 stacks = traceback.format_exc() # assertRaises doesn't give this.
1681 else:
1682 self.fail("TimeoutExpired not raised.")
1683 self.assertLess(after_secs - before_secs, 1.5,
1684 msg="TimeoutExpired was delayed! Bad traceback:\n```\n"
1685 f"{stacks}```")
1686
Gregory P. Smith6e730002015-04-14 16:14:25 -07001687
Gregory P. Smith693aa802019-09-13 14:43:35 +01001688def _get_test_grp_name():
Victor Stinnerfaca8552019-09-25 15:52:49 +02001689 for name_group in ('staff', 'nogroup', 'grp', 'nobody', 'nfsnobody'):
Gregory P. Smith693aa802019-09-13 14:43:35 +01001690 if grp:
1691 try:
1692 grp.getgrnam(name_group)
1693 except KeyError:
1694 continue
1695 return name_group
1696 else:
1697 raise unittest.SkipTest('No identified group name to use for this test on this platform.')
1698
1699
Victor Stinner937ee9e2018-06-26 02:11:06 +02001700@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001701class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001702
Gregory P. Smith5591b022012-10-10 03:34:47 -07001703 def setUp(self):
1704 super().setUp()
1705 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1706
1707 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001708 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001709 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001710 except OSError as e:
1711 # This avoids hard coding the errno value or the OS perror()
1712 # string and instead capture the exception that we want to see
1713 # below for comparison.
1714 desired_exception = e
1715 else:
Martin Pantereb995702016-07-28 01:11:04 +00001716 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001717 self._nonexistent_dir)
1718 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001719
Gregory P. Smith5591b022012-10-10 03:34:47 -07001720 def test_exception_cwd(self):
1721 """Test error in the child raised in the parent for a bad cwd."""
1722 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001723 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001724 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001725 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001726 except OSError as e:
1727 # Test that the child process chdir failure actually makes
1728 # it up to the parent process as the correct exception.
1729 self.assertEqual(desired_exception.errno, e.errno)
1730 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001731 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001732 else:
1733 self.fail("Expected OSError: %s" % desired_exception)
1734
Gregory P. Smith5591b022012-10-10 03:34:47 -07001735 def test_exception_bad_executable(self):
1736 """Test error in the child raised in the parent for a bad executable."""
1737 desired_exception = self._get_chdir_exception()
1738 try:
1739 p = subprocess.Popen([sys.executable, "-c", ""],
1740 executable=self._nonexistent_dir)
1741 except OSError as e:
1742 # Test that the child process exec failure actually makes
1743 # it up to the parent process as the correct exception.
1744 self.assertEqual(desired_exception.errno, e.errno)
1745 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001746 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001747 else:
1748 self.fail("Expected OSError: %s" % desired_exception)
1749
1750 def test_exception_bad_args_0(self):
1751 """Test error in the child raised in the parent for a bad args[0]."""
1752 desired_exception = self._get_chdir_exception()
1753 try:
1754 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1755 except OSError as e:
1756 # Test that the child process exec failure actually makes
1757 # it up to the parent process as the correct exception.
1758 self.assertEqual(desired_exception.errno, e.errno)
1759 self.assertEqual(desired_exception.strerror, e.strerror)
Zackery Spytz73870bf2018-09-11 09:54:07 -06001760 self.assertEqual(desired_exception.filename, e.filename)
Gregory P. Smith5591b022012-10-10 03:34:47 -07001761 else:
1762 self.fail("Expected OSError: %s" % desired_exception)
1763
Ammar Askar3fc499b2017-09-06 02:41:30 -04001764 # We mock the __del__ method for Popen in the next two tests
1765 # because it does cleanup based on the pid returned by fork_exec
1766 # along with issuing a resource warning if it still exists. Since
1767 # we don't actually spawn a process in these tests we can forego
1768 # the destructor. An alternative would be to set _child_created to
1769 # False before the destructor is called but there is no easy way
1770 # to do that
1771 class PopenNoDestructor(subprocess.Popen):
1772 def __del__(self):
1773 pass
1774
1775 @mock.patch("subprocess._posixsubprocess.fork_exec")
1776 def test_exception_errpipe_normal(self, fork_exec):
1777 """Test error passing done through errpipe_write in the good case"""
1778 def proper_error(*args):
1779 errpipe_write = args[13]
1780 # Write the hex for the error code EISDIR: 'is a directory'
1781 err_code = '{:x}'.format(errno.EISDIR).encode()
1782 os.write(errpipe_write, b"OSError:" + err_code + b":")
1783 return 0
1784
1785 fork_exec.side_effect = proper_error
1786
Victor Stinner11045c92017-10-05 06:32:53 -07001787 with mock.patch("subprocess.os.waitpid",
1788 side_effect=ChildProcessError):
1789 with self.assertRaises(IsADirectoryError):
1790 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001791
1792 @mock.patch("subprocess._posixsubprocess.fork_exec")
1793 def test_exception_errpipe_bad_data(self, fork_exec):
1794 """Test error passing done through errpipe_write where its not
1795 in the expected format"""
1796 error_data = b"\xFF\x00\xDE\xAD"
1797 def bad_error(*args):
1798 errpipe_write = args[13]
1799 # Anything can be in the pipe, no assumptions should
1800 # be made about its encoding, so we'll write some
1801 # arbitrary hex bytes to test it out
1802 os.write(errpipe_write, error_data)
1803 return 0
1804
1805 fork_exec.side_effect = bad_error
1806
Victor Stinner11045c92017-10-05 06:32:53 -07001807 with mock.patch("subprocess.os.waitpid",
1808 side_effect=ChildProcessError):
1809 with self.assertRaises(subprocess.SubprocessError) as e:
1810 self.PopenNoDestructor(["non_existent_command"])
Ammar Askar3fc499b2017-09-06 02:41:30 -04001811
1812 self.assertIn(repr(error_data), str(e.exception))
1813
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001814 @unittest.skipIf(not os.path.exists('/proc/self/status'),
1815 "need /proc/self/status")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001816 def test_restore_signals(self):
Gregory P. Smith5f3d04f2018-06-05 12:00:57 -07001817 # Blindly assume that cat exists on systems with /proc/self/status...
1818 default_proc_status = subprocess.check_output(
1819 ['cat', '/proc/self/status'],
1820 restore_signals=False)
1821 for line in default_proc_status.splitlines():
1822 if line.startswith(b'SigIgn'):
1823 default_sig_ign_mask = line
1824 break
1825 else:
1826 self.skipTest("SigIgn not found in /proc/self/status.")
1827 restored_proc_status = subprocess.check_output(
1828 ['cat', '/proc/self/status'],
1829 restore_signals=True)
1830 for line in restored_proc_status.splitlines():
1831 if line.startswith(b'SigIgn'):
1832 restored_sig_ign_mask = line
1833 break
1834 self.assertNotEqual(default_sig_ign_mask, restored_sig_ign_mask,
1835 msg="restore_signals=True should've unblocked "
1836 "SIGPIPE and friends.")
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001837
1838 def test_start_new_session(self):
1839 # For code coverage of calling setsid(). We don't care if we get an
1840 # EPERM error from it depending on the test execution environment, that
1841 # still indicates that it was called.
1842 try:
1843 output = subprocess.check_output(
Victor Stinner58840432019-06-14 19:31:43 +02001844 [sys.executable, "-c", "import os; print(os.getsid(0))"],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001845 start_new_session=True)
1846 except OSError as e:
1847 if e.errno != errno.EPERM:
1848 raise
1849 else:
Victor Stinner58840432019-06-14 19:31:43 +02001850 parent_sid = os.getsid(0)
1851 child_sid = int(output)
1852 self.assertNotEqual(parent_sid, child_sid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001853
Patrick McLean2b2ead72019-09-12 10:15:44 -07001854 @unittest.skipUnless(hasattr(os, 'setreuid'), 'no setreuid on platform')
1855 def test_user(self):
1856 # For code coverage of the user parameter. We don't care if we get an
1857 # EPERM error from it depending on the test execution environment, that
1858 # still indicates that it was called.
1859
1860 uid = os.geteuid()
1861 test_users = [65534 if uid != 65534 else 65533, uid]
1862 name_uid = "nobody" if sys.platform != 'darwin' else "unknown"
1863
1864 if pwd is not None:
Victor Stinnerf7b5d412020-03-05 14:28:40 +01001865 try:
1866 pwd.getpwnam(name_uid)
1867 test_users.append(name_uid)
1868 except KeyError:
1869 # unknown user name
1870 name_uid = None
Patrick McLean2b2ead72019-09-12 10:15:44 -07001871
1872 for user in test_users:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001873 # posix_spawn() may be used with close_fds=False
1874 for close_fds in (False, True):
1875 with self.subTest(user=user, close_fds=close_fds):
1876 try:
1877 output = subprocess.check_output(
1878 [sys.executable, "-c",
1879 "import os; print(os.getuid())"],
1880 user=user,
1881 close_fds=close_fds)
1882 except PermissionError: # (EACCES, EPERM)
1883 pass
1884 except OSError as e:
1885 if e.errno not in (errno.EACCES, errno.EPERM):
1886 raise
Patrick McLean2b2ead72019-09-12 10:15:44 -07001887 else:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001888 if isinstance(user, str):
1889 user_uid = pwd.getpwnam(user).pw_uid
1890 else:
1891 user_uid = user
1892 child_user = int(output)
1893 self.assertEqual(child_user, user_uid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001894
1895 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001896 subprocess.check_call(ZERO_RETURN_CMD, user=-1)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001897
Alexey Izbyshevc0590c02020-10-26 03:09:32 +03001898 with self.assertRaises(OverflowError):
1899 subprocess.check_call(ZERO_RETURN_CMD,
1900 cwd=os.curdir, env=os.environ, user=2**64)
1901
Victor Stinnerf7b5d412020-03-05 14:28:40 +01001902 if pwd is None and name_uid is not None:
Patrick McLean2b2ead72019-09-12 10:15:44 -07001903 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001904 subprocess.check_call(ZERO_RETURN_CMD, user=name_uid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001905
1906 @unittest.skipIf(hasattr(os, 'setreuid'), 'setreuid() available on platform')
1907 def test_user_error(self):
1908 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001909 subprocess.check_call(ZERO_RETURN_CMD, user=65535)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001910
1911 @unittest.skipUnless(hasattr(os, 'setregid'), 'no setregid() on platform')
1912 def test_group(self):
1913 gid = os.getegid()
1914 group_list = [65534 if gid != 65534 else 65533]
Gregory P. Smith693aa802019-09-13 14:43:35 +01001915 name_group = _get_test_grp_name()
Patrick McLean2b2ead72019-09-12 10:15:44 -07001916
1917 if grp is not None:
1918 group_list.append(name_group)
1919
1920 for group in group_list + [gid]:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001921 # posix_spawn() may be used with close_fds=False
1922 for close_fds in (False, True):
1923 with self.subTest(group=group, close_fds=close_fds):
1924 try:
1925 output = subprocess.check_output(
1926 [sys.executable, "-c",
1927 "import os; print(os.getgid())"],
1928 group=group,
1929 close_fds=close_fds)
1930 except PermissionError: # (EACCES, EPERM)
1931 pass
Patrick McLean2b2ead72019-09-12 10:15:44 -07001932 else:
Victor Stinnerfaca8552019-09-25 15:52:49 +02001933 if isinstance(group, str):
1934 group_gid = grp.getgrnam(group).gr_gid
1935 else:
1936 group_gid = group
Patrick McLean2b2ead72019-09-12 10:15:44 -07001937
Victor Stinnerfaca8552019-09-25 15:52:49 +02001938 child_group = int(output)
1939 self.assertEqual(child_group, group_gid)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001940
1941 # make sure we bomb on negative values
1942 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001943 subprocess.check_call(ZERO_RETURN_CMD, group=-1)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001944
Alexey Izbyshevc0590c02020-10-26 03:09:32 +03001945 with self.assertRaises(OverflowError):
1946 subprocess.check_call(ZERO_RETURN_CMD,
1947 cwd=os.curdir, env=os.environ, group=2**64)
1948
Patrick McLean2b2ead72019-09-12 10:15:44 -07001949 if grp is None:
1950 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001951 subprocess.check_call(ZERO_RETURN_CMD, group=name_group)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001952
1953 @unittest.skipIf(hasattr(os, 'setregid'), 'setregid() available on platform')
1954 def test_group_error(self):
1955 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001956 subprocess.check_call(ZERO_RETURN_CMD, group=65535)
Patrick McLean2b2ead72019-09-12 10:15:44 -07001957
1958 @unittest.skipUnless(hasattr(os, 'setgroups'), 'no setgroups() on platform')
1959 def test_extra_groups(self):
1960 gid = os.getegid()
1961 group_list = [65534 if gid != 65534 else 65533]
Gregory P. Smith693aa802019-09-13 14:43:35 +01001962 name_group = _get_test_grp_name()
Patrick McLean2b2ead72019-09-12 10:15:44 -07001963 perm_error = False
1964
1965 if grp is not None:
1966 group_list.append(name_group)
1967
1968 try:
1969 output = subprocess.check_output(
1970 [sys.executable, "-c",
1971 "import os, sys, json; json.dump(os.getgroups(), sys.stdout)"],
1972 extra_groups=group_list)
1973 except OSError as ex:
1974 if ex.errno != errno.EPERM:
1975 raise
1976 perm_error = True
1977
1978 else:
1979 parent_groups = os.getgroups()
1980 child_groups = json.loads(output)
1981
1982 if grp is not None:
1983 desired_gids = [grp.getgrnam(g).gr_gid if isinstance(g, str) else g
1984 for g in group_list]
1985 else:
1986 desired_gids = group_list
1987
1988 if perm_error:
1989 self.assertEqual(set(child_groups), set(parent_groups))
1990 else:
1991 self.assertEqual(set(desired_gids), set(child_groups))
1992
1993 # make sure we bomb on negative values
1994 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07001995 subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[-1])
Patrick McLean2b2ead72019-09-12 10:15:44 -07001996
Alexey Izbyshevc0590c02020-10-26 03:09:32 +03001997 with self.assertRaises(ValueError):
1998 subprocess.check_call(ZERO_RETURN_CMD,
1999 cwd=os.curdir, env=os.environ,
2000 extra_groups=[2**64])
2001
Patrick McLean2b2ead72019-09-12 10:15:44 -07002002 if grp is None:
2003 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002004 subprocess.check_call(ZERO_RETURN_CMD,
Patrick McLean2b2ead72019-09-12 10:15:44 -07002005 extra_groups=[name_group])
2006
2007 @unittest.skipIf(hasattr(os, 'setgroups'), 'setgroups() available on platform')
2008 def test_extra_groups_error(self):
2009 with self.assertRaises(ValueError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002010 subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[])
Patrick McLean2b2ead72019-09-12 10:15:44 -07002011
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07002012 @unittest.skipIf(mswindows or not hasattr(os, 'umask'),
2013 'POSIX umask() is not available.')
2014 def test_umask(self):
2015 tmpdir = None
2016 try:
2017 tmpdir = tempfile.mkdtemp()
2018 name = os.path.join(tmpdir, "beans")
2019 # We set an unusual umask in the child so as a unique mode
2020 # for us to test the child's touched file for.
2021 subprocess.check_call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002022 [sys.executable, "-c", f"open({name!r}, 'w').close()"],
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07002023 umask=0o053)
2024 # Ignore execute permissions entirely in our test,
2025 # filesystems could be mounted to ignore or force that.
2026 st_mode = os.stat(name).st_mode & 0o666
2027 expected_mode = 0o624
2028 self.assertEqual(expected_mode, st_mode,
2029 msg=f'{oct(expected_mode)} != {oct(st_mode)}')
2030 finally:
2031 if tmpdir is not None:
2032 shutil.rmtree(tmpdir)
2033
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002034 def test_run_abort(self):
2035 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02002036 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002037 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002038 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002039 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002040 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002041
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00002042 def test_CalledProcessError_str_signal(self):
2043 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
2044 error_string = str(err)
2045 # We're relying on the repr() of the signal.Signals intenum to provide
2046 # the word signal, the signal name and the numeric value.
2047 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00002048 # We're not being specific about the signal name as some signals have
2049 # multiple names and which name is revealed can vary.
2050 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00002051 self.assertIn(str(signal.SIGABRT), error_string)
2052
2053 def test_CalledProcessError_str_unknown_signal(self):
2054 err = subprocess.CalledProcessError(-9876543, "fake cmd")
2055 error_string = str(err)
2056 self.assertIn("unknown signal 9876543.", error_string)
2057
2058 def test_CalledProcessError_str_non_zero(self):
2059 err = subprocess.CalledProcessError(2, "fake cmd")
2060 error_string = str(err)
2061 self.assertIn("non-zero exit status 2.", error_string)
2062
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002063 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002064 # DISCLAIMER: Setting environment variables is *not* a good use
2065 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002066 p = subprocess.Popen([sys.executable, "-c",
2067 'import sys,os;'
2068 'sys.stdout.write(os.getenv("FRUIT"))'],
2069 stdout=subprocess.PIPE,
2070 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02002071 with p:
2072 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002073
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002074 def test_preexec_exception(self):
2075 def raise_it():
2076 raise ValueError("What if two swallows carried a coconut?")
2077 try:
2078 p = subprocess.Popen([sys.executable, "-c", ""],
2079 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002080 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002081 self.assertTrue(
2082 subprocess._posixsubprocess,
2083 "Expected a ValueError from the preexec_fn")
2084 except ValueError as e:
2085 self.assertIn("coconut", e.args[0])
2086 else:
2087 self.fail("Exception raised by preexec_fn did not make it "
2088 "to the parent process.")
2089
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002090 class _TestExecuteChildPopen(subprocess.Popen):
2091 """Used to test behavior at the end of _execute_child."""
2092 def __init__(self, testcase, *args, **kwargs):
2093 self._testcase = testcase
2094 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002095
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002096 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08002097 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002098 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002099 finally:
2100 # Open a bunch of file descriptors and verify that
2101 # none of them are the same as the ones the Popen
2102 # instance is using for stdin/stdout/stderr.
2103 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
2104 for _ in range(8)]
2105 try:
2106 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002107 self._testcase.assertNotIn(
2108 fd, (self.stdin.fileno(), self.stdout.fileno(),
2109 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08002110 msg="At least one fd was closed early.")
2111 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01002112 for fd in devzero_fds:
2113 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08002114
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002115 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
2116 def test_preexec_errpipe_does_not_double_close_pipes(self):
2117 """Issue16140: Don't double close pipes on preexec error."""
2118
2119 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08002120 raise subprocess.SubprocessError(
2121 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08002122
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08002123 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08002124 self._TestExecuteChildPopen(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002125 self, ZERO_RETURN_CMD,
Gregory P. Smith12489d92012-11-11 01:37:02 -08002126 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2127 stderr=subprocess.PIPE, preexec_fn=raise_it)
2128
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00002129 def test_preexec_gc_module_failure(self):
2130 # This tests the code that disables garbage collection if the child
2131 # process will execute any Python.
2132 def raise_runtime_error():
2133 raise RuntimeError("this shouldn't escape")
2134 enabled = gc.isenabled()
2135 orig_gc_disable = gc.disable
2136 orig_gc_isenabled = gc.isenabled
2137 try:
2138 gc.disable()
2139 self.assertFalse(gc.isenabled())
2140 subprocess.call([sys.executable, '-c', ''],
2141 preexec_fn=lambda: None)
2142 self.assertFalse(gc.isenabled(),
2143 "Popen enabled gc when it shouldn't.")
2144
2145 gc.enable()
2146 self.assertTrue(gc.isenabled())
2147 subprocess.call([sys.executable, '-c', ''],
2148 preexec_fn=lambda: None)
2149 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
2150
2151 gc.disable = raise_runtime_error
2152 self.assertRaises(RuntimeError, subprocess.Popen,
2153 [sys.executable, '-c', ''],
2154 preexec_fn=lambda: None)
2155
2156 del gc.isenabled # force an AttributeError
2157 self.assertRaises(AttributeError, subprocess.Popen,
2158 [sys.executable, '-c', ''],
2159 preexec_fn=lambda: None)
2160 finally:
2161 gc.disable = orig_gc_disable
2162 gc.isenabled = orig_gc_isenabled
2163 if not enabled:
2164 gc.disable()
2165
Martin Panterf7fdbda2015-12-05 09:51:52 +00002166 @unittest.skipIf(
2167 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00002168 def test_preexec_fork_failure(self):
2169 # The internal code did not preserve the previous exception when
2170 # re-enabling garbage collection
2171 try:
2172 from resource import getrlimit, setrlimit, RLIMIT_NPROC
2173 except ImportError as err:
2174 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
2175 limits = getrlimit(RLIMIT_NPROC)
2176 [_, hard] = limits
2177 setrlimit(RLIMIT_NPROC, (0, hard))
2178 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00002179 try:
Martin Panterafdd5132015-11-30 02:21:41 +00002180 subprocess.call([sys.executable, '-c', ''],
2181 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00002182 except BlockingIOError:
2183 # Forking should raise EAGAIN, translated to BlockingIOError
2184 pass
2185 else:
2186 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00002187
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002188 def test_args_string(self):
2189 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03002190 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002191 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002192 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002193 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002194 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2195 sys.executable)
2196 os.chmod(fname, 0o700)
2197 p = subprocess.Popen(fname)
2198 p.wait()
2199 os.remove(fname)
2200 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002201
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002202 def test_invalid_args(self):
2203 # invalid arguments should raise ValueError
2204 self.assertRaises(ValueError, subprocess.call,
2205 [sys.executable, "-c",
2206 "import sys; sys.exit(47)"],
2207 startupinfo=47)
2208 self.assertRaises(ValueError, subprocess.call,
2209 [sys.executable, "-c",
2210 "import sys; sys.exit(47)"],
2211 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002212
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002213 def test_shell_sequence(self):
2214 # Run command through the shell (sequence)
2215 newenv = os.environ.copy()
2216 newenv["FRUIT"] = "apple"
2217 p = subprocess.Popen(["echo $FRUIT"], shell=1,
2218 stdout=subprocess.PIPE,
2219 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002220 with p:
2221 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002222
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002223 def test_shell_string(self):
2224 # Run command through the shell (string)
2225 newenv = os.environ.copy()
2226 newenv["FRUIT"] = "apple"
2227 p = subprocess.Popen("echo $FRUIT", shell=1,
2228 stdout=subprocess.PIPE,
2229 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002230 with p:
2231 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00002232
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002233 def test_call_string(self):
2234 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03002235 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002236 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00002237 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02002238 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002239 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2240 sys.executable)
2241 os.chmod(fname, 0o700)
2242 rc = subprocess.call(fname)
2243 os.remove(fname)
2244 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00002245
Stefan Krah9542cc62010-07-19 14:20:53 +00002246 def test_specific_shell(self):
2247 # Issue #9265: Incorrect name passed as arg[0].
2248 shells = []
2249 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
2250 for name in ['bash', 'ksh']:
2251 sh = os.path.join(prefix, name)
2252 if os.path.isfile(sh):
2253 shells.append(sh)
2254 if not shells: # Will probably work for any shell but csh.
2255 self.skipTest("bash or ksh required for this test")
2256 sh = '/bin/sh'
2257 if os.path.isfile(sh) and not os.path.islink(sh):
2258 # Test will fail if /bin/sh is a symlink to csh.
2259 shells.append(sh)
2260 for sh in shells:
2261 p = subprocess.Popen("echo $0", executable=sh, shell=True,
2262 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002263 with p:
2264 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00002265
Florent Xicluna4886d242010-03-08 13:27:26 +00002266 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00002267 # Do not inherit file handles from the parent.
2268 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07002269 # Also set the SIGINT handler to the default to make sure it's not
2270 # being ignored (some tests rely on that.)
2271 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
2272 try:
2273 p = subprocess.Popen([sys.executable, "-c", """if 1:
2274 import sys, time
2275 sys.stdout.write('x\\n')
2276 sys.stdout.flush()
2277 time.sleep(30)
2278 """],
2279 close_fds=True,
2280 stdin=subprocess.PIPE,
2281 stdout=subprocess.PIPE,
2282 stderr=subprocess.PIPE)
2283 finally:
2284 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00002285 # Wait for the interpreter to be completely initialized before
2286 # sending any signal.
2287 p.stdout.read(1)
2288 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00002289 return p
2290
Charles-François Natali53221e32013-01-12 16:52:20 +01002291 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
2292 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002293 def _kill_dead_process(self, method, *args):
2294 # Do not inherit file handles from the parent.
2295 # It should fix failures on some platforms.
2296 p = subprocess.Popen([sys.executable, "-c", """if 1:
2297 import sys, time
2298 sys.stdout.write('x\\n')
2299 sys.stdout.flush()
2300 """],
2301 close_fds=True,
2302 stdin=subprocess.PIPE,
2303 stdout=subprocess.PIPE,
2304 stderr=subprocess.PIPE)
2305 # Wait for the interpreter to be completely initialized before
2306 # sending any signal.
2307 p.stdout.read(1)
2308 # The process should end after this
2309 time.sleep(1)
2310 # This shouldn't raise even though the child is now dead
2311 getattr(p, method)(*args)
2312 p.communicate()
2313
Florent Xicluna4886d242010-03-08 13:27:26 +00002314 def test_send_signal(self):
2315 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00002316 _, stderr = p.communicate()
2317 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002318 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00002319
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002320 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002321 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00002322 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002323 self.assertEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002324 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00002325
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002326 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002327 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00002328 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002329 self.assertEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002330 self.assertEqual(p.wait(), -signal.SIGTERM)
2331
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002332 def test_send_signal_dead(self):
2333 # Sending a signal to a dead process
2334 self._kill_dead_process('send_signal', signal.SIGINT)
2335
2336 def test_kill_dead(self):
2337 # Killing a dead process
2338 self._kill_dead_process('kill')
2339
2340 def test_terminate_dead(self):
2341 # Terminating a dead process
2342 self._kill_dead_process('terminate')
2343
Victor Stinnerdaf45552013-08-28 00:53:59 +02002344 def _save_fds(self, save_fds):
2345 fds = []
2346 for fd in save_fds:
2347 inheritable = os.get_inheritable(fd)
2348 saved = os.dup(fd)
2349 fds.append((fd, saved, inheritable))
2350 return fds
2351
2352 def _restore_fds(self, fds):
2353 for fd, saved, inheritable in fds:
2354 os.dup2(saved, fd, inheritable=inheritable)
2355 os.close(saved)
2356
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002357 def check_close_std_fds(self, fds):
2358 # Issue #9905: test that subprocess pipes still work properly with
2359 # some standard fds closed
2360 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02002361 saved_fds = self._save_fds(fds)
2362 for fd, saved, inheritable in saved_fds:
2363 if fd == 0:
2364 stdin = saved
2365 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002366 try:
2367 for fd in fds:
2368 os.close(fd)
2369 out, err = subprocess.Popen([sys.executable, "-c",
2370 'import sys;'
2371 'sys.stdout.write("apple");'
2372 'sys.stdout.flush();'
2373 'sys.stderr.write("orange")'],
2374 stdin=stdin,
2375 stdout=subprocess.PIPE,
2376 stderr=subprocess.PIPE).communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01002377 self.assertEqual(out, b'apple')
2378 self.assertEqual(err, b'orange')
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002379 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002380 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00002381
2382 def test_close_fd_0(self):
2383 self.check_close_std_fds([0])
2384
2385 def test_close_fd_1(self):
2386 self.check_close_std_fds([1])
2387
2388 def test_close_fd_2(self):
2389 self.check_close_std_fds([2])
2390
2391 def test_close_fds_0_1(self):
2392 self.check_close_std_fds([0, 1])
2393
2394 def test_close_fds_0_2(self):
2395 self.check_close_std_fds([0, 2])
2396
2397 def test_close_fds_1_2(self):
2398 self.check_close_std_fds([1, 2])
2399
2400 def test_close_fds_0_1_2(self):
2401 # Issue #10806: test that subprocess pipes still work properly with
2402 # all standard fds closed.
2403 self.check_close_std_fds([0, 1, 2])
2404
Gregory P. Smith53dd8162013-12-01 16:03:24 -08002405 def test_small_errpipe_write_fd(self):
2406 """Issue #15798: Popen should work when stdio fds are available."""
2407 new_stdin = os.dup(0)
2408 new_stdout = os.dup(1)
2409 try:
2410 os.close(0)
2411 os.close(1)
2412
2413 # Side test: if errpipe_write fails to have its CLOEXEC
2414 # flag set this should cause the parent to think the exec
2415 # failed. Extremely unlikely: everyone supports CLOEXEC.
2416 subprocess.Popen([
2417 sys.executable, "-c",
2418 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
2419 finally:
2420 # Restore original stdin and stdout
2421 os.dup2(new_stdin, 0)
2422 os.dup2(new_stdout, 1)
2423 os.close(new_stdin)
2424 os.close(new_stdout)
2425
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002426 def test_remapping_std_fds(self):
2427 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002428 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002429 try:
2430 temp_fds = [fd for fd, fname in temps]
2431
2432 # unlink the files -- we won't need to reopen them
2433 for fd, fname in temps:
2434 os.unlink(fname)
2435
2436 # write some data to what will become stdin, and rewind
2437 os.write(temp_fds[1], b"STDIN")
2438 os.lseek(temp_fds[1], 0, 0)
2439
2440 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02002441 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002442 try:
2443 # duplicate the file objects over the standard fd's
2444 for fd, temp_fd in enumerate(temp_fds):
2445 os.dup2(temp_fd, fd)
2446
2447 # now use those files in the "wrong" order, so that subprocess
2448 # has to rearrange them in the child
2449 p = subprocess.Popen([sys.executable, "-c",
2450 'import sys; got = sys.stdin.read();'
2451 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2452 stdin=temp_fds[1],
2453 stdout=temp_fds[2],
2454 stderr=temp_fds[0])
2455 p.wait()
2456 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002457 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002458
2459 for fd in temp_fds:
2460 os.lseek(fd, 0, 0)
2461
2462 out = os.read(temp_fds[2], 1024)
Victor Stinner6cac1132019-12-08 08:38:16 +01002463 err = os.read(temp_fds[0], 1024).strip()
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00002464 self.assertEqual(out, b"got STDIN")
2465 self.assertEqual(err, b"err")
2466
2467 finally:
2468 for fd in temp_fds:
2469 os.close(fd)
2470
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002471 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
2472 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03002473 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002474 temp_fds = [fd for fd, fname in temps]
2475 try:
2476 # unlink the files -- we won't need to reopen them
2477 for fd, fname in temps:
2478 os.unlink(fname)
2479
2480 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02002481 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002482 try:
2483 # duplicate the temp files over the standard fd's 0, 1, 2
2484 for fd, temp_fd in enumerate(temp_fds):
2485 os.dup2(temp_fd, fd)
2486
2487 # write some data to what will become stdin, and rewind
2488 os.write(stdin_no, b"STDIN")
2489 os.lseek(stdin_no, 0, 0)
2490
2491 # now use those files in the given order, so that subprocess
2492 # has to rearrange them in the child
2493 p = subprocess.Popen([sys.executable, "-c",
2494 'import sys; got = sys.stdin.read();'
2495 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2496 stdin=stdin_no,
2497 stdout=stdout_no,
2498 stderr=stderr_no)
2499 p.wait()
2500
2501 for fd in temp_fds:
2502 os.lseek(fd, 0, 0)
2503
2504 out = os.read(stdout_no, 1024)
Victor Stinner6cac1132019-12-08 08:38:16 +01002505 err = os.read(stderr_no, 1024).strip()
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002506 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02002507 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02002508
2509 self.assertEqual(out, b"got STDIN")
2510 self.assertEqual(err, b"err")
2511
2512 finally:
2513 for fd in temp_fds:
2514 os.close(fd)
2515
2516 # When duping fds, if there arises a situation where one of the fds is
2517 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
2518 # This tests all combinations of this.
2519 def test_swap_fds(self):
2520 self.check_swap_fds(0, 1, 2)
2521 self.check_swap_fds(0, 2, 1)
2522 self.check_swap_fds(1, 0, 2)
2523 self.check_swap_fds(1, 2, 0)
2524 self.check_swap_fds(2, 0, 1)
2525 self.check_swap_fds(2, 1, 0)
2526
Alexey Izbyshev0e7144b2018-03-26 22:49:35 +03002527 def _check_swap_std_fds_with_one_closed(self, from_fds, to_fds):
2528 saved_fds = self._save_fds(range(3))
2529 try:
2530 for from_fd in from_fds:
2531 with tempfile.TemporaryFile() as f:
2532 os.dup2(f.fileno(), from_fd)
2533
2534 fd_to_close = (set(range(3)) - set(from_fds)).pop()
2535 os.close(fd_to_close)
2536
2537 arg_names = ['stdin', 'stdout', 'stderr']
2538 kwargs = {}
2539 for from_fd, to_fd in zip(from_fds, to_fds):
2540 kwargs[arg_names[to_fd]] = from_fd
2541
2542 code = textwrap.dedent(r'''
2543 import os, sys
2544 skipped_fd = int(sys.argv[1])
2545 for fd in range(3):
2546 if fd != skipped_fd:
2547 os.write(fd, str(fd).encode('ascii'))
2548 ''')
2549
2550 skipped_fd = (set(range(3)) - set(to_fds)).pop()
2551
2552 rc = subprocess.call([sys.executable, '-c', code, str(skipped_fd)],
2553 **kwargs)
2554 self.assertEqual(rc, 0)
2555
2556 for from_fd, to_fd in zip(from_fds, to_fds):
2557 os.lseek(from_fd, 0, os.SEEK_SET)
2558 read_bytes = os.read(from_fd, 1024)
2559 read_fds = list(map(int, read_bytes.decode('ascii')))
2560 msg = textwrap.dedent(f"""
2561 When testing {from_fds} to {to_fds} redirection,
2562 parent descriptor {from_fd} got redirected
2563 to descriptor(s) {read_fds} instead of descriptor {to_fd}.
2564 """)
2565 self.assertEqual([to_fd], read_fds, msg)
2566 finally:
2567 self._restore_fds(saved_fds)
2568
2569 # Check that subprocess can remap std fds correctly even
2570 # if one of them is closed (#32844).
2571 def test_swap_std_fds_with_one_closed(self):
2572 for from_fds in itertools.combinations(range(3), 2):
2573 for to_fds in itertools.permutations(range(3), 2):
2574 self._check_swap_std_fds_with_one_closed(from_fds, to_fds)
2575
Victor Stinner13bb71c2010-04-23 21:41:56 +00002576 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00002577 def prepare():
2578 raise ValueError("surrogate:\uDCff")
2579
2580 try:
2581 subprocess.call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002582 ZERO_RETURN_CMD,
Victor Stinner4d078042010-04-23 19:28:32 +00002583 preexec_fn=prepare)
2584 except ValueError as err:
2585 # Pure Python implementations keeps the message
2586 self.assertIsNone(subprocess._posixsubprocess)
2587 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002588 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00002589 # _posixsubprocess uses a default message
2590 self.assertIsNotNone(subprocess._posixsubprocess)
2591 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
2592 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08002593 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00002594
Victor Stinner13bb71c2010-04-23 21:41:56 +00002595 def test_undecodable_env(self):
2596 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01002597 encoded_value = value.encode("ascii", "surrogateescape")
2598
Victor Stinner13bb71c2010-04-23 21:41:56 +00002599 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002600 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002601 env = os.environ.copy()
2602 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01002603 # Use C locale to get ASCII for the locale encoding to force
Michael Felt89d79b12018-08-26 19:29:36 +02002604 # surrogate-escaping of \xFF in the child process
Victor Stinnerebc78d22010-10-14 10:38:17 +00002605 env['LC_ALL'] = 'C'
Michael Felt89d79b12018-08-26 19:29:36 +02002606 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002607 stdout = subprocess.check_output(
2608 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002609 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002610 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002611 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002612
2613 # test bytes
2614 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002615 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002616 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01002617 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002618 stdout = subprocess.check_output(
2619 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002620 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002621 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002622 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002623
Victor Stinnerb745a742010-05-18 17:17:23 +00002624 def test_bytes_program(self):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002625 abs_program = os.fsencode(ZERO_RETURN_CMD[0])
2626 args = list(ZERO_RETURN_CMD[1:])
2627 path, program = os.path.split(ZERO_RETURN_CMD[0])
Victor Stinnerb745a742010-05-18 17:17:23 +00002628 program = os.fsencode(program)
2629
2630 # absolute bytes path
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002631 exitcode = subprocess.call([abs_program]+args)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002632 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002633
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002634 # absolute bytes path as a string
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002635 cmd = b"'%s' %s" % (abs_program, " ".join(args).encode("utf-8"))
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002636 exitcode = subprocess.call(cmd, shell=True)
2637 self.assertEqual(exitcode, 0)
2638
Victor Stinnerb745a742010-05-18 17:17:23 +00002639 # bytes program, unicode PATH
2640 env = os.environ.copy()
2641 env["PATH"] = path
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002642 exitcode = subprocess.call([program]+args, env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002643 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002644
2645 # bytes program, bytes PATH
2646 envb = os.environb.copy()
2647 envb[b"PATH"] = os.fsencode(path)
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002648 exitcode = subprocess.call([program]+args, env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002649 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002650
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002651 def test_pipe_cloexec(self):
2652 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2653 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2654
2655 p1 = subprocess.Popen([sys.executable, sleeper],
2656 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2657 stderr=subprocess.PIPE, close_fds=False)
2658
2659 self.addCleanup(p1.communicate, b'')
2660
2661 p2 = subprocess.Popen([sys.executable, fd_status],
2662 stdout=subprocess.PIPE, close_fds=False)
2663
2664 output, error = p2.communicate()
2665 result_fds = set(map(int, output.split(b',')))
2666 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2667 p1.stderr.fileno()])
2668
2669 self.assertFalse(result_fds & unwanted_fds,
2670 "Expected no fds from %r to be open in child, "
2671 "found %r" %
2672 (unwanted_fds, result_fds & unwanted_fds))
2673
2674 def test_pipe_cloexec_real_tools(self):
2675 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2676 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2677
2678 subdata = b'zxcvbn'
2679 data = subdata * 4 + b'\n'
2680
2681 p1 = subprocess.Popen([sys.executable, qcat],
2682 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2683 close_fds=False)
2684
2685 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2686 stdin=p1.stdout, stdout=subprocess.PIPE,
2687 close_fds=False)
2688
2689 self.addCleanup(p1.wait)
2690 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002691 def kill_p1():
2692 try:
2693 p1.terminate()
2694 except ProcessLookupError:
2695 pass
2696 def kill_p2():
2697 try:
2698 p2.terminate()
2699 except ProcessLookupError:
2700 pass
2701 self.addCleanup(kill_p1)
2702 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002703
2704 p1.stdin.write(data)
2705 p1.stdin.close()
2706
2707 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2708
2709 self.assertTrue(readfiles, "The child hung")
2710 self.assertEqual(p2.stdout.read(), data)
2711
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002712 p1.stdout.close()
2713 p2.stdout.close()
2714
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002715 def test_close_fds(self):
2716 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2717
2718 fds = os.pipe()
2719 self.addCleanup(os.close, fds[0])
2720 self.addCleanup(os.close, fds[1])
2721
2722 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002723 # add a bunch more fds
2724 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002725 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002726 self.addCleanup(os.close, fd)
2727 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002728
Victor Stinnerdaf45552013-08-28 00:53:59 +02002729 for fd in open_fds:
2730 os.set_inheritable(fd, True)
2731
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002732 p = subprocess.Popen([sys.executable, fd_status],
2733 stdout=subprocess.PIPE, close_fds=False)
2734 output, ignored = p.communicate()
2735 remaining_fds = set(map(int, output.split(b',')))
2736
2737 self.assertEqual(remaining_fds & open_fds, open_fds,
2738 "Some fds were closed")
2739
2740 p = subprocess.Popen([sys.executable, fd_status],
2741 stdout=subprocess.PIPE, close_fds=True)
2742 output, ignored = p.communicate()
2743 remaining_fds = set(map(int, output.split(b',')))
2744
2745 self.assertFalse(remaining_fds & open_fds,
2746 "Some fds were left open")
2747 self.assertIn(1, remaining_fds, "Subprocess failed")
2748
Gregory P. Smith8facece2012-01-21 14:01:08 -08002749 # Keep some of the fd's we opened open in the subprocess.
2750 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2751 fds_to_keep = set(open_fds.pop() for _ in range(8))
2752 p = subprocess.Popen([sys.executable, fd_status],
2753 stdout=subprocess.PIPE, close_fds=True,
izbyshev2d8f0632017-12-19 03:26:49 +07002754 pass_fds=fds_to_keep)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002755 output, ignored = p.communicate()
2756 remaining_fds = set(map(int, output.split(b',')))
2757
izbyshev2d8f0632017-12-19 03:26:49 +07002758 self.assertFalse((remaining_fds - fds_to_keep) & open_fds,
Gregory P. Smith8facece2012-01-21 14:01:08 -08002759 "Some fds not in pass_fds were left open")
2760 self.assertIn(1, remaining_fds, "Subprocess failed")
2761
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002762
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002763 @unittest.skipIf(sys.platform.startswith("freebsd") and
2764 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2765 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002766 def test_close_fds_when_max_fd_is_lowered(self):
2767 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2768 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2769
Gregory P. Smith634aa682014-06-15 17:51:04 -07002770 # This launches the meat of the test in a child process to
2771 # avoid messing with the larger unittest processes maximum
2772 # number of file descriptors.
2773 # This process launches:
2774 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2775 # a bunch of high open fds above the new lower rlimit.
2776 # Those are reported via stdout before launching a new
2777 # process with close_fds=False to run the actual test:
2778 # +--> The TEST: This one launches a fd_status.py
2779 # subprocess with close_fds=True so we can find out if
2780 # any of the fds above the lowered rlimit are still open.
2781 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2782 '''
2783 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002784 open_fds = set()
2785 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002786 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002787 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002788 open_fds.add(fd)
2789
2790 # Leave a two pairs of low ones available for use by the
2791 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002792 # We also leave 10 more open as some Python buildbots run into
2793 # "too many open files" errors during the test if we do not.
2794 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002795 os.close(fd)
2796 open_fds.remove(fd)
2797
2798 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002799 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002800 os.set_inheritable(fd, True)
2801
2802 max_fd_open = max(open_fds)
2803
Gregory P. Smith634aa682014-06-15 17:51:04 -07002804 # Communicate the open_fds to the parent unittest.TestCase process.
2805 print(','.join(map(str, sorted(open_fds))))
2806 sys.stdout.flush()
2807
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002808 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2809 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002810 # 29 is lower than the highest fds we are leaving open.
2811 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002812 # Launch a new Python interpreter with our low fd rlim_cur that
2813 # inherits open fds above that limit. It then uses subprocess
2814 # with close_fds=True to get a report of open fds in the child.
2815 # An explicit list of fds to check is passed to fd_status.py as
2816 # letting fd_status rely on its default logic would miss the
2817 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002818 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002819 [sys.executable, '-c',
2820 textwrap.dedent("""
2821 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002822 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002823 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002824 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002825 """.format(max_fd=max_fd_open+1))],
2826 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002827 finally:
2828 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002829 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002830
2831 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002832 output_lines = output.splitlines()
2833 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002834 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002835 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2836 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002837
Gregory P. Smith634aa682014-06-15 17:51:04 -07002838 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002839 msg="Some fds were left open.")
2840
2841
Victor Stinner88701e22011-06-01 13:13:04 +02002842 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2843 # descriptor of a pipe closed in the parent process is valid in the
2844 # child process according to fstat(), but the mode of the file
2845 # descriptor is invalid, and read or write raise an error.
2846 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002847 def test_pass_fds(self):
2848 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2849
2850 open_fds = set()
2851
2852 for x in range(5):
2853 fds = os.pipe()
2854 self.addCleanup(os.close, fds[0])
2855 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002856 os.set_inheritable(fds[0], True)
2857 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002858 open_fds.update(fds)
2859
2860 for fd in open_fds:
2861 p = subprocess.Popen([sys.executable, fd_status],
2862 stdout=subprocess.PIPE, close_fds=True,
2863 pass_fds=(fd, ))
2864 output, ignored = p.communicate()
2865
2866 remaining_fds = set(map(int, output.split(b',')))
2867 to_be_closed = open_fds - {fd}
2868
2869 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2870 self.assertFalse(remaining_fds & to_be_closed,
2871 "fd to be closed passed")
2872
2873 # pass_fds overrides close_fds with a warning.
2874 with self.assertWarns(RuntimeWarning) as context:
2875 self.assertFalse(subprocess.call(
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002876 ZERO_RETURN_CMD,
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002877 close_fds=False, pass_fds=(fd, )))
2878 self.assertIn('overriding close_fds', str(context.warning))
2879
Victor Stinnerdaf45552013-08-28 00:53:59 +02002880 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002881 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002882
2883 inheritable, non_inheritable = os.pipe()
2884 self.addCleanup(os.close, inheritable)
2885 self.addCleanup(os.close, non_inheritable)
2886 os.set_inheritable(inheritable, True)
2887 os.set_inheritable(non_inheritable, False)
2888 pass_fds = (inheritable, non_inheritable)
2889 args = [sys.executable, script]
2890 args += list(map(str, pass_fds))
2891
2892 p = subprocess.Popen(args,
2893 stdout=subprocess.PIPE, close_fds=True,
2894 pass_fds=pass_fds)
2895 output, ignored = p.communicate()
2896 fds = set(map(int, output.split(b',')))
2897
2898 # the inheritable file descriptor must be inherited, so its inheritable
2899 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002900 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002901
2902 # inheritable flag must not be changed in the parent process
2903 self.assertEqual(os.get_inheritable(inheritable), True)
2904 self.assertEqual(os.get_inheritable(non_inheritable), False)
2905
Gregory P. Smithce344102018-09-10 17:46:22 -07002906
2907 # bpo-32270: Ensure that descriptors specified in pass_fds
2908 # are inherited even if they are used in redirections.
2909 # Contributed by @izbyshev.
2910 def test_pass_fds_redirected(self):
2911 """Regression test for https://bugs.python.org/issue32270."""
2912 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2913 pass_fds = []
2914 for _ in range(2):
2915 fd = os.open(os.devnull, os.O_RDWR)
2916 self.addCleanup(os.close, fd)
2917 pass_fds.append(fd)
2918
2919 stdout_r, stdout_w = os.pipe()
2920 self.addCleanup(os.close, stdout_r)
2921 self.addCleanup(os.close, stdout_w)
2922 pass_fds.insert(1, stdout_w)
2923
2924 with subprocess.Popen([sys.executable, fd_status],
2925 stdin=pass_fds[0],
2926 stdout=pass_fds[1],
2927 stderr=pass_fds[2],
2928 close_fds=True,
2929 pass_fds=pass_fds):
2930 output = os.read(stdout_r, 1024)
2931 fds = {int(num) for num in output.split(b',')}
2932
2933 self.assertEqual(fds, {0, 1, 2} | frozenset(pass_fds), f"output={output!a}")
2934
2935
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002936 def test_stdout_stdin_are_single_inout_fd(self):
2937 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002938 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002939 stdout=inout, stdin=inout)
2940 p.wait()
2941
2942 def test_stdout_stderr_are_single_inout_fd(self):
2943 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002944 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002945 stdout=inout, stderr=inout)
2946 p.wait()
2947
2948 def test_stderr_stdin_are_single_inout_fd(self):
2949 with io.open(os.devnull, "r+") as inout:
Gregory P. Smith67b93f82019-10-12 16:35:53 -07002950 p = subprocess.Popen(ZERO_RETURN_CMD,
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002951 stderr=inout, stdin=inout)
2952 p.wait()
2953
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002954 def test_wait_when_sigchild_ignored(self):
2955 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2956 sigchild_ignore = support.findfile("sigchild_ignore.py",
2957 subdir="subprocessdata")
2958 p = subprocess.Popen([sys.executable, sigchild_ignore],
2959 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2960 stdout, stderr = p.communicate()
2961 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002962 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002963 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002964
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002965 def test_select_unbuffered(self):
2966 # Issue #11459: bufsize=0 should really set the pipes as
2967 # unbuffered (and therefore let select() work properly).
Hai Shi0c4f0f32020-06-30 21:46:31 +08002968 select = import_helper.import_module("select")
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002969 p = subprocess.Popen([sys.executable, "-c",
2970 'import sys;'
2971 'sys.stdout.write("apple")'],
2972 stdout=subprocess.PIPE,
2973 bufsize=0)
2974 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002975 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002976 try:
2977 self.assertEqual(f.read(4), b"appl")
2978 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2979 finally:
2980 p.wait()
2981
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002982 def test_zombie_fast_process_del(self):
2983 # Issue #12650: on Unix, if Popen.__del__() was called before the
2984 # process exited, it wouldn't be added to subprocess._active, and would
2985 # remain a zombie.
2986 # spawn a Popen, and delete its reference before it exits
2987 p = subprocess.Popen([sys.executable, "-c",
2988 'import sys, time;'
2989 'time.sleep(0.2)'],
2990 stdout=subprocess.PIPE,
2991 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002992 self.addCleanup(p.stdout.close)
2993 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002994 ident = id(p)
2995 pid = p.pid
Hai Shi0c4f0f32020-06-30 21:46:31 +08002996 with warnings_helper.check_warnings(('', ResourceWarning)):
Victor Stinner5a48e212016-05-20 12:11:15 +02002997 p = None
2998
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03002999 if mswindows:
3000 # subprocess._active is not used on Windows and is set to None.
3001 self.assertIsNone(subprocess._active)
3002 else:
3003 # check that p is in the active processes list
3004 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003005
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003006 def test_leak_fast_process_del_killed(self):
3007 # Issue #12650: on Unix, if Popen.__del__() was called before the
3008 # process exited, and the process got killed by a signal, it would never
3009 # be removed from subprocess._active, which triggered a FD and memory
3010 # leak.
3011 # spawn a Popen, delete its reference and kill it
3012 p = subprocess.Popen([sys.executable, "-c",
3013 'import time;'
3014 'time.sleep(3)'],
3015 stdout=subprocess.PIPE,
3016 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02003017 self.addCleanup(p.stdout.close)
3018 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003019 ident = id(p)
3020 pid = p.pid
Hai Shi0c4f0f32020-06-30 21:46:31 +08003021 with warnings_helper.check_warnings(('', ResourceWarning)):
Victor Stinner5a48e212016-05-20 12:11:15 +02003022 p = None
3023
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003024 os.kill(pid, signal.SIGKILL)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03003025 if mswindows:
3026 # subprocess._active is not used on Windows and is set to None.
3027 self.assertIsNone(subprocess._active)
3028 else:
3029 # check that p is in the active processes list
3030 self.assertIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003031
3032 # let some time for the process to exit, and create a new Popen: this
3033 # should trigger the wait() of p
3034 time.sleep(0.2)
Victor Stinnerb31206a2018-01-25 19:06:05 +01003035 with self.assertRaises(OSError):
Victor Stinner9a83f652017-08-21 23:51:31 +02003036 with subprocess.Popen(NONEXISTING_CMD,
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003037 stdout=subprocess.PIPE,
3038 stderr=subprocess.PIPE) as proc:
3039 pass
3040 # p should have been wait()ed on, and removed from the _active list
3041 self.assertRaises(OSError, os.waitpid, pid, 0)
Ruslan Kuprieiev042821a2019-06-28 19:12:16 +03003042 if mswindows:
3043 # subprocess._active is not used on Windows and is set to None.
3044 self.assertIsNone(subprocess._active)
3045 else:
3046 self.assertNotIn(ident, [id(o) for o in subprocess._active])
Charles-François Natali134a8ba2011-08-18 18:49:39 +02003047
Charles-François Natali249cdc32013-08-25 18:24:45 +02003048 def test_close_fds_after_preexec(self):
3049 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
3050
3051 # this FD is used as dup2() target by preexec_fn, and should be closed
3052 # in the child process
3053 fd = os.dup(1)
3054 self.addCleanup(os.close, fd)
3055
3056 p = subprocess.Popen([sys.executable, fd_status],
3057 stdout=subprocess.PIPE, close_fds=True,
3058 preexec_fn=lambda: os.dup2(1, fd))
3059 output, ignored = p.communicate()
3060
3061 remaining_fds = set(map(int, output.split(b',')))
3062
3063 self.assertNotIn(fd, remaining_fds)
3064
Victor Stinner8f437aa2014-10-05 17:25:19 +02003065 @support.cpython_only
3066 def test_fork_exec(self):
3067 # Issue #22290: fork_exec() must not crash on memory allocation failure
3068 # or other errors
3069 import _posixsubprocess
3070 gc_enabled = gc.isenabled()
3071 try:
3072 # Use a preexec function and enable the garbage collector
3073 # to force fork_exec() to re-enable the garbage collector
3074 # on error.
3075 func = lambda: None
3076 gc.enable()
3077
Victor Stinner8f437aa2014-10-05 17:25:19 +02003078 for args, exe_list, cwd, env_list in (
3079 (123, [b"exe"], None, [b"env"]),
3080 ([b"arg"], 123, None, [b"env"]),
3081 ([b"arg"], [b"exe"], 123, [b"env"]),
3082 ([b"arg"], [b"exe"], None, 123),
3083 ):
Patrick McLean2b2ead72019-09-12 10:15:44 -07003084 with self.assertRaises(TypeError) as err:
Victor Stinner8f437aa2014-10-05 17:25:19 +02003085 _posixsubprocess.fork_exec(
3086 args, exe_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003087 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02003088 -1, -1, -1, -1,
3089 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003090 True, True,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07003091 False, [], 0, -1,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003092 func)
3093 # Attempt to prevent
3094 # "TypeError: fork_exec() takes exactly N arguments (M given)"
3095 # from passing the test. More refactoring to have us start
3096 # with a valid *args list, confirm a good call with that works
3097 # before mutating it in various ways to ensure that bad calls
3098 # with individual arg type errors raise a typeerror would be
3099 # ideal. Saving that for a future PR...
3100 self.assertNotIn('takes exactly', str(err.exception))
Victor Stinner8f437aa2014-10-05 17:25:19 +02003101 finally:
3102 if not gc_enabled:
3103 gc.disable()
3104
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003105 @support.cpython_only
3106 def test_fork_exec_sorted_fd_sanity_check(self):
3107 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
3108 import _posixsubprocess
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003109 class BadInt:
3110 first = True
3111 def __init__(self, value):
3112 self.value = value
3113 def __int__(self):
3114 if self.first:
3115 self.first = False
3116 return self.value
3117 raise ValueError
3118
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003119 gc_enabled = gc.isenabled()
3120 try:
3121 gc.enable()
3122
3123 for fds_to_keep in (
3124 (-1, 2, 3, 4, 5), # Negative number.
3125 ('str', 4), # Not an int.
3126 (18, 23, 42, 2**63), # Out of range.
3127 (5, 4), # Not sorted.
3128 (6, 7, 7, 8), # Duplicate.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03003129 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003130 ):
3131 with self.assertRaises(
3132 ValueError,
3133 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
3134 _posixsubprocess.fork_exec(
3135 [b"false"], [b"false"],
3136 True, fds_to_keep, None, [b"env"],
3137 -1, -1, -1, -1,
3138 1, 2, 3, 4,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003139 True, True,
Gregory P. Smithf3751ef2019-10-12 13:24:56 -07003140 None, None, None, -1,
Patrick McLean2b2ead72019-09-12 10:15:44 -07003141 None)
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08003142 self.assertIn('fds_to_keep', str(c.exception))
3143 finally:
3144 if not gc_enabled:
3145 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02003146
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003147 def test_communicate_BrokenPipeError_stdin_close(self):
3148 # By not setting stdout or stderr or a timeout we force the fast path
3149 # that just calls _stdin_write() internally due to our mock.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003150 proc = subprocess.Popen(ZERO_RETURN_CMD)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003151 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3152 mock_proc_stdin.close.side_effect = BrokenPipeError
3153 proc.communicate() # Should swallow BrokenPipeError from close.
3154 mock_proc_stdin.close.assert_called_with()
3155
3156 def test_communicate_BrokenPipeError_stdin_write(self):
3157 # By not setting stdout or stderr or a timeout we force the fast path
3158 # that just calls _stdin_write() internally due to our mock.
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003159 proc = subprocess.Popen(ZERO_RETURN_CMD)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00003160 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3161 mock_proc_stdin.write.side_effect = BrokenPipeError
3162 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
3163 mock_proc_stdin.write.assert_called_once_with(b'stuff')
3164 mock_proc_stdin.close.assert_called_once_with()
3165
3166 def test_communicate_BrokenPipeError_stdin_flush(self):
3167 # Setting stdin and stdout forces the ._communicate() code path.
3168 # python -h exits faster than python -c pass (but spams stdout).
3169 proc = subprocess.Popen([sys.executable, '-h'],
3170 stdin=subprocess.PIPE,
3171 stdout=subprocess.PIPE)
3172 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
3173 open(os.devnull, 'wb') as dev_null:
3174 mock_proc_stdin.flush.side_effect = BrokenPipeError
3175 # because _communicate registers a selector using proc.stdin...
3176 mock_proc_stdin.fileno.return_value = dev_null.fileno()
3177 # _communicate() should swallow BrokenPipeError from flush.
3178 proc.communicate(b'stuff')
3179 mock_proc_stdin.flush.assert_called_once_with()
3180
3181 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
3182 # Setting stdin and stdout forces the ._communicate() code path.
3183 # python -h exits faster than python -c pass (but spams stdout).
3184 proc = subprocess.Popen([sys.executable, '-h'],
3185 stdin=subprocess.PIPE,
3186 stdout=subprocess.PIPE)
3187 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3188 mock_proc_stdin.close.side_effect = BrokenPipeError
3189 # _communicate() should swallow BrokenPipeError from close.
3190 proc.communicate(timeout=999)
3191 mock_proc_stdin.close.assert_called_once_with()
3192
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003193 @unittest.skipUnless(_testcapi is not None
3194 and hasattr(_testcapi, 'W_STOPCODE'),
3195 'need _testcapi.W_STOPCODE')
3196 def test_stopped(self):
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003197 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003198 args = ZERO_RETURN_CMD
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003199 proc = subprocess.Popen(args)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003200
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003201 # Wait until the real process completes to avoid zombie process
Victor Stinner278c1e12020-03-31 20:08:12 +02003202 support.wait_process(proc.pid, exitcode=0)
Victor Stinnercdee3f12017-06-26 17:23:03 +02003203
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003204 status = _testcapi.W_STOPCODE(3)
Victor Stinner278c1e12020-03-31 20:08:12 +02003205 with mock.patch('subprocess.os.waitpid', return_value=(proc.pid, status)):
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003206 returncode = proc.wait()
Victor Stinnercdee3f12017-06-26 17:23:03 +02003207
Victor Stinner7b7c6dc2017-08-10 12:37:39 +02003208 self.assertEqual(returncode, -3)
Gregory P. Smith50e16e32017-01-22 17:28:38 -08003209
Victor Stinnere85a3052020-01-15 17:38:55 +01003210 def test_send_signal_race(self):
3211 # bpo-38630: send_signal() must poll the process exit status to reduce
3212 # the risk of sending the signal to the wrong process.
3213 proc = subprocess.Popen(ZERO_RETURN_CMD)
3214
3215 # wait until the process completes without using the Popen APIs.
Victor Stinner278c1e12020-03-31 20:08:12 +02003216 support.wait_process(proc.pid, exitcode=0)
Victor Stinnere85a3052020-01-15 17:38:55 +01003217
3218 # returncode is still None but the process completed.
3219 self.assertIsNone(proc.returncode)
3220
3221 with mock.patch("os.kill") as mock_kill:
3222 proc.send_signal(signal.SIGTERM)
3223
3224 # send_signal() didn't call os.kill() since the process already
3225 # completed.
3226 mock_kill.assert_not_called()
3227
3228 # Don't check the returncode value: the test reads the exit status,
3229 # so Popen failed to read it and uses a default returncode instead.
3230 self.assertIsNotNone(proc.returncode)
3231
Filipe Laíns01a202a2020-11-21 09:22:08 +00003232 def test_send_signal_race2(self):
3233 # bpo-40550: the process might exist between the returncode check and
3234 # the kill operation
3235 p = subprocess.Popen([sys.executable, '-c', 'exit(1)'])
3236
3237 # wait for process to exit
3238 while not p.returncode:
3239 p.poll()
3240
3241 with mock.patch.object(p, 'poll', new=lambda: None):
3242 p.returncode = None
3243 p.send_signal(signal.SIGTERM)
3244
Alex Rebertd3ae95e2020-01-22 18:28:31 -05003245 def test_communicate_repeated_call_after_stdout_close(self):
3246 proc = subprocess.Popen([sys.executable, '-c',
3247 'import os, time; os.close(1), time.sleep(2)'],
3248 stdout=subprocess.PIPE)
3249 while True:
3250 try:
3251 proc.communicate(timeout=0.1)
3252 return
3253 except subprocess.TimeoutExpired:
3254 pass
3255
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003256
Victor Stinner937ee9e2018-06-26 02:11:06 +02003257@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00003258class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00003259
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003260 def test_startupinfo(self):
3261 # startupinfo argument
3262 # We uses hardcoded constants, because we do not want to
3263 # depend on win32all.
3264 STARTF_USESHOWWINDOW = 1
3265 SW_MAXIMIZE = 3
3266 startupinfo = subprocess.STARTUPINFO()
3267 startupinfo.dwFlags = STARTF_USESHOWWINDOW
3268 startupinfo.wShowWindow = SW_MAXIMIZE
3269 # Since Python is a console process, it won't be affected
3270 # by wShowWindow, but the argument should be silently
3271 # ignored
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003272 subprocess.call(ZERO_RETURN_CMD,
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003273 startupinfo=startupinfo)
3274
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05303275 def test_startupinfo_keywords(self):
3276 # startupinfo argument
3277 # We use hardcoded constants, because we do not want to
3278 # depend on win32all.
3279 STARTF_USERSHOWWINDOW = 1
3280 SW_MAXIMIZE = 3
3281 startupinfo = subprocess.STARTUPINFO(
3282 dwFlags=STARTF_USERSHOWWINDOW,
3283 wShowWindow=SW_MAXIMIZE
3284 )
3285 # Since Python is a console process, it won't be affected
3286 # by wShowWindow, but the argument should be silently
3287 # ignored
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003288 subprocess.call(ZERO_RETURN_CMD,
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05303289 startupinfo=startupinfo)
3290
Victor Stinner483422f2018-07-05 22:54:17 +02003291 def test_startupinfo_copy(self):
3292 # bpo-34044: Popen must not modify input STARTUPINFO structure
3293 startupinfo = subprocess.STARTUPINFO()
3294 startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
3295 startupinfo.wShowWindow = subprocess.SW_HIDE
3296
3297 # Call Popen() twice with the same startupinfo object to make sure
3298 # that it's not modified
3299 for _ in range(2):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003300 cmd = ZERO_RETURN_CMD
Victor Stinner483422f2018-07-05 22:54:17 +02003301 with open(os.devnull, 'w') as null:
3302 proc = subprocess.Popen(cmd,
3303 stdout=null,
3304 stderr=subprocess.STDOUT,
3305 startupinfo=startupinfo)
3306 with proc:
3307 proc.communicate()
3308 self.assertEqual(proc.returncode, 0)
3309
3310 self.assertEqual(startupinfo.dwFlags,
3311 subprocess.STARTF_USESHOWWINDOW)
3312 self.assertIsNone(startupinfo.hStdInput)
3313 self.assertIsNone(startupinfo.hStdOutput)
3314 self.assertIsNone(startupinfo.hStdError)
3315 self.assertEqual(startupinfo.wShowWindow, subprocess.SW_HIDE)
3316 self.assertEqual(startupinfo.lpAttributeList, {"handle_list": []})
3317
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003318 def test_creationflags(self):
3319 # creationflags argument
3320 CREATE_NEW_CONSOLE = 16
3321 sys.stderr.write(" a DOS box should flash briefly ...\n")
3322 subprocess.call(sys.executable +
3323 ' -c "import time; time.sleep(0.25)"',
3324 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003325
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003326 def test_invalid_args(self):
3327 # invalid arguments should raise ValueError
3328 self.assertRaises(ValueError, subprocess.call,
3329 [sys.executable, "-c",
3330 "import sys; sys.exit(47)"],
3331 preexec_fn=lambda: 1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003332
Oren Milman0b3a87e2017-09-14 22:30:28 +03003333 @support.cpython_only
3334 def test_issue31471(self):
3335 # There shouldn't be an assertion failure in Popen() in case the env
3336 # argument has a bad keys() method.
3337 class BadEnv(dict):
3338 keys = None
3339 with self.assertRaises(TypeError):
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003340 subprocess.Popen(ZERO_RETURN_CMD, env=BadEnv())
Oren Milman0b3a87e2017-09-14 22:30:28 +03003341
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003342 def test_close_fds(self):
3343 # close file descriptors
3344 rc = subprocess.call([sys.executable, "-c",
3345 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003346 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003347 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003348
Segev Finerb2a60832017-12-18 11:28:19 +02003349 def test_close_fds_with_stdio(self):
3350 import msvcrt
3351
3352 fds = os.pipe()
3353 self.addCleanup(os.close, fds[0])
3354 self.addCleanup(os.close, fds[1])
3355
3356 handles = []
3357 for fd in fds:
3358 os.set_inheritable(fd, True)
3359 handles.append(msvcrt.get_osfhandle(fd))
3360
3361 p = subprocess.Popen([sys.executable, "-c",
3362 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3363 stdout=subprocess.PIPE, close_fds=False)
3364 stdout, stderr = p.communicate()
3365 self.assertEqual(p.returncode, 0)
3366 int(stdout.strip()) # Check that stdout is an integer
3367
3368 p = subprocess.Popen([sys.executable, "-c",
3369 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3370 stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
3371 stdout, stderr = p.communicate()
3372 self.assertEqual(p.returncode, 1)
3373 self.assertIn(b"OSError", stderr)
3374
3375 # The same as the previous call, but with an empty handle_list
3376 handle_list = []
3377 startupinfo = subprocess.STARTUPINFO()
3378 startupinfo.lpAttributeList = {"handle_list": handle_list}
3379 p = subprocess.Popen([sys.executable, "-c",
3380 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3381 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3382 startupinfo=startupinfo, close_fds=True)
3383 stdout, stderr = p.communicate()
3384 self.assertEqual(p.returncode, 1)
3385 self.assertIn(b"OSError", stderr)
3386
3387 # Check for a warning due to using handle_list and close_fds=False
Hai Shi0c4f0f32020-06-30 21:46:31 +08003388 with warnings_helper.check_warnings((".*overriding close_fds",
3389 RuntimeWarning)):
Segev Finerb2a60832017-12-18 11:28:19 +02003390 startupinfo = subprocess.STARTUPINFO()
3391 startupinfo.lpAttributeList = {"handle_list": handles[:]}
3392 p = subprocess.Popen([sys.executable, "-c",
3393 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3394 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3395 startupinfo=startupinfo, close_fds=False)
3396 stdout, stderr = p.communicate()
3397 self.assertEqual(p.returncode, 0)
3398
3399 def test_empty_attribute_list(self):
3400 startupinfo = subprocess.STARTUPINFO()
3401 startupinfo.lpAttributeList = {}
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003402 subprocess.call(ZERO_RETURN_CMD,
Segev Finerb2a60832017-12-18 11:28:19 +02003403 startupinfo=startupinfo)
3404
3405 def test_empty_handle_list(self):
3406 startupinfo = subprocess.STARTUPINFO()
3407 startupinfo.lpAttributeList = {"handle_list": []}
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003408 subprocess.call(ZERO_RETURN_CMD,
Segev Finerb2a60832017-12-18 11:28:19 +02003409 startupinfo=startupinfo)
3410
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003411 def test_shell_sequence(self):
3412 # Run command through the shell (sequence)
3413 newenv = os.environ.copy()
3414 newenv["FRUIT"] = "physalis"
3415 p = subprocess.Popen(["set"], shell=1,
3416 stdout=subprocess.PIPE,
3417 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003418 with p:
3419 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00003420
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003421 def test_shell_string(self):
3422 # Run command through the shell (string)
3423 newenv = os.environ.copy()
3424 newenv["FRUIT"] = "physalis"
3425 p = subprocess.Popen("set", shell=1,
3426 stdout=subprocess.PIPE,
3427 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02003428 with p:
3429 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003430
Steve Dower050acae2016-09-06 20:16:17 -07003431 def test_shell_encodings(self):
3432 # Run command through the shell (string)
3433 for enc in ['ansi', 'oem']:
3434 newenv = os.environ.copy()
3435 newenv["FRUIT"] = "physalis"
3436 p = subprocess.Popen("set", shell=1,
3437 stdout=subprocess.PIPE,
3438 env=newenv,
3439 encoding=enc)
3440 with p:
3441 self.assertIn("physalis", p.stdout.read(), enc)
3442
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003443 def test_call_string(self):
3444 # call() function with string argument on Windows
3445 rc = subprocess.call(sys.executable +
3446 ' -c "import sys; sys.exit(47)"')
3447 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003448
Florent Xicluna4886d242010-03-08 13:27:26 +00003449 def _kill_process(self, method, *args):
3450 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00003451 p = subprocess.Popen([sys.executable, "-c", """if 1:
3452 import sys, time
3453 sys.stdout.write('x\\n')
3454 sys.stdout.flush()
3455 time.sleep(30)
3456 """],
3457 stdin=subprocess.PIPE,
3458 stdout=subprocess.PIPE,
3459 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003460 with p:
3461 # Wait for the interpreter to be completely initialized before
3462 # sending any signal.
3463 p.stdout.read(1)
3464 getattr(p, method)(*args)
3465 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01003466 self.assertEqual(stderr, b'')
Victor Stinner7438c612016-05-20 12:43:15 +02003467 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00003468 self.assertNotEqual(returncode, 0)
3469
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003470 def _kill_dead_process(self, method, *args):
3471 p = subprocess.Popen([sys.executable, "-c", """if 1:
3472 import sys, time
3473 sys.stdout.write('x\\n')
3474 sys.stdout.flush()
3475 sys.exit(42)
3476 """],
3477 stdin=subprocess.PIPE,
3478 stdout=subprocess.PIPE,
3479 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02003480 with p:
3481 # Wait for the interpreter to be completely initialized before
3482 # sending any signal.
3483 p.stdout.read(1)
3484 # The process should end after this
3485 time.sleep(1)
3486 # This shouldn't raise even though the child is now dead
3487 getattr(p, method)(*args)
3488 _, stderr = p.communicate()
Victor Stinner6cac1132019-12-08 08:38:16 +01003489 self.assertEqual(stderr, b'')
Victor Stinner7438c612016-05-20 12:43:15 +02003490 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003491 self.assertEqual(rc, 42)
3492
Florent Xicluna4886d242010-03-08 13:27:26 +00003493 def test_send_signal(self):
3494 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00003495
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003496 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003497 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00003498
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003499 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00003500 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00003501
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01003502 def test_send_signal_dead(self):
3503 self._kill_dead_process('send_signal', signal.SIGTERM)
3504
3505 def test_kill_dead(self):
3506 self._kill_dead_process('kill')
3507
3508 def test_terminate_dead(self):
3509 self._kill_dead_process('terminate')
3510
Martin Panter23172bd2016-04-16 11:28:10 +00003511class MiscTests(unittest.TestCase):
Gregory P. Smithf4d644f2018-01-29 21:27:39 -08003512
3513 class RecordingPopen(subprocess.Popen):
3514 """A Popen that saves a reference to each instance for testing."""
3515 instances_created = []
3516
3517 def __init__(self, *args, **kwargs):
3518 super().__init__(*args, **kwargs)
3519 self.instances_created.append(self)
3520
3521 @mock.patch.object(subprocess.Popen, "_communicate")
3522 def _test_keyboardinterrupt_no_kill(self, popener, mock__communicate,
3523 **kwargs):
3524 """Fake a SIGINT happening during Popen._communicate() and ._wait().
3525
3526 This avoids the need to actually try and get test environments to send
3527 and receive signals reliably across platforms. The net effect of a ^C
3528 happening during a blocking subprocess execution which we want to clean
3529 up from is a KeyboardInterrupt coming out of communicate() or wait().
3530 """
3531
3532 mock__communicate.side_effect = KeyboardInterrupt
3533 try:
3534 with mock.patch.object(subprocess.Popen, "_wait") as mock__wait:
3535 # We patch out _wait() as no signal was involved so the
3536 # child process isn't actually going to exit rapidly.
3537 mock__wait.side_effect = KeyboardInterrupt
3538 with mock.patch.object(subprocess, "Popen",
3539 self.RecordingPopen):
3540 with self.assertRaises(KeyboardInterrupt):
3541 popener([sys.executable, "-c",
3542 "import time\ntime.sleep(9)\nimport sys\n"
3543 "sys.stderr.write('\\n!runaway child!\\n')"],
3544 stdout=subprocess.DEVNULL, **kwargs)
3545 for call in mock__wait.call_args_list[1:]:
3546 self.assertNotEqual(
3547 call, mock.call(timeout=None),
3548 "no open-ended wait() after the first allowed: "
3549 f"{mock__wait.call_args_list}")
3550 sigint_calls = []
3551 for call in mock__wait.call_args_list:
3552 if call == mock.call(timeout=0.25): # from Popen.__init__
3553 sigint_calls.append(call)
3554 self.assertLessEqual(mock__wait.call_count, 2,
3555 msg=mock__wait.call_args_list)
3556 self.assertEqual(len(sigint_calls), 1,
3557 msg=mock__wait.call_args_list)
3558 finally:
3559 # cleanup the forgotten (due to our mocks) child process
3560 process = self.RecordingPopen.instances_created.pop()
3561 process.kill()
3562 process.wait()
3563 self.assertEqual([], self.RecordingPopen.instances_created)
3564
3565 def test_call_keyboardinterrupt_no_kill(self):
3566 self._test_keyboardinterrupt_no_kill(subprocess.call, timeout=6.282)
3567
3568 def test_run_keyboardinterrupt_no_kill(self):
3569 self._test_keyboardinterrupt_no_kill(subprocess.run, timeout=6.282)
3570
3571 def test_context_manager_keyboardinterrupt_no_kill(self):
3572 def popen_via_context_manager(*args, **kwargs):
3573 with subprocess.Popen(*args, **kwargs) as unused_process:
3574 raise KeyboardInterrupt # Test how __exit__ handles ^C.
3575 self._test_keyboardinterrupt_no_kill(popen_via_context_manager)
3576
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003577 def test_getoutput(self):
3578 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
3579 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
3580 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00003581
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003582 # we use mkdtemp in the next line to create an empty directory
3583 # under our exclusive control; from that, we can invent a pathname
3584 # that we _know_ won't exist. This is guaranteed to fail.
3585 dir = None
3586 try:
3587 dir = tempfile.mkdtemp()
3588 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00003589 status, output = subprocess.getstatusoutput(
Victor Stinner937ee9e2018-06-26 02:11:06 +02003590 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00003591 self.assertNotEqual(status, 0)
3592 finally:
3593 if dir is not None:
3594 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00003595
Gregory P. Smithace55862015-04-07 15:57:54 -07003596 def test__all__(self):
3597 """Ensure that __all__ is populated properly."""
Ruben Vorderman23c0fb82020-10-20 01:30:02 +02003598 intentionally_excluded = {"list2cmdline", "Handle", "pwd", "grp", "fcntl"}
Gregory P. Smithace55862015-04-07 15:57:54 -07003599 exported = set(subprocess.__all__)
3600 possible_exports = set()
3601 import types
3602 for name, value in subprocess.__dict__.items():
3603 if name.startswith('_'):
3604 continue
3605 if isinstance(value, (types.ModuleType,)):
3606 continue
3607 possible_exports.add(name)
3608 self.assertEqual(exported, possible_exports - intentionally_excluded)
3609
3610
Martin Panter23172bd2016-04-16 11:28:10 +00003611@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
3612 "Test needs selectors.PollSelector")
3613class ProcessTestCaseNoPoll(ProcessTestCase):
3614 def setUp(self):
3615 self.orig_selector = subprocess._PopenSelector
3616 subprocess._PopenSelector = selectors.SelectSelector
3617 ProcessTestCase.setUp(self)
3618
3619 def tearDown(self):
3620 subprocess._PopenSelector = self.orig_selector
3621 ProcessTestCase.tearDown(self)
3622
Gregory P. Smithd06fa472009-07-04 02:46:54 +00003623
Victor Stinner937ee9e2018-06-26 02:11:06 +02003624@unittest.skipUnless(mswindows, "Windows-specific tests")
Tim Golden126c2962010-08-11 14:20:40 +00003625class CommandsWithSpaces (BaseTestCase):
3626
3627 def setUp(self):
3628 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03003629 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00003630 self.fname = fname.lower ()
3631 os.write(f, b"import sys;"
3632 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
3633 )
3634 os.close(f)
3635
3636 def tearDown(self):
3637 os.remove(self.fname)
3638 super().tearDown()
3639
3640 def with_spaces(self, *args, **kwargs):
3641 kwargs['stdout'] = subprocess.PIPE
3642 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02003643 with p:
3644 self.assertEqual(
3645 p.stdout.read ().decode("mbcs"),
3646 "2 [%r, 'ab cd']" % self.fname
3647 )
Tim Golden126c2962010-08-11 14:20:40 +00003648
3649 def test_shell_string_with_spaces(self):
3650 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003651 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3652 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003653
3654 def test_shell_sequence_with_spaces(self):
3655 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00003656 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00003657
3658 def test_noshell_string_with_spaces(self):
3659 # call() function with string argument with spaces on Windows
3660 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
3661 "ab cd"))
3662
3663 def test_noshell_sequence_with_spaces(self):
3664 # call() function with sequence argument with spaces on Windows
3665 self.with_spaces([sys.executable, self.fname, "ab cd"])
3666
Brian Curtin79cdb662010-12-03 02:46:02 +00003667
Georg Brandla86b2622012-02-20 21:34:57 +01003668class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00003669
3670 def test_pipe(self):
3671 with subprocess.Popen([sys.executable, "-c",
3672 "import sys;"
3673 "sys.stdout.write('stdout');"
3674 "sys.stderr.write('stderr');"],
3675 stdout=subprocess.PIPE,
3676 stderr=subprocess.PIPE) as proc:
3677 self.assertEqual(proc.stdout.read(), b"stdout")
Victor Stinner6cac1132019-12-08 08:38:16 +01003678 self.assertEqual(proc.stderr.read(), b"stderr")
Brian Curtin79cdb662010-12-03 02:46:02 +00003679
3680 self.assertTrue(proc.stdout.closed)
3681 self.assertTrue(proc.stderr.closed)
3682
3683 def test_returncode(self):
3684 with subprocess.Popen([sys.executable, "-c",
3685 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07003686 pass
3687 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00003688 self.assertEqual(proc.returncode, 100)
3689
3690 def test_communicate_stdin(self):
3691 with subprocess.Popen([sys.executable, "-c",
3692 "import sys;"
3693 "sys.exit(sys.stdin.read() == 'context')"],
3694 stdin=subprocess.PIPE) as proc:
3695 proc.communicate(b"context")
3696 self.assertEqual(proc.returncode, 1)
3697
3698 def test_invalid_args(self):
Victor Stinnerb31206a2018-01-25 19:06:05 +01003699 with self.assertRaises(NONEXISTING_ERRORS):
Victor Stinner9a83f652017-08-21 23:51:31 +02003700 with subprocess.Popen(NONEXISTING_CMD,
Brian Curtin79cdb662010-12-03 02:46:02 +00003701 stdout=subprocess.PIPE,
3702 stderr=subprocess.PIPE) as proc:
3703 pass
3704
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003705 def test_broken_pipe_cleanup(self):
3706 """Broken pipe error should not prevent wait() (Issue 21619)"""
Gregory P. Smith67b93f82019-10-12 16:35:53 -07003707 proc = subprocess.Popen(ZERO_RETURN_CMD,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003708 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01003709 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003710 proc = proc.__enter__()
3711 # Prepare to send enough data to overflow any OS pipe buffering and
3712 # guarantee a broken pipe error. Data is held in BufferedWriter
3713 # buffer until closed.
3714 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003715 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003716 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02003717 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02003718 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003719 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02003720
Brian Curtin79cdb662010-12-03 02:46:02 +00003721
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003722if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04003723 unittest.main()