blob: f01bd1a6951865ab3c41eed89a3522c93e8c643b [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)1ef8c7e2016-06-04 00:22:17 +00002from unittest import mock
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003from test import support
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00004import subprocess
5import sys
Gregory P. Smith50e16e32017-01-22 17:28:38 -08006import platform
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00007import signal
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04008import io
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00009import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +000010import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000011import tempfile
12import time
Charles-François Natali3a4586a2013-11-08 19:56:59 +010013import selectors
Ezio Melotti184bdfb2010-02-18 09:37:05 +000014import sysconfig
Gregory P. Smith51ee2702010-12-13 07:59:39 +000015import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040016import shutil
Benjamin Petersonb870aa12011-12-10 12:44:25 -050017import gc
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030018import textwrap
Benjamin Peterson964561b2011-12-10 12:31:42 -050019
20try:
Gregory P. Smith1fa08bc2017-01-22 22:19:38 -080021 import ctypes
22except ImportError:
23 ctypes = None
24
25try:
Antoine Pitroua8392712013-08-30 23:38:13 +020026 import threading
27except ImportError:
28 threading = None
Benjamin Peterson964561b2011-12-10 12:31:42 -050029
Steve Dower22d06982016-09-06 19:38:15 -070030if support.PGO:
31 raise unittest.SkipTest("test is not helpful for PGO")
32
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000033mswindows = (sys.platform == "win32")
34
35#
36# Depends on the following external programs: Python
37#
38
39if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000040 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
41 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000042else:
43 SETBINARY = ''
44
Florent Xiclunab1e94e82010-02-27 22:12:37 +000045
Florent Xiclunac049d872010-03-27 22:47:23 +000046class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000047 def setUp(self):
48 # Try to minimize the number of children we have so this test
49 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000050 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000051
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000052 def tearDown(self):
53 for inst in subprocess._active:
54 inst.wait()
55 subprocess._cleanup()
56 self.assertFalse(subprocess._active, "subprocess._active not empty")
57
Florent Xiclunab1e94e82010-02-27 22:12:37 +000058 def assertStderrEqual(self, stderr, expected, msg=None):
59 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
60 # shutdown time. That frustrates tests trying to check stderr produced
61 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000062 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040063 # strip_python_stderr also strips whitespace, so we do too.
64 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000065 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000066
Florent Xiclunac049d872010-03-27 22:47:23 +000067
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080068class PopenTestException(Exception):
69 pass
70
71
72class PopenExecuteChildRaises(subprocess.Popen):
73 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
74 _execute_child fails.
75 """
76 def _execute_child(self, *args, **kwargs):
77 raise PopenTestException("Forced Exception for Test")
78
79
Florent Xiclunac049d872010-03-27 22:47:23 +000080class ProcessTestCase(BaseTestCase):
81
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070082 def test_io_buffered_by_default(self):
83 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
84 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
85 stderr=subprocess.PIPE)
86 try:
87 self.assertIsInstance(p.stdin, io.BufferedIOBase)
88 self.assertIsInstance(p.stdout, io.BufferedIOBase)
89 self.assertIsInstance(p.stderr, io.BufferedIOBase)
90 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -070091 p.stdin.close()
92 p.stdout.close()
93 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070094 p.wait()
95
96 def test_io_unbuffered_works(self):
97 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
98 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
99 stderr=subprocess.PIPE, bufsize=0)
100 try:
101 self.assertIsInstance(p.stdin, io.RawIOBase)
102 self.assertIsInstance(p.stdout, io.RawIOBase)
103 self.assertIsInstance(p.stderr, io.RawIOBase)
104 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700105 p.stdin.close()
106 p.stdout.close()
107 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700108 p.wait()
109
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000110 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000111 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000112 rc = subprocess.call([sys.executable, "-c",
113 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000114 self.assertEqual(rc, 47)
115
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400116 def test_call_timeout(self):
117 # call() function with timeout argument; we want to test that the child
118 # process gets killed when the timeout expires. If the child isn't
119 # killed, this call will deadlock since subprocess.call waits for the
120 # child.
121 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
122 [sys.executable, "-c", "while True: pass"],
123 timeout=0.1)
124
Peter Astrand454f7672005-01-01 09:36:35 +0000125 def test_check_call_zero(self):
126 # check_call() function with zero return code
127 rc = subprocess.check_call([sys.executable, "-c",
128 "import sys; sys.exit(0)"])
129 self.assertEqual(rc, 0)
130
131 def test_check_call_nonzero(self):
132 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000133 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000134 subprocess.check_call([sys.executable, "-c",
135 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000136 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000137
Georg Brandlf9734072008-12-07 15:30:06 +0000138 def test_check_output(self):
139 # check_output() function with zero return code
140 output = subprocess.check_output(
141 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000142 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000143
144 def test_check_output_nonzero(self):
145 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000146 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000147 subprocess.check_output(
148 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000149 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000150
151 def test_check_output_stderr(self):
152 # check_output() function stderr redirected to stdout
153 output = subprocess.check_output(
154 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
155 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000156 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000157
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300158 def test_check_output_stdin_arg(self):
159 # check_output() can be called with stdin set to a file
160 tf = tempfile.TemporaryFile()
161 self.addCleanup(tf.close)
162 tf.write(b'pear')
163 tf.seek(0)
164 output = subprocess.check_output(
165 [sys.executable, "-c",
166 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
167 stdin=tf)
168 self.assertIn(b'PEAR', output)
169
170 def test_check_output_input_arg(self):
171 # check_output() can be called with input set to a string
172 output = subprocess.check_output(
173 [sys.executable, "-c",
174 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
175 input=b'pear')
176 self.assertIn(b'PEAR', output)
177
Georg Brandlf9734072008-12-07 15:30:06 +0000178 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300179 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000180 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000181 output = subprocess.check_output(
182 [sys.executable, "-c", "print('will not be run')"],
183 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000184 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000185 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000186
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300187 def test_check_output_stdin_with_input_arg(self):
188 # check_output() refuses to accept 'stdin' with 'input'
189 tf = tempfile.TemporaryFile()
190 self.addCleanup(tf.close)
191 tf.write(b'pear')
192 tf.seek(0)
193 with self.assertRaises(ValueError) as c:
194 output = subprocess.check_output(
195 [sys.executable, "-c", "print('will not be run')"],
196 stdin=tf, input=b'hare')
197 self.fail("Expected ValueError when stdin and input args supplied.")
198 self.assertIn('stdin', c.exception.args[0])
199 self.assertIn('input', c.exception.args[0])
200
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400201 def test_check_output_timeout(self):
202 # check_output() function with timeout arg
203 with self.assertRaises(subprocess.TimeoutExpired) as c:
204 output = subprocess.check_output(
205 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200206 "import sys, time\n"
207 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400208 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200209 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400210 # Some heavily loaded buildbots (sparc Debian 3.x) require
211 # this much time to start and print.
212 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400213 self.fail("Expected TimeoutExpired.")
214 self.assertEqual(c.exception.output, b'BDFL')
215
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000216 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000217 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000218 newenv = os.environ.copy()
219 newenv["FRUIT"] = "banana"
220 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000221 'import sys, os;'
222 'sys.exit(os.getenv("FRUIT")=="banana")'],
223 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000224 self.assertEqual(rc, 1)
225
Victor Stinner87b9bc32011-06-01 00:57:47 +0200226 def test_invalid_args(self):
227 # Popen() called with invalid arguments should raise TypeError
228 # but Popen.__del__ should not complain (issue #12085)
229 with support.captured_stderr() as s:
230 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
231 argcount = subprocess.Popen.__init__.__code__.co_argcount
232 too_many_args = [0] * (argcount + 1)
233 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
234 self.assertEqual(s.getvalue(), '')
235
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000236 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000237 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000238 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000239 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000240 self.addCleanup(p.stdout.close)
241 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000242 p.wait()
243 self.assertEqual(p.stdin, None)
244
245 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200246 # .stdout is None when not redirected, and the child's stdout will
247 # be inherited from the parent. In order to test this we run a
248 # subprocess in a subprocess:
249 # this_test
250 # \-- subprocess created by this test (parent)
251 # \-- subprocess created by the parent subprocess (child)
252 # The parent doesn't specify stdout, so the child will use the
253 # parent's stdout. This test checks that the message printed by the
254 # child goes to the parent stdout. The parent also checks that the
255 # child's stdout is None. See #11963.
256 code = ('import sys; from subprocess import Popen, PIPE;'
257 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
258 ' stdin=PIPE, stderr=PIPE);'
259 'p.wait(); assert p.stdout is None;')
260 p = subprocess.Popen([sys.executable, "-c", code],
261 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
262 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000263 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200264 out, err = p.communicate()
265 self.assertEqual(p.returncode, 0, err)
266 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000267
268 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000269 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000270 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000271 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000272 self.addCleanup(p.stdout.close)
273 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000274 p.wait()
275 self.assertEqual(p.stderr, None)
276
Chris Jerdonek776cb192012-10-08 15:56:43 -0700277 def _assert_python(self, pre_args, **kwargs):
278 # We include sys.exit() to prevent the test runner from hanging
279 # whenever python is found.
280 args = pre_args + ["import sys; sys.exit(47)"]
281 p = subprocess.Popen(args, **kwargs)
282 p.wait()
283 self.assertEqual(47, p.returncode)
284
285 def test_executable(self):
286 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700287 #
288 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
289 # determine where its standard library is, so we need the directory
290 # of args[0] to be valid for the Popen() call to Python to succeed.
291 # See also issue #16170 and issue #7774.
292 doesnotexist = os.path.join(os.path.dirname(sys.executable),
293 "doesnotexist")
294 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700295
296 def test_executable_takes_precedence(self):
297 # Check that the executable argument takes precedence over args[0].
298 #
299 # Verify first that the call succeeds without the executable arg.
300 pre_args = [sys.executable, "-c"]
301 self._assert_python(pre_args)
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +0100302 self.assertRaises((FileNotFoundError, PermissionError),
303 self._assert_python, pre_args,
Chris Jerdonek776cb192012-10-08 15:56:43 -0700304 executable="doesnotexist")
305
306 @unittest.skipIf(mswindows, "executable argument replaces shell")
307 def test_executable_replaces_shell(self):
308 # Check that the executable argument replaces the default shell
309 # when shell=True.
310 self._assert_python([], executable=sys.executable, shell=True)
311
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700312 # For use in the test_cwd* tests below.
313 def _normalize_cwd(self, cwd):
314 # Normalize an expected cwd (for Tru64 support).
315 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
316 # strings. See bug #1063571.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300317 with support.change_cwd(cwd):
318 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700319
320 # For use in the test_cwd* tests below.
321 def _split_python_path(self):
322 # Return normalized (python_dir, python_base).
323 python_path = os.path.realpath(sys.executable)
324 return os.path.split(python_path)
325
326 # For use in the test_cwd* tests below.
327 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
328 # Invoke Python via Popen, and assert that (1) the call succeeds,
329 # and that (2) the current working directory of the child process
330 # matches *expected_cwd*.
331 p = subprocess.Popen([python_arg, "-c",
332 "import os, sys; "
333 "sys.stdout.write(os.getcwd()); "
334 "sys.exit(47)"],
335 stdout=subprocess.PIPE,
336 **kwargs)
337 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000338 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700339 self.assertEqual(47, p.returncode)
340 normcase = os.path.normcase
341 self.assertEqual(normcase(expected_cwd),
342 normcase(p.stdout.read().decode("utf-8")))
343
344 def test_cwd(self):
345 # Check that cwd changes the cwd for the child process.
346 temp_dir = tempfile.gettempdir()
347 temp_dir = self._normalize_cwd(temp_dir)
348 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
349
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530350 def test_cwd_with_pathlike(self):
351 temp_dir = tempfile.gettempdir()
352 temp_dir = self._normalize_cwd(temp_dir)
353
354 class _PathLikeObj:
355 def __fspath__(self):
356 return temp_dir
357
358 self._assert_cwd(temp_dir, sys.executable, cwd=_PathLikeObj())
359
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700360 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700361 def test_cwd_with_relative_arg(self):
362 # Check that Popen looks for args[0] relative to cwd if args[0]
363 # is relative.
364 python_dir, python_base = self._split_python_path()
365 rel_python = os.path.join(os.curdir, python_base)
366 with support.temp_cwd() as wrong_dir:
367 # Before calling with the correct cwd, confirm that the call fails
368 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700369 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700370 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700371 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700372 [rel_python], cwd=wrong_dir)
373 python_dir = self._normalize_cwd(python_dir)
374 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
375
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700376 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700377 def test_cwd_with_relative_executable(self):
378 # Check that Popen looks for executable relative to cwd if executable
379 # is relative (and that executable takes precedence over args[0]).
380 python_dir, python_base = self._split_python_path()
381 rel_python = os.path.join(os.curdir, python_base)
382 doesntexist = "somethingyoudonthave"
383 with support.temp_cwd() as wrong_dir:
384 # Before calling with the correct cwd, confirm that the call fails
385 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700386 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700387 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700388 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700389 [doesntexist], executable=rel_python,
390 cwd=wrong_dir)
391 python_dir = self._normalize_cwd(python_dir)
392 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
393 cwd=python_dir)
394
395 def test_cwd_with_absolute_arg(self):
396 # Check that Popen can find the executable when the cwd is wrong
397 # if args[0] is an absolute path.
398 python_dir, python_base = self._split_python_path()
399 abs_python = os.path.join(python_dir, python_base)
400 rel_python = os.path.join(os.curdir, python_base)
Berker Peksagce643912015-05-06 06:33:17 +0300401 with support.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700402 # Before calling with an absolute path, confirm that using a
403 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700404 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700405 [rel_python], cwd=wrong_dir)
406 wrong_dir = self._normalize_cwd(wrong_dir)
407 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
408
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100409 @unittest.skipIf(sys.base_prefix != sys.prefix,
410 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000411 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700412 python_dir, python_base = self._split_python_path()
413 python_dir = self._normalize_cwd(python_dir)
414 self._assert_cwd(python_dir, "somethingyoudonthave",
415 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000416
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100417 @unittest.skipIf(sys.base_prefix != sys.prefix,
418 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000419 @unittest.skipIf(sysconfig.is_python_build(),
420 "need an installed Python. See #7774")
421 def test_executable_without_cwd(self):
422 # For a normal installation, it should work without 'cwd'
423 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700424 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
425 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000426
427 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000428 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000429 p = subprocess.Popen([sys.executable, "-c",
430 'import sys; sys.exit(sys.stdin.read() == "pear")'],
431 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000432 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000433 p.stdin.close()
434 p.wait()
435 self.assertEqual(p.returncode, 1)
436
437 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000438 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000439 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000440 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000441 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000442 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000443 os.lseek(d, 0, 0)
444 p = subprocess.Popen([sys.executable, "-c",
445 'import sys; sys.exit(sys.stdin.read() == "pear")'],
446 stdin=d)
447 p.wait()
448 self.assertEqual(p.returncode, 1)
449
450 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000451 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000452 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000453 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000454 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000455 tf.seek(0)
456 p = subprocess.Popen([sys.executable, "-c",
457 'import sys; sys.exit(sys.stdin.read() == "pear")'],
458 stdin=tf)
459 p.wait()
460 self.assertEqual(p.returncode, 1)
461
462 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000463 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000464 p = subprocess.Popen([sys.executable, "-c",
465 'import sys; sys.stdout.write("orange")'],
466 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200467 with p:
468 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000469
470 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000471 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000472 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000473 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000474 d = tf.fileno()
475 p = subprocess.Popen([sys.executable, "-c",
476 'import sys; sys.stdout.write("orange")'],
477 stdout=d)
478 p.wait()
479 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000480 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000481
482 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000483 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000484 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000485 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000486 p = subprocess.Popen([sys.executable, "-c",
487 'import sys; sys.stdout.write("orange")'],
488 stdout=tf)
489 p.wait()
490 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000491 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000492
493 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000494 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000495 p = subprocess.Popen([sys.executable, "-c",
496 'import sys; sys.stderr.write("strawberry")'],
497 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200498 with p:
499 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000500
501 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000502 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000503 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000504 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000505 d = tf.fileno()
506 p = subprocess.Popen([sys.executable, "-c",
507 'import sys; sys.stderr.write("strawberry")'],
508 stderr=d)
509 p.wait()
510 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000511 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000512
513 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000514 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000515 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000516 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000517 p = subprocess.Popen([sys.executable, "-c",
518 'import sys; sys.stderr.write("strawberry")'],
519 stderr=tf)
520 p.wait()
521 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000522 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000523
Martin Panterc7635892016-05-13 01:54:44 +0000524 def test_stderr_redirect_with_no_stdout_redirect(self):
525 # test stderr=STDOUT while stdout=None (not set)
526
527 # - grandchild prints to stderr
528 # - child redirects grandchild's stderr to its stdout
529 # - the parent should get grandchild's stderr in child's stdout
530 p = subprocess.Popen([sys.executable, "-c",
531 'import sys, subprocess;'
532 'rc = subprocess.call([sys.executable, "-c",'
533 ' "import sys;"'
534 ' "sys.stderr.write(\'42\')"],'
535 ' stderr=subprocess.STDOUT);'
536 'sys.exit(rc)'],
537 stdout=subprocess.PIPE,
538 stderr=subprocess.PIPE)
539 stdout, stderr = p.communicate()
540 #NOTE: stdout should get stderr from grandchild
541 self.assertStderrEqual(stdout, b'42')
542 self.assertStderrEqual(stderr, b'') # should be empty
543 self.assertEqual(p.returncode, 0)
544
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000545 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000546 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000547 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000548 'import sys;'
549 'sys.stdout.write("apple");'
550 'sys.stdout.flush();'
551 'sys.stderr.write("orange")'],
552 stdout=subprocess.PIPE,
553 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200554 with p:
555 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000556
557 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000558 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000559 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000560 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000561 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000562 'import sys;'
563 'sys.stdout.write("apple");'
564 'sys.stdout.flush();'
565 'sys.stderr.write("orange")'],
566 stdout=tf,
567 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000568 p.wait()
569 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000570 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000571
Thomas Wouters89f507f2006-12-13 04:49:30 +0000572 def test_stdout_filedes_of_stdout(self):
573 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200574 # To avoid printing the text on stdout, we do something similar to
575 # test_stdout_none (see above). The parent subprocess calls the child
576 # subprocess passing stdout=1, and this test uses stdout=PIPE in
577 # order to capture and check the output of the parent. See #11963.
578 code = ('import sys, subprocess; '
579 'rc = subprocess.call([sys.executable, "-c", '
580 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
581 'b\'test with stdout=1\'))"], stdout=1); '
582 'assert rc == 18')
583 p = subprocess.Popen([sys.executable, "-c", code],
584 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
585 self.addCleanup(p.stdout.close)
586 self.addCleanup(p.stderr.close)
587 out, err = p.communicate()
588 self.assertEqual(p.returncode, 0, err)
589 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000590
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200591 def test_stdout_devnull(self):
592 p = subprocess.Popen([sys.executable, "-c",
593 'for i in range(10240):'
594 'print("x" * 1024)'],
595 stdout=subprocess.DEVNULL)
596 p.wait()
597 self.assertEqual(p.stdout, None)
598
599 def test_stderr_devnull(self):
600 p = subprocess.Popen([sys.executable, "-c",
601 'import sys\n'
602 'for i in range(10240):'
603 'sys.stderr.write("x" * 1024)'],
604 stderr=subprocess.DEVNULL)
605 p.wait()
606 self.assertEqual(p.stderr, None)
607
608 def test_stdin_devnull(self):
609 p = subprocess.Popen([sys.executable, "-c",
610 'import sys;'
611 'sys.stdin.read(1)'],
612 stdin=subprocess.DEVNULL)
613 p.wait()
614 self.assertEqual(p.stdin, None)
615
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000616 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000617 newenv = os.environ.copy()
618 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200619 with subprocess.Popen([sys.executable, "-c",
620 'import sys,os;'
621 'sys.stdout.write(os.getenv("FRUIT"))'],
622 stdout=subprocess.PIPE,
623 env=newenv) as p:
624 stdout, stderr = p.communicate()
625 self.assertEqual(stdout, b"orange")
626
Victor Stinner62d51182011-06-23 01:02:25 +0200627 # Windows requires at least the SYSTEMROOT environment variable to start
628 # Python
629 @unittest.skipIf(sys.platform == 'win32',
630 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200631 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200632 'the python library cannot be loaded '
633 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200634 def test_empty_env(self):
635 with subprocess.Popen([sys.executable, "-c",
636 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200637 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200638 stdout=subprocess.PIPE,
639 env={}) as p:
640 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200641 self.assertIn(stdout.strip(),
642 (b"[]",
643 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
644 # environment
645 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000646
Peter Astrandcbac93c2005-03-03 20:24:28 +0000647 def test_communicate_stdin(self):
648 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000649 'import sys;'
650 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000651 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000652 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000653 self.assertEqual(p.returncode, 1)
654
655 def test_communicate_stdout(self):
656 p = subprocess.Popen([sys.executable, "-c",
657 'import sys; sys.stdout.write("pineapple")'],
658 stdout=subprocess.PIPE)
659 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000660 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000661 self.assertEqual(stderr, None)
662
663 def test_communicate_stderr(self):
664 p = subprocess.Popen([sys.executable, "-c",
665 'import sys; sys.stderr.write("pineapple")'],
666 stderr=subprocess.PIPE)
667 (stdout, stderr) = p.communicate()
668 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000669 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000670
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000671 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000672 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000673 'import sys,os;'
674 'sys.stderr.write("pineapple");'
675 'sys.stdout.write(sys.stdin.read())'],
676 stdin=subprocess.PIPE,
677 stdout=subprocess.PIPE,
678 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000679 self.addCleanup(p.stdout.close)
680 self.addCleanup(p.stderr.close)
681 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000682 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000683 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000684 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000685
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400686 def test_communicate_timeout(self):
687 p = subprocess.Popen([sys.executable, "-c",
688 'import sys,os,time;'
689 'sys.stderr.write("pineapple\\n");'
690 'time.sleep(1);'
691 'sys.stderr.write("pear\\n");'
692 'sys.stdout.write(sys.stdin.read())'],
693 universal_newlines=True,
694 stdin=subprocess.PIPE,
695 stdout=subprocess.PIPE,
696 stderr=subprocess.PIPE)
697 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
698 timeout=0.3)
699 # Make sure we can keep waiting for it, and that we get the whole output
700 # after it completes.
701 (stdout, stderr) = p.communicate()
702 self.assertEqual(stdout, "banana")
703 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
704
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700705 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200706 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400707 p = subprocess.Popen([sys.executable, "-c",
708 'import sys,os,time;'
709 'sys.stdout.write("a" * (64 * 1024));'
710 'time.sleep(0.2);'
711 'sys.stdout.write("a" * (64 * 1024));'
712 'time.sleep(0.2);'
713 'sys.stdout.write("a" * (64 * 1024));'
714 'time.sleep(0.2);'
715 'sys.stdout.write("a" * (64 * 1024));'],
716 stdout=subprocess.PIPE)
717 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
718 (stdout, _) = p.communicate()
719 self.assertEqual(len(stdout), 4 * 64 * 1024)
720
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000721 # Test for the fd leak reported in http://bugs.python.org/issue2791.
722 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000723 for stdin_pipe in (False, True):
724 for stdout_pipe in (False, True):
725 for stderr_pipe in (False, True):
726 options = {}
727 if stdin_pipe:
728 options['stdin'] = subprocess.PIPE
729 if stdout_pipe:
730 options['stdout'] = subprocess.PIPE
731 if stderr_pipe:
732 options['stderr'] = subprocess.PIPE
733 if not options:
734 continue
735 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
736 p.communicate()
737 if p.stdin is not None:
738 self.assertTrue(p.stdin.closed)
739 if p.stdout is not None:
740 self.assertTrue(p.stdout.closed)
741 if p.stderr is not None:
742 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000743
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000744 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000745 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000746 p = subprocess.Popen([sys.executable, "-c",
747 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000748 (stdout, stderr) = p.communicate()
749 self.assertEqual(stdout, None)
750 self.assertEqual(stderr, None)
751
752 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000753 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000754 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000755 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000756 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000757 os.close(x)
758 os.close(y)
759 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000760 'import sys,os;'
761 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200762 'sys.stderr.write("x" * %d);'
763 'sys.stdout.write(sys.stdin.read())' %
764 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000765 stdin=subprocess.PIPE,
766 stdout=subprocess.PIPE,
767 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000768 self.addCleanup(p.stdout.close)
769 self.addCleanup(p.stderr.close)
770 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200771 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000772 (stdout, stderr) = p.communicate(string_to_write)
773 self.assertEqual(stdout, string_to_write)
774
775 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000776 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000777 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000778 'import sys,os;'
779 'sys.stdout.write(sys.stdin.read())'],
780 stdin=subprocess.PIPE,
781 stdout=subprocess.PIPE,
782 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000783 self.addCleanup(p.stdout.close)
784 self.addCleanup(p.stderr.close)
785 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000786 p.stdin.write(b"banana")
787 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000788 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000789 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000790
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000791 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000792 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000793 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200794 'buf = sys.stdout.buffer;'
795 'buf.write(sys.stdin.readline().encode());'
796 'buf.flush();'
797 'buf.write(b"line2\\n");'
798 'buf.flush();'
799 'buf.write(sys.stdin.read().encode());'
800 'buf.flush();'
801 'buf.write(b"line4\\n");'
802 'buf.flush();'
803 'buf.write(b"line5\\r\\n");'
804 'buf.flush();'
805 'buf.write(b"line6\\r");'
806 'buf.flush();'
807 'buf.write(b"\\nline7");'
808 'buf.flush();'
809 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200810 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000811 stdout=subprocess.PIPE,
812 universal_newlines=1)
Victor Stinner7438c612016-05-20 12:43:15 +0200813 with p:
814 p.stdin.write("line1\n")
815 p.stdin.flush()
816 self.assertEqual(p.stdout.readline(), "line1\n")
817 p.stdin.write("line3\n")
818 p.stdin.close()
819 self.addCleanup(p.stdout.close)
820 self.assertEqual(p.stdout.readline(),
821 "line2\n")
822 self.assertEqual(p.stdout.read(6),
823 "line3\n")
824 self.assertEqual(p.stdout.read(),
825 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000826
827 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000828 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000829 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000830 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200831 'buf = sys.stdout.buffer;'
832 'buf.write(b"line2\\n");'
833 'buf.flush();'
834 'buf.write(b"line4\\n");'
835 'buf.flush();'
836 'buf.write(b"line5\\r\\n");'
837 'buf.flush();'
838 'buf.write(b"line6\\r");'
839 'buf.flush();'
840 'buf.write(b"\\nline7");'
841 'buf.flush();'
842 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200843 stderr=subprocess.PIPE,
844 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000845 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000846 self.addCleanup(p.stdout.close)
847 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000848 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200849 self.assertEqual(stdout,
850 "line2\nline4\nline5\nline6\nline7\nline8")
851
852 def test_universal_newlines_communicate_stdin(self):
853 # universal newlines through communicate(), with only stdin
854 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300855 'import sys,os;' + SETBINARY + textwrap.dedent('''
856 s = sys.stdin.readline()
857 assert s == "line1\\n", repr(s)
858 s = sys.stdin.read()
859 assert s == "line3\\n", repr(s)
860 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200861 stdin=subprocess.PIPE,
862 universal_newlines=1)
863 (stdout, stderr) = p.communicate("line1\nline3\n")
864 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000865
Andrew Svetlovf3765072012-08-14 18:35:17 +0300866 def test_universal_newlines_communicate_input_none(self):
867 # Test communicate(input=None) with universal newlines.
868 #
869 # We set stdout to PIPE because, as of this writing, a different
870 # code path is tested when the number of pipes is zero or one.
871 p = subprocess.Popen([sys.executable, "-c", "pass"],
872 stdin=subprocess.PIPE,
873 stdout=subprocess.PIPE,
874 universal_newlines=True)
875 p.communicate()
876 self.assertEqual(p.returncode, 0)
877
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300878 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300879 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300880 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300881 'import sys,os;' + SETBINARY + textwrap.dedent('''
882 s = sys.stdin.buffer.readline()
883 sys.stdout.buffer.write(s)
884 sys.stdout.buffer.write(b"line2\\r")
885 sys.stderr.buffer.write(b"eline2\\n")
886 s = sys.stdin.buffer.read()
887 sys.stdout.buffer.write(s)
888 sys.stdout.buffer.write(b"line4\\n")
889 sys.stdout.buffer.write(b"line5\\r\\n")
890 sys.stderr.buffer.write(b"eline6\\r")
891 sys.stderr.buffer.write(b"eline7\\r\\nz")
892 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300893 stdin=subprocess.PIPE,
894 stderr=subprocess.PIPE,
895 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300896 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300897 self.addCleanup(p.stdout.close)
898 self.addCleanup(p.stderr.close)
899 (stdout, stderr) = p.communicate("line1\nline3\n")
900 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300901 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300902 # Python debug build push something like "[42442 refs]\n"
903 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300904 # Don't use assertStderrEqual because it strips CR and LF from output.
905 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300906
Andrew Svetlov82860712012-08-19 22:13:41 +0300907 def test_universal_newlines_communicate_encodings(self):
908 # Check that universal newlines mode works for various encodings,
909 # in particular for encodings in the UTF-16 and UTF-32 families.
910 # See issue #15595.
911 #
912 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
913 # without, and UTF-16 and UTF-32.
914 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +0300915 code = ("import sys; "
916 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
917 encoding)
918 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -0700919 # We set stdin to be non-None because, as of this writing,
920 # a different code path is used when the number of pipes is
921 # zero or one.
922 popen = subprocess.Popen(args,
923 stdin=subprocess.PIPE,
924 stdout=subprocess.PIPE,
925 encoding=encoding)
926 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +0300927 self.assertEqual(stdout, '1\n2\n3\n4')
928
Steve Dower050acae2016-09-06 20:16:17 -0700929 def test_communicate_errors(self):
930 for errors, expected in [
931 ('ignore', ''),
932 ('replace', '\ufffd\ufffd'),
933 ('surrogateescape', '\udc80\udc80'),
934 ('backslashreplace', '\\x80\\x80'),
935 ]:
936 code = ("import sys; "
937 r"sys.stdout.buffer.write(b'[\x80\x80]')")
938 args = [sys.executable, '-c', code]
939 # We set stdin to be non-None because, as of this writing,
940 # a different code path is used when the number of pipes is
941 # zero or one.
942 popen = subprocess.Popen(args,
943 stdin=subprocess.PIPE,
944 stdout=subprocess.PIPE,
945 encoding='utf-8',
946 errors=errors)
947 stdout, stderr = popen.communicate(input='')
948 self.assertEqual(stdout, '[{}]'.format(expected))
949
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000950 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000951 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000952 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000953 max_handles = 1026 # too much for most UNIX systems
954 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000955 max_handles = 2050 # too much for (at least some) Windows setups
956 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400957 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000958 try:
959 for i in range(max_handles):
960 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400961 tmpfile = os.path.join(tmpdir, support.TESTFN)
962 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000963 except OSError as e:
964 if e.errno != errno.EMFILE:
965 raise
966 break
967 else:
968 self.skipTest("failed to reach the file descriptor limit "
969 "(tried %d)" % max_handles)
970 # Close a couple of them (should be enough for a subprocess)
971 for i in range(10):
972 os.close(handles.pop())
973 # Loop creating some subprocesses. If one of them leaks some fds,
974 # the next loop iteration will fail by reaching the max fd limit.
975 for i in range(15):
976 p = subprocess.Popen([sys.executable, "-c",
977 "import sys;"
978 "sys.stdout.write(sys.stdin.read())"],
979 stdin=subprocess.PIPE,
980 stdout=subprocess.PIPE,
981 stderr=subprocess.PIPE)
982 data = p.communicate(b"lime")[0]
983 self.assertEqual(data, b"lime")
984 finally:
985 for h in handles:
986 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400987 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000988
989 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000990 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
991 '"a b c" d e')
992 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
993 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000994 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
995 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000996 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
997 'a\\\\\\b "de fg" h')
998 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
999 'a\\\\\\"b c d')
1000 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
1001 '"a\\\\b c" d e')
1002 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
1003 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001004 self.assertEqual(subprocess.list2cmdline(['ab', '']),
1005 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001006
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001007 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001008 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +02001009 "import os; os.read(0, 1)"],
1010 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001011 self.addCleanup(p.stdin.close)
1012 self.assertIsNone(p.poll())
1013 os.write(p.stdin.fileno(), b'A')
1014 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001015 # Subsequent invocations should just return the returncode
1016 self.assertEqual(p.poll(), 0)
1017
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001018 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001019 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001020 self.assertEqual(p.wait(), 0)
1021 # Subsequent invocations should just return the returncode
1022 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001023
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001024 def test_wait_timeout(self):
1025 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001026 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001027 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001028 p.wait(timeout=0.0001)
1029 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -04001030 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
1031 # time to start.
1032 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001033
Peter Astrand738131d2004-11-30 21:04:45 +00001034 def test_invalid_bufsize(self):
1035 # an invalid type of the bufsize argument should raise
1036 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001037 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +00001038 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001039
Guido van Rossum46a05a72007-06-07 21:56:45 +00001040 def test_bufsize_is_none(self):
1041 # bufsize=None should be the same as bufsize=0.
1042 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
1043 self.assertEqual(p.wait(), 0)
1044 # Again with keyword arg
1045 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
1046 self.assertEqual(p.wait(), 0)
1047
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001048 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1049 # subprocess may deadlock with bufsize=1, see issue #21332
1050 with subprocess.Popen([sys.executable, "-c", "import sys;"
1051 "sys.stdout.write(sys.stdin.readline());"
1052 "sys.stdout.flush()"],
1053 stdin=subprocess.PIPE,
1054 stdout=subprocess.PIPE,
1055 stderr=subprocess.DEVNULL,
1056 bufsize=1,
1057 universal_newlines=universal_newlines) as p:
1058 p.stdin.write(line) # expect that it flushes the line in text mode
1059 os.close(p.stdin.fileno()) # close it without flushing the buffer
1060 read_line = p.stdout.readline()
1061 try:
1062 p.stdin.close()
1063 except OSError:
1064 pass
1065 p.stdin = None
1066 self.assertEqual(p.returncode, 0)
1067 self.assertEqual(read_line, expected)
1068
1069 def test_bufsize_equal_one_text_mode(self):
1070 # line is flushed in text mode with bufsize=1.
1071 # we should get the full line in return
1072 line = "line\n"
1073 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1074
1075 def test_bufsize_equal_one_binary_mode(self):
1076 # line is not flushed in binary mode with bufsize=1.
1077 # we should get empty response
1078 line = b'line' + os.linesep.encode() # assume ascii-based locale
1079 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
1080
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001081 def test_leaking_fds_on_error(self):
1082 # see bug #5179: Popen leaks file descriptors to PIPEs if
1083 # the child fails to execute; this will eventually exhaust
1084 # the maximum number of open fds. 1024 seems a very common
1085 # value for that limit, but Windows has 2048, so we loop
1086 # 1024 times (each call leaked two fds).
1087 for i in range(1024):
Andrew Svetlov3438fa42012-12-17 23:35:18 +02001088 with self.assertRaises(OSError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001089 subprocess.Popen(['nonexisting_i_hope'],
1090 stdout=subprocess.PIPE,
1091 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -04001092 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -04001093 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001094 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001095
Antoine Pitroua8392712013-08-30 23:38:13 +02001096 @unittest.skipIf(threading is None, "threading required")
1097 def test_double_close_on_error(self):
1098 # Issue #18851
1099 fds = []
1100 def open_fds():
1101 for i in range(20):
1102 fds.extend(os.pipe())
1103 time.sleep(0.001)
1104 t = threading.Thread(target=open_fds)
1105 t.start()
1106 try:
1107 with self.assertRaises(EnvironmentError):
1108 subprocess.Popen(['nonexisting_i_hope'],
1109 stdin=subprocess.PIPE,
1110 stdout=subprocess.PIPE,
1111 stderr=subprocess.PIPE)
1112 finally:
1113 t.join()
1114 exc = None
1115 for fd in fds:
1116 # If a double close occurred, some of those fds will
1117 # already have been closed by mistake, and os.close()
1118 # here will raise.
1119 try:
1120 os.close(fd)
1121 except OSError as e:
1122 exc = e
1123 if exc is not None:
1124 raise exc
1125
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001126 @unittest.skipIf(threading is None, "threading required")
1127 def test_threadsafe_wait(self):
1128 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1129 proc = subprocess.Popen([sys.executable, '-c',
1130 'import time; time.sleep(12)'])
1131 self.assertEqual(proc.returncode, None)
1132 results = []
1133
1134 def kill_proc_timer_thread():
1135 results.append(('thread-start-poll-result', proc.poll()))
1136 # terminate it from the thread and wait for the result.
1137 proc.kill()
1138 proc.wait()
1139 results.append(('thread-after-kill-and-wait', proc.returncode))
1140 # this wait should be a no-op given the above.
1141 proc.wait()
1142 results.append(('thread-after-second-wait', proc.returncode))
1143
1144 # This is a timing sensitive test, the failure mode is
1145 # triggered when both the main thread and this thread are in
1146 # the wait() call at once. The delay here is to allow the
1147 # main thread to most likely be blocked in its wait() call.
1148 t = threading.Timer(0.2, kill_proc_timer_thread)
1149 t.start()
1150
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001151 if mswindows:
1152 expected_errorcode = 1
1153 else:
1154 # Should be -9 because of the proc.kill() from the thread.
1155 expected_errorcode = -9
1156
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001157 # Wait for the process to finish; the thread should kill it
1158 # long before it finishes on its own. Supplying a timeout
1159 # triggers a different code path for better coverage.
1160 proc.wait(timeout=20)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001161 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001162 msg="unexpected result in wait from main thread")
1163
1164 # This should be a no-op with no change in returncode.
1165 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001166 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001167 msg="unexpected result in second main wait.")
1168
1169 t.join()
1170 # Ensure that all of the thread results are as expected.
1171 # When a race condition occurs in wait(), the returncode could
1172 # be set by the wrong thread that doesn't actually have it
1173 # leading to an incorrect value.
1174 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001175 ('thread-after-kill-and-wait', expected_errorcode),
1176 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001177 results)
1178
Victor Stinnerb3693582010-05-21 20:13:12 +00001179 def test_issue8780(self):
1180 # Ensure that stdout is inherited from the parent
1181 # if stdout=PIPE is not used
1182 code = ';'.join((
1183 'import subprocess, sys',
1184 'retcode = subprocess.call('
1185 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1186 'assert retcode == 0'))
1187 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001188 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001189
Tim Goldenaf5ac392010-08-06 13:03:56 +00001190 def test_handles_closed_on_exception(self):
1191 # If CreateProcess exits with an error, ensure the
1192 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001193 ifhandle, ifname = tempfile.mkstemp()
1194 ofhandle, ofname = tempfile.mkstemp()
1195 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001196 try:
1197 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1198 stderr=efhandle)
1199 except OSError:
1200 os.close(ifhandle)
1201 os.remove(ifname)
1202 os.close(ofhandle)
1203 os.remove(ofname)
1204 os.close(efhandle)
1205 os.remove(efname)
1206 self.assertFalse(os.path.exists(ifname))
1207 self.assertFalse(os.path.exists(ofname))
1208 self.assertFalse(os.path.exists(efname))
1209
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001210 def test_communicate_epipe(self):
1211 # Issue 10963: communicate() should hide EPIPE
1212 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1213 stdin=subprocess.PIPE,
1214 stdout=subprocess.PIPE,
1215 stderr=subprocess.PIPE)
1216 self.addCleanup(p.stdout.close)
1217 self.addCleanup(p.stderr.close)
1218 self.addCleanup(p.stdin.close)
1219 p.communicate(b"x" * 2**20)
1220
1221 def test_communicate_epipe_only_stdin(self):
1222 # Issue 10963: communicate() should hide EPIPE
1223 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1224 stdin=subprocess.PIPE)
1225 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001226 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001227 p.communicate(b"x" * 2**20)
1228
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001229 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1230 "Requires signal.SIGUSR1")
1231 @unittest.skipUnless(hasattr(os, 'kill'),
1232 "Requires os.kill")
1233 @unittest.skipUnless(hasattr(os, 'getppid'),
1234 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001235 def test_communicate_eintr(self):
1236 # Issue #12493: communicate() should handle EINTR
1237 def handler(signum, frame):
1238 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001239 old_handler = signal.signal(signal.SIGUSR1, handler)
1240 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001241
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001242 args = [sys.executable, "-c",
1243 'import os, signal;'
1244 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001245 for stream in ('stdout', 'stderr'):
1246 kw = {stream: subprocess.PIPE}
1247 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001248 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001249 process.communicate()
1250
Tim Peterse718f612004-10-12 21:51:32 +00001251
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001252 # This test is Linux-ish specific for simplicity to at least have
1253 # some coverage. It is not a platform specific bug.
1254 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1255 "Linux specific")
1256 def test_failed_child_execute_fd_leak(self):
1257 """Test for the fork() failure fd leak reported in issue16327."""
1258 fd_directory = '/proc/%d/fd' % os.getpid()
1259 fds_before_popen = os.listdir(fd_directory)
1260 with self.assertRaises(PopenTestException):
1261 PopenExecuteChildRaises(
1262 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
1263 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1264
1265 # NOTE: This test doesn't verify that the real _execute_child
1266 # does not close the file descriptors itself on the way out
1267 # during an exception. Code inspection has confirmed that.
1268
1269 fds_after_exception = os.listdir(fd_directory)
1270 self.assertEqual(fds_before_popen, fds_after_exception)
1271
Gregory P. Smith6e730002015-04-14 16:14:25 -07001272
1273class RunFuncTestCase(BaseTestCase):
1274 def run_python(self, code, **kwargs):
1275 """Run Python code in a subprocess using subprocess.run"""
1276 argv = [sys.executable, "-c", code]
1277 return subprocess.run(argv, **kwargs)
1278
1279 def test_returncode(self):
1280 # call() function with sequence argument
1281 cp = self.run_python("import sys; sys.exit(47)")
1282 self.assertEqual(cp.returncode, 47)
1283 with self.assertRaises(subprocess.CalledProcessError):
1284 cp.check_returncode()
1285
1286 def test_check(self):
1287 with self.assertRaises(subprocess.CalledProcessError) as c:
1288 self.run_python("import sys; sys.exit(47)", check=True)
1289 self.assertEqual(c.exception.returncode, 47)
1290
1291 def test_check_zero(self):
1292 # check_returncode shouldn't raise when returncode is zero
1293 cp = self.run_python("import sys; sys.exit(0)", check=True)
1294 self.assertEqual(cp.returncode, 0)
1295
1296 def test_timeout(self):
1297 # run() function with timeout argument; we want to test that the child
1298 # process gets killed when the timeout expires. If the child isn't
1299 # killed, this call will deadlock since subprocess.run waits for the
1300 # child.
1301 with self.assertRaises(subprocess.TimeoutExpired):
1302 self.run_python("while True: pass", timeout=0.0001)
1303
1304 def test_capture_stdout(self):
1305 # capture stdout with zero return code
1306 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1307 self.assertIn(b'BDFL', cp.stdout)
1308
1309 def test_capture_stderr(self):
1310 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1311 stderr=subprocess.PIPE)
1312 self.assertIn(b'BDFL', cp.stderr)
1313
1314 def test_check_output_stdin_arg(self):
1315 # run() can be called with stdin set to a file
1316 tf = tempfile.TemporaryFile()
1317 self.addCleanup(tf.close)
1318 tf.write(b'pear')
1319 tf.seek(0)
1320 cp = self.run_python(
1321 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1322 stdin=tf, stdout=subprocess.PIPE)
1323 self.assertIn(b'PEAR', cp.stdout)
1324
1325 def test_check_output_input_arg(self):
1326 # check_output() can be called with input set to a string
1327 cp = self.run_python(
1328 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1329 input=b'pear', stdout=subprocess.PIPE)
1330 self.assertIn(b'PEAR', cp.stdout)
1331
1332 def test_check_output_stdin_with_input_arg(self):
1333 # run() refuses to accept 'stdin' with 'input'
1334 tf = tempfile.TemporaryFile()
1335 self.addCleanup(tf.close)
1336 tf.write(b'pear')
1337 tf.seek(0)
1338 with self.assertRaises(ValueError,
1339 msg="Expected ValueError when stdin and input args supplied.") as c:
1340 output = self.run_python("print('will not be run')",
1341 stdin=tf, input=b'hare')
1342 self.assertIn('stdin', c.exception.args[0])
1343 self.assertIn('input', c.exception.args[0])
1344
1345 def test_check_output_timeout(self):
1346 with self.assertRaises(subprocess.TimeoutExpired) as c:
1347 cp = self.run_python((
1348 "import sys, time\n"
1349 "sys.stdout.write('BDFL')\n"
1350 "sys.stdout.flush()\n"
1351 "time.sleep(3600)"),
1352 # Some heavily loaded buildbots (sparc Debian 3.x) require
1353 # this much time to start and print.
1354 timeout=3, stdout=subprocess.PIPE)
1355 self.assertEqual(c.exception.output, b'BDFL')
1356 # output is aliased to stdout
1357 self.assertEqual(c.exception.stdout, b'BDFL')
1358
1359 def test_run_kwargs(self):
1360 newenv = os.environ.copy()
1361 newenv["FRUIT"] = "banana"
1362 cp = self.run_python(('import sys, os;'
1363 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1364 env=newenv)
1365 self.assertEqual(cp.returncode, 33)
1366
1367
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001368@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001369class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001370
Gregory P. Smith5591b022012-10-10 03:34:47 -07001371 def setUp(self):
1372 super().setUp()
1373 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1374
1375 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001376 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001377 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001378 except OSError as e:
1379 # This avoids hard coding the errno value or the OS perror()
1380 # string and instead capture the exception that we want to see
1381 # below for comparison.
1382 desired_exception = e
Gregory P. Smith5591b022012-10-10 03:34:47 -07001383 desired_exception.strerror += ': ' + repr(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001384 else:
Martin Pantereb995702016-07-28 01:11:04 +00001385 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001386 self._nonexistent_dir)
1387 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001388
Gregory P. Smith5591b022012-10-10 03:34:47 -07001389 def test_exception_cwd(self):
1390 """Test error in the child raised in the parent for a bad cwd."""
1391 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001392 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001393 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001394 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001395 except OSError as e:
1396 # Test that the child process chdir failure actually makes
1397 # it up to the parent process as the correct exception.
1398 self.assertEqual(desired_exception.errno, e.errno)
1399 self.assertEqual(desired_exception.strerror, e.strerror)
1400 else:
1401 self.fail("Expected OSError: %s" % desired_exception)
1402
Gregory P. Smith5591b022012-10-10 03:34:47 -07001403 def test_exception_bad_executable(self):
1404 """Test error in the child raised in the parent for a bad executable."""
1405 desired_exception = self._get_chdir_exception()
1406 try:
1407 p = subprocess.Popen([sys.executable, "-c", ""],
1408 executable=self._nonexistent_dir)
1409 except OSError as e:
1410 # Test that the child process exec failure actually makes
1411 # it up to the parent process as the correct exception.
1412 self.assertEqual(desired_exception.errno, e.errno)
1413 self.assertEqual(desired_exception.strerror, e.strerror)
1414 else:
1415 self.fail("Expected OSError: %s" % desired_exception)
1416
1417 def test_exception_bad_args_0(self):
1418 """Test error in the child raised in the parent for a bad args[0]."""
1419 desired_exception = self._get_chdir_exception()
1420 try:
1421 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1422 except OSError as e:
1423 # Test that the child process exec failure actually makes
1424 # it up to the parent process as the correct exception.
1425 self.assertEqual(desired_exception.errno, e.errno)
1426 self.assertEqual(desired_exception.strerror, e.strerror)
1427 else:
1428 self.fail("Expected OSError: %s" % desired_exception)
1429
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001430 def test_restore_signals(self):
1431 # Code coverage for both values of restore_signals to make sure it
1432 # at least does not blow up.
1433 # A test for behavior would be complex. Contributions welcome.
1434 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1435 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1436
1437 def test_start_new_session(self):
1438 # For code coverage of calling setsid(). We don't care if we get an
1439 # EPERM error from it depending on the test execution environment, that
1440 # still indicates that it was called.
1441 try:
1442 output = subprocess.check_output(
1443 [sys.executable, "-c",
1444 "import os; print(os.getpgid(os.getpid()))"],
1445 start_new_session=True)
1446 except OSError as e:
1447 if e.errno != errno.EPERM:
1448 raise
1449 else:
1450 parent_pgid = os.getpgid(os.getpid())
1451 child_pgid = int(output)
1452 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001453
1454 def test_run_abort(self):
1455 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001456 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001457 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001458 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001459 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001460 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001461
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001462 def test_CalledProcessError_str_signal(self):
1463 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
1464 error_string = str(err)
1465 # We're relying on the repr() of the signal.Signals intenum to provide
1466 # the word signal, the signal name and the numeric value.
1467 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00001468 # We're not being specific about the signal name as some signals have
1469 # multiple names and which name is revealed can vary.
1470 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001471 self.assertIn(str(signal.SIGABRT), error_string)
1472
1473 def test_CalledProcessError_str_unknown_signal(self):
1474 err = subprocess.CalledProcessError(-9876543, "fake cmd")
1475 error_string = str(err)
1476 self.assertIn("unknown signal 9876543.", error_string)
1477
1478 def test_CalledProcessError_str_non_zero(self):
1479 err = subprocess.CalledProcessError(2, "fake cmd")
1480 error_string = str(err)
1481 self.assertIn("non-zero exit status 2.", error_string)
1482
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001483 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001484 # DISCLAIMER: Setting environment variables is *not* a good use
1485 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001486 p = subprocess.Popen([sys.executable, "-c",
1487 'import sys,os;'
1488 'sys.stdout.write(os.getenv("FRUIT"))'],
1489 stdout=subprocess.PIPE,
1490 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02001491 with p:
1492 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001493
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001494 def test_preexec_exception(self):
1495 def raise_it():
1496 raise ValueError("What if two swallows carried a coconut?")
1497 try:
1498 p = subprocess.Popen([sys.executable, "-c", ""],
1499 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001500 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001501 self.assertTrue(
1502 subprocess._posixsubprocess,
1503 "Expected a ValueError from the preexec_fn")
1504 except ValueError as e:
1505 self.assertIn("coconut", e.args[0])
1506 else:
1507 self.fail("Exception raised by preexec_fn did not make it "
1508 "to the parent process.")
1509
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001510 class _TestExecuteChildPopen(subprocess.Popen):
1511 """Used to test behavior at the end of _execute_child."""
1512 def __init__(self, testcase, *args, **kwargs):
1513 self._testcase = testcase
1514 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001515
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001516 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001517 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001518 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001519 finally:
1520 # Open a bunch of file descriptors and verify that
1521 # none of them are the same as the ones the Popen
1522 # instance is using for stdin/stdout/stderr.
1523 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1524 for _ in range(8)]
1525 try:
1526 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001527 self._testcase.assertNotIn(
1528 fd, (self.stdin.fileno(), self.stdout.fileno(),
1529 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001530 msg="At least one fd was closed early.")
1531 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01001532 for fd in devzero_fds:
1533 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001534
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001535 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1536 def test_preexec_errpipe_does_not_double_close_pipes(self):
1537 """Issue16140: Don't double close pipes on preexec error."""
1538
1539 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08001540 raise subprocess.SubprocessError(
1541 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001542
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08001543 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001544 self._TestExecuteChildPopen(
1545 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001546 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1547 stderr=subprocess.PIPE, preexec_fn=raise_it)
1548
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001549 def test_preexec_gc_module_failure(self):
1550 # This tests the code that disables garbage collection if the child
1551 # process will execute any Python.
1552 def raise_runtime_error():
1553 raise RuntimeError("this shouldn't escape")
1554 enabled = gc.isenabled()
1555 orig_gc_disable = gc.disable
1556 orig_gc_isenabled = gc.isenabled
1557 try:
1558 gc.disable()
1559 self.assertFalse(gc.isenabled())
1560 subprocess.call([sys.executable, '-c', ''],
1561 preexec_fn=lambda: None)
1562 self.assertFalse(gc.isenabled(),
1563 "Popen enabled gc when it shouldn't.")
1564
1565 gc.enable()
1566 self.assertTrue(gc.isenabled())
1567 subprocess.call([sys.executable, '-c', ''],
1568 preexec_fn=lambda: None)
1569 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1570
1571 gc.disable = raise_runtime_error
1572 self.assertRaises(RuntimeError, subprocess.Popen,
1573 [sys.executable, '-c', ''],
1574 preexec_fn=lambda: None)
1575
1576 del gc.isenabled # force an AttributeError
1577 self.assertRaises(AttributeError, subprocess.Popen,
1578 [sys.executable, '-c', ''],
1579 preexec_fn=lambda: None)
1580 finally:
1581 gc.disable = orig_gc_disable
1582 gc.isenabled = orig_gc_isenabled
1583 if not enabled:
1584 gc.disable()
1585
Martin Panterf7fdbda2015-12-05 09:51:52 +00001586 @unittest.skipIf(
1587 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00001588 def test_preexec_fork_failure(self):
1589 # The internal code did not preserve the previous exception when
1590 # re-enabling garbage collection
1591 try:
1592 from resource import getrlimit, setrlimit, RLIMIT_NPROC
1593 except ImportError as err:
1594 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
1595 limits = getrlimit(RLIMIT_NPROC)
1596 [_, hard] = limits
1597 setrlimit(RLIMIT_NPROC, (0, hard))
1598 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00001599 try:
Martin Panterafdd5132015-11-30 02:21:41 +00001600 subprocess.call([sys.executable, '-c', ''],
1601 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00001602 except BlockingIOError:
1603 # Forking should raise EAGAIN, translated to BlockingIOError
1604 pass
1605 else:
1606 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00001607
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001608 def test_args_string(self):
1609 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03001610 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001611 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001612 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001613 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001614 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1615 sys.executable)
1616 os.chmod(fname, 0o700)
1617 p = subprocess.Popen(fname)
1618 p.wait()
1619 os.remove(fname)
1620 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001621
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001622 def test_invalid_args(self):
1623 # invalid arguments should raise ValueError
1624 self.assertRaises(ValueError, subprocess.call,
1625 [sys.executable, "-c",
1626 "import sys; sys.exit(47)"],
1627 startupinfo=47)
1628 self.assertRaises(ValueError, subprocess.call,
1629 [sys.executable, "-c",
1630 "import sys; sys.exit(47)"],
1631 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001632
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001633 def test_shell_sequence(self):
1634 # Run command through the shell (sequence)
1635 newenv = os.environ.copy()
1636 newenv["FRUIT"] = "apple"
1637 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1638 stdout=subprocess.PIPE,
1639 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001640 with p:
1641 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001642
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001643 def test_shell_string(self):
1644 # Run command through the shell (string)
1645 newenv = os.environ.copy()
1646 newenv["FRUIT"] = "apple"
1647 p = subprocess.Popen("echo $FRUIT", shell=1,
1648 stdout=subprocess.PIPE,
1649 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001650 with p:
1651 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001652
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001653 def test_call_string(self):
1654 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03001655 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001656 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001657 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001658 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001659 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1660 sys.executable)
1661 os.chmod(fname, 0o700)
1662 rc = subprocess.call(fname)
1663 os.remove(fname)
1664 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001665
Stefan Krah9542cc62010-07-19 14:20:53 +00001666 def test_specific_shell(self):
1667 # Issue #9265: Incorrect name passed as arg[0].
1668 shells = []
1669 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1670 for name in ['bash', 'ksh']:
1671 sh = os.path.join(prefix, name)
1672 if os.path.isfile(sh):
1673 shells.append(sh)
1674 if not shells: # Will probably work for any shell but csh.
1675 self.skipTest("bash or ksh required for this test")
1676 sh = '/bin/sh'
1677 if os.path.isfile(sh) and not os.path.islink(sh):
1678 # Test will fail if /bin/sh is a symlink to csh.
1679 shells.append(sh)
1680 for sh in shells:
1681 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1682 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02001683 with p:
1684 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00001685
Florent Xicluna4886d242010-03-08 13:27:26 +00001686 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001687 # Do not inherit file handles from the parent.
1688 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07001689 # Also set the SIGINT handler to the default to make sure it's not
1690 # being ignored (some tests rely on that.)
1691 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
1692 try:
1693 p = subprocess.Popen([sys.executable, "-c", """if 1:
1694 import sys, time
1695 sys.stdout.write('x\\n')
1696 sys.stdout.flush()
1697 time.sleep(30)
1698 """],
1699 close_fds=True,
1700 stdin=subprocess.PIPE,
1701 stdout=subprocess.PIPE,
1702 stderr=subprocess.PIPE)
1703 finally:
1704 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001705 # Wait for the interpreter to be completely initialized before
1706 # sending any signal.
1707 p.stdout.read(1)
1708 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001709 return p
1710
Charles-François Natali53221e32013-01-12 16:52:20 +01001711 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1712 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001713 def _kill_dead_process(self, method, *args):
1714 # Do not inherit file handles from the parent.
1715 # It should fix failures on some platforms.
1716 p = subprocess.Popen([sys.executable, "-c", """if 1:
1717 import sys, time
1718 sys.stdout.write('x\\n')
1719 sys.stdout.flush()
1720 """],
1721 close_fds=True,
1722 stdin=subprocess.PIPE,
1723 stdout=subprocess.PIPE,
1724 stderr=subprocess.PIPE)
1725 # Wait for the interpreter to be completely initialized before
1726 # sending any signal.
1727 p.stdout.read(1)
1728 # The process should end after this
1729 time.sleep(1)
1730 # This shouldn't raise even though the child is now dead
1731 getattr(p, method)(*args)
1732 p.communicate()
1733
Florent Xicluna4886d242010-03-08 13:27:26 +00001734 def test_send_signal(self):
1735 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001736 _, stderr = p.communicate()
1737 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001738 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001739
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001740 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001741 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001742 _, stderr = p.communicate()
1743 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001744 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001745
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001746 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001747 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001748 _, stderr = p.communicate()
1749 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001750 self.assertEqual(p.wait(), -signal.SIGTERM)
1751
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001752 def test_send_signal_dead(self):
1753 # Sending a signal to a dead process
1754 self._kill_dead_process('send_signal', signal.SIGINT)
1755
1756 def test_kill_dead(self):
1757 # Killing a dead process
1758 self._kill_dead_process('kill')
1759
1760 def test_terminate_dead(self):
1761 # Terminating a dead process
1762 self._kill_dead_process('terminate')
1763
Victor Stinnerdaf45552013-08-28 00:53:59 +02001764 def _save_fds(self, save_fds):
1765 fds = []
1766 for fd in save_fds:
1767 inheritable = os.get_inheritable(fd)
1768 saved = os.dup(fd)
1769 fds.append((fd, saved, inheritable))
1770 return fds
1771
1772 def _restore_fds(self, fds):
1773 for fd, saved, inheritable in fds:
1774 os.dup2(saved, fd, inheritable=inheritable)
1775 os.close(saved)
1776
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001777 def check_close_std_fds(self, fds):
1778 # Issue #9905: test that subprocess pipes still work properly with
1779 # some standard fds closed
1780 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02001781 saved_fds = self._save_fds(fds)
1782 for fd, saved, inheritable in saved_fds:
1783 if fd == 0:
1784 stdin = saved
1785 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001786 try:
1787 for fd in fds:
1788 os.close(fd)
1789 out, err = subprocess.Popen([sys.executable, "-c",
1790 'import sys;'
1791 'sys.stdout.write("apple");'
1792 'sys.stdout.flush();'
1793 'sys.stderr.write("orange")'],
1794 stdin=stdin,
1795 stdout=subprocess.PIPE,
1796 stderr=subprocess.PIPE).communicate()
1797 err = support.strip_python_stderr(err)
1798 self.assertEqual((out, err), (b'apple', b'orange'))
1799 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001800 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001801
1802 def test_close_fd_0(self):
1803 self.check_close_std_fds([0])
1804
1805 def test_close_fd_1(self):
1806 self.check_close_std_fds([1])
1807
1808 def test_close_fd_2(self):
1809 self.check_close_std_fds([2])
1810
1811 def test_close_fds_0_1(self):
1812 self.check_close_std_fds([0, 1])
1813
1814 def test_close_fds_0_2(self):
1815 self.check_close_std_fds([0, 2])
1816
1817 def test_close_fds_1_2(self):
1818 self.check_close_std_fds([1, 2])
1819
1820 def test_close_fds_0_1_2(self):
1821 # Issue #10806: test that subprocess pipes still work properly with
1822 # all standard fds closed.
1823 self.check_close_std_fds([0, 1, 2])
1824
Gregory P. Smith53dd8162013-12-01 16:03:24 -08001825 def test_small_errpipe_write_fd(self):
1826 """Issue #15798: Popen should work when stdio fds are available."""
1827 new_stdin = os.dup(0)
1828 new_stdout = os.dup(1)
1829 try:
1830 os.close(0)
1831 os.close(1)
1832
1833 # Side test: if errpipe_write fails to have its CLOEXEC
1834 # flag set this should cause the parent to think the exec
1835 # failed. Extremely unlikely: everyone supports CLOEXEC.
1836 subprocess.Popen([
1837 sys.executable, "-c",
1838 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
1839 finally:
1840 # Restore original stdin and stdout
1841 os.dup2(new_stdin, 0)
1842 os.dup2(new_stdout, 1)
1843 os.close(new_stdin)
1844 os.close(new_stdout)
1845
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001846 def test_remapping_std_fds(self):
1847 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03001848 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001849 try:
1850 temp_fds = [fd for fd, fname in temps]
1851
1852 # unlink the files -- we won't need to reopen them
1853 for fd, fname in temps:
1854 os.unlink(fname)
1855
1856 # write some data to what will become stdin, and rewind
1857 os.write(temp_fds[1], b"STDIN")
1858 os.lseek(temp_fds[1], 0, 0)
1859
1860 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02001861 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001862 try:
1863 # duplicate the file objects over the standard fd's
1864 for fd, temp_fd in enumerate(temp_fds):
1865 os.dup2(temp_fd, fd)
1866
1867 # now use those files in the "wrong" order, so that subprocess
1868 # has to rearrange them in the child
1869 p = subprocess.Popen([sys.executable, "-c",
1870 'import sys; got = sys.stdin.read();'
1871 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1872 stdin=temp_fds[1],
1873 stdout=temp_fds[2],
1874 stderr=temp_fds[0])
1875 p.wait()
1876 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001877 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001878
1879 for fd in temp_fds:
1880 os.lseek(fd, 0, 0)
1881
1882 out = os.read(temp_fds[2], 1024)
1883 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1884 self.assertEqual(out, b"got STDIN")
1885 self.assertEqual(err, b"err")
1886
1887 finally:
1888 for fd in temp_fds:
1889 os.close(fd)
1890
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001891 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1892 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03001893 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001894 temp_fds = [fd for fd, fname in temps]
1895 try:
1896 # unlink the files -- we won't need to reopen them
1897 for fd, fname in temps:
1898 os.unlink(fname)
1899
1900 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02001901 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001902 try:
1903 # duplicate the temp files over the standard fd's 0, 1, 2
1904 for fd, temp_fd in enumerate(temp_fds):
1905 os.dup2(temp_fd, fd)
1906
1907 # write some data to what will become stdin, and rewind
1908 os.write(stdin_no, b"STDIN")
1909 os.lseek(stdin_no, 0, 0)
1910
1911 # now use those files in the given order, so that subprocess
1912 # has to rearrange them in the child
1913 p = subprocess.Popen([sys.executable, "-c",
1914 'import sys; got = sys.stdin.read();'
1915 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1916 stdin=stdin_no,
1917 stdout=stdout_no,
1918 stderr=stderr_no)
1919 p.wait()
1920
1921 for fd in temp_fds:
1922 os.lseek(fd, 0, 0)
1923
1924 out = os.read(stdout_no, 1024)
1925 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1926 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001927 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001928
1929 self.assertEqual(out, b"got STDIN")
1930 self.assertEqual(err, b"err")
1931
1932 finally:
1933 for fd in temp_fds:
1934 os.close(fd)
1935
1936 # When duping fds, if there arises a situation where one of the fds is
1937 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1938 # This tests all combinations of this.
1939 def test_swap_fds(self):
1940 self.check_swap_fds(0, 1, 2)
1941 self.check_swap_fds(0, 2, 1)
1942 self.check_swap_fds(1, 0, 2)
1943 self.check_swap_fds(1, 2, 0)
1944 self.check_swap_fds(2, 0, 1)
1945 self.check_swap_fds(2, 1, 0)
1946
Victor Stinner13bb71c2010-04-23 21:41:56 +00001947 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001948 def prepare():
1949 raise ValueError("surrogate:\uDCff")
1950
1951 try:
1952 subprocess.call(
1953 [sys.executable, "-c", "pass"],
1954 preexec_fn=prepare)
1955 except ValueError as err:
1956 # Pure Python implementations keeps the message
1957 self.assertIsNone(subprocess._posixsubprocess)
1958 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001959 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00001960 # _posixsubprocess uses a default message
1961 self.assertIsNotNone(subprocess._posixsubprocess)
1962 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1963 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001964 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00001965
Victor Stinner13bb71c2010-04-23 21:41:56 +00001966 def test_undecodable_env(self):
1967 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01001968 encoded_value = value.encode("ascii", "surrogateescape")
1969
Victor Stinner13bb71c2010-04-23 21:41:56 +00001970 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001971 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001972 env = os.environ.copy()
1973 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01001974 # Use C locale to get ASCII for the locale encoding to force
Victor Stinner89f3ad12010-10-14 10:43:31 +00001975 # surrogate-escaping of \xFF in the child process; otherwise it can
1976 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001977 env['LC_ALL'] = 'C'
Victor Stinner5323fb02013-11-19 23:46:06 +01001978 if sys.platform.startswith("aix"):
1979 # On AIX, the C locale uses the Latin1 encoding
1980 decoded_value = encoded_value.decode("latin1", "surrogateescape")
1981 else:
1982 # On other UNIXes, the C locale uses the ASCII encoding
1983 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001984 stdout = subprocess.check_output(
1985 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001986 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001987 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01001988 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001989
1990 # test bytes
1991 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001992 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001993 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01001994 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001995 stdout = subprocess.check_output(
1996 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001997 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001998 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01001999 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002000
Victor Stinnerb745a742010-05-18 17:17:23 +00002001 def test_bytes_program(self):
2002 abs_program = os.fsencode(sys.executable)
2003 path, program = os.path.split(sys.executable)
2004 program = os.fsencode(program)
2005
2006 # absolute bytes path
2007 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00002008 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002009
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002010 # absolute bytes path as a string
2011 cmd = b"'" + abs_program + b"' -c pass"
2012 exitcode = subprocess.call(cmd, shell=True)
2013 self.assertEqual(exitcode, 0)
2014
Victor Stinnerb745a742010-05-18 17:17:23 +00002015 # bytes program, unicode PATH
2016 env = os.environ.copy()
2017 env["PATH"] = path
2018 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002019 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002020
2021 # bytes program, bytes PATH
2022 envb = os.environb.copy()
2023 envb[b"PATH"] = os.fsencode(path)
2024 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002025 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002026
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002027 def test_pipe_cloexec(self):
2028 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2029 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2030
2031 p1 = subprocess.Popen([sys.executable, sleeper],
2032 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2033 stderr=subprocess.PIPE, close_fds=False)
2034
2035 self.addCleanup(p1.communicate, b'')
2036
2037 p2 = subprocess.Popen([sys.executable, fd_status],
2038 stdout=subprocess.PIPE, close_fds=False)
2039
2040 output, error = p2.communicate()
2041 result_fds = set(map(int, output.split(b',')))
2042 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2043 p1.stderr.fileno()])
2044
2045 self.assertFalse(result_fds & unwanted_fds,
2046 "Expected no fds from %r to be open in child, "
2047 "found %r" %
2048 (unwanted_fds, result_fds & unwanted_fds))
2049
2050 def test_pipe_cloexec_real_tools(self):
2051 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2052 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2053
2054 subdata = b'zxcvbn'
2055 data = subdata * 4 + b'\n'
2056
2057 p1 = subprocess.Popen([sys.executable, qcat],
2058 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2059 close_fds=False)
2060
2061 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2062 stdin=p1.stdout, stdout=subprocess.PIPE,
2063 close_fds=False)
2064
2065 self.addCleanup(p1.wait)
2066 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002067 def kill_p1():
2068 try:
2069 p1.terminate()
2070 except ProcessLookupError:
2071 pass
2072 def kill_p2():
2073 try:
2074 p2.terminate()
2075 except ProcessLookupError:
2076 pass
2077 self.addCleanup(kill_p1)
2078 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002079
2080 p1.stdin.write(data)
2081 p1.stdin.close()
2082
2083 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2084
2085 self.assertTrue(readfiles, "The child hung")
2086 self.assertEqual(p2.stdout.read(), data)
2087
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002088 p1.stdout.close()
2089 p2.stdout.close()
2090
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002091 def test_close_fds(self):
2092 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2093
2094 fds = os.pipe()
2095 self.addCleanup(os.close, fds[0])
2096 self.addCleanup(os.close, fds[1])
2097
2098 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002099 # add a bunch more fds
2100 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002101 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002102 self.addCleanup(os.close, fd)
2103 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002104
Victor Stinnerdaf45552013-08-28 00:53:59 +02002105 for fd in open_fds:
2106 os.set_inheritable(fd, True)
2107
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002108 p = subprocess.Popen([sys.executable, fd_status],
2109 stdout=subprocess.PIPE, close_fds=False)
2110 output, ignored = p.communicate()
2111 remaining_fds = set(map(int, output.split(b',')))
2112
2113 self.assertEqual(remaining_fds & open_fds, open_fds,
2114 "Some fds were closed")
2115
2116 p = subprocess.Popen([sys.executable, fd_status],
2117 stdout=subprocess.PIPE, close_fds=True)
2118 output, ignored = p.communicate()
2119 remaining_fds = set(map(int, output.split(b',')))
2120
2121 self.assertFalse(remaining_fds & open_fds,
2122 "Some fds were left open")
2123 self.assertIn(1, remaining_fds, "Subprocess failed")
2124
Gregory P. Smith8facece2012-01-21 14:01:08 -08002125 # Keep some of the fd's we opened open in the subprocess.
2126 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2127 fds_to_keep = set(open_fds.pop() for _ in range(8))
2128 p = subprocess.Popen([sys.executable, fd_status],
2129 stdout=subprocess.PIPE, close_fds=True,
2130 pass_fds=())
2131 output, ignored = p.communicate()
2132 remaining_fds = set(map(int, output.split(b',')))
2133
2134 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
2135 "Some fds not in pass_fds were left open")
2136 self.assertIn(1, remaining_fds, "Subprocess failed")
2137
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002138
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002139 @unittest.skipIf(sys.platform.startswith("freebsd") and
2140 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2141 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002142 def test_close_fds_when_max_fd_is_lowered(self):
2143 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2144 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2145
Gregory P. Smith634aa682014-06-15 17:51:04 -07002146 # This launches the meat of the test in a child process to
2147 # avoid messing with the larger unittest processes maximum
2148 # number of file descriptors.
2149 # This process launches:
2150 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2151 # a bunch of high open fds above the new lower rlimit.
2152 # Those are reported via stdout before launching a new
2153 # process with close_fds=False to run the actual test:
2154 # +--> The TEST: This one launches a fd_status.py
2155 # subprocess with close_fds=True so we can find out if
2156 # any of the fds above the lowered rlimit are still open.
2157 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2158 '''
2159 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002160 open_fds = set()
2161 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002162 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002163 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002164 open_fds.add(fd)
2165
2166 # Leave a two pairs of low ones available for use by the
2167 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002168 # We also leave 10 more open as some Python buildbots run into
2169 # "too many open files" errors during the test if we do not.
2170 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002171 os.close(fd)
2172 open_fds.remove(fd)
2173
2174 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002175 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002176 os.set_inheritable(fd, True)
2177
2178 max_fd_open = max(open_fds)
2179
Gregory P. Smith634aa682014-06-15 17:51:04 -07002180 # Communicate the open_fds to the parent unittest.TestCase process.
2181 print(','.join(map(str, sorted(open_fds))))
2182 sys.stdout.flush()
2183
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002184 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2185 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002186 # 29 is lower than the highest fds we are leaving open.
2187 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002188 # Launch a new Python interpreter with our low fd rlim_cur that
2189 # inherits open fds above that limit. It then uses subprocess
2190 # with close_fds=True to get a report of open fds in the child.
2191 # An explicit list of fds to check is passed to fd_status.py as
2192 # letting fd_status rely on its default logic would miss the
2193 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002194 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002195 [sys.executable, '-c',
2196 textwrap.dedent("""
2197 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002198 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002199 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002200 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002201 """.format(max_fd=max_fd_open+1))],
2202 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002203 finally:
2204 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002205 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002206
2207 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002208 output_lines = output.splitlines()
2209 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002210 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002211 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2212 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002213
Gregory P. Smith634aa682014-06-15 17:51:04 -07002214 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002215 msg="Some fds were left open.")
2216
2217
Victor Stinner88701e22011-06-01 13:13:04 +02002218 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2219 # descriptor of a pipe closed in the parent process is valid in the
2220 # child process according to fstat(), but the mode of the file
2221 # descriptor is invalid, and read or write raise an error.
2222 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002223 def test_pass_fds(self):
2224 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2225
2226 open_fds = set()
2227
2228 for x in range(5):
2229 fds = os.pipe()
2230 self.addCleanup(os.close, fds[0])
2231 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002232 os.set_inheritable(fds[0], True)
2233 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002234 open_fds.update(fds)
2235
2236 for fd in open_fds:
2237 p = subprocess.Popen([sys.executable, fd_status],
2238 stdout=subprocess.PIPE, close_fds=True,
2239 pass_fds=(fd, ))
2240 output, ignored = p.communicate()
2241
2242 remaining_fds = set(map(int, output.split(b',')))
2243 to_be_closed = open_fds - {fd}
2244
2245 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2246 self.assertFalse(remaining_fds & to_be_closed,
2247 "fd to be closed passed")
2248
2249 # pass_fds overrides close_fds with a warning.
2250 with self.assertWarns(RuntimeWarning) as context:
2251 self.assertFalse(subprocess.call(
2252 [sys.executable, "-c", "import sys; sys.exit(0)"],
2253 close_fds=False, pass_fds=(fd, )))
2254 self.assertIn('overriding close_fds', str(context.warning))
2255
Victor Stinnerdaf45552013-08-28 00:53:59 +02002256 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002257 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002258
2259 inheritable, non_inheritable = os.pipe()
2260 self.addCleanup(os.close, inheritable)
2261 self.addCleanup(os.close, non_inheritable)
2262 os.set_inheritable(inheritable, True)
2263 os.set_inheritable(non_inheritable, False)
2264 pass_fds = (inheritable, non_inheritable)
2265 args = [sys.executable, script]
2266 args += list(map(str, pass_fds))
2267
2268 p = subprocess.Popen(args,
2269 stdout=subprocess.PIPE, close_fds=True,
2270 pass_fds=pass_fds)
2271 output, ignored = p.communicate()
2272 fds = set(map(int, output.split(b',')))
2273
2274 # the inheritable file descriptor must be inherited, so its inheritable
2275 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002276 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002277
2278 # inheritable flag must not be changed in the parent process
2279 self.assertEqual(os.get_inheritable(inheritable), True)
2280 self.assertEqual(os.get_inheritable(non_inheritable), False)
2281
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002282 def test_stdout_stdin_are_single_inout_fd(self):
2283 with io.open(os.devnull, "r+") as inout:
2284 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2285 stdout=inout, stdin=inout)
2286 p.wait()
2287
2288 def test_stdout_stderr_are_single_inout_fd(self):
2289 with io.open(os.devnull, "r+") as inout:
2290 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2291 stdout=inout, stderr=inout)
2292 p.wait()
2293
2294 def test_stderr_stdin_are_single_inout_fd(self):
2295 with io.open(os.devnull, "r+") as inout:
2296 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2297 stderr=inout, stdin=inout)
2298 p.wait()
2299
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002300 def test_wait_when_sigchild_ignored(self):
2301 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2302 sigchild_ignore = support.findfile("sigchild_ignore.py",
2303 subdir="subprocessdata")
2304 p = subprocess.Popen([sys.executable, sigchild_ignore],
2305 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2306 stdout, stderr = p.communicate()
2307 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002308 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002309 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002310
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002311 def test_select_unbuffered(self):
2312 # Issue #11459: bufsize=0 should really set the pipes as
2313 # unbuffered (and therefore let select() work properly).
2314 select = support.import_module("select")
2315 p = subprocess.Popen([sys.executable, "-c",
2316 'import sys;'
2317 'sys.stdout.write("apple")'],
2318 stdout=subprocess.PIPE,
2319 bufsize=0)
2320 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002321 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002322 try:
2323 self.assertEqual(f.read(4), b"appl")
2324 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2325 finally:
2326 p.wait()
2327
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002328 def test_zombie_fast_process_del(self):
2329 # Issue #12650: on Unix, if Popen.__del__() was called before the
2330 # process exited, it wouldn't be added to subprocess._active, and would
2331 # remain a zombie.
2332 # spawn a Popen, and delete its reference before it exits
2333 p = subprocess.Popen([sys.executable, "-c",
2334 'import sys, time;'
2335 'time.sleep(0.2)'],
2336 stdout=subprocess.PIPE,
2337 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002338 self.addCleanup(p.stdout.close)
2339 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002340 ident = id(p)
2341 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002342 with support.check_warnings(('', ResourceWarning)):
2343 p = None
2344
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002345 # check that p is in the active processes list
2346 self.assertIn(ident, [id(o) for o in subprocess._active])
2347
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002348 def test_leak_fast_process_del_killed(self):
2349 # Issue #12650: on Unix, if Popen.__del__() was called before the
2350 # process exited, and the process got killed by a signal, it would never
2351 # be removed from subprocess._active, which triggered a FD and memory
2352 # leak.
2353 # spawn a Popen, delete its reference and kill it
2354 p = subprocess.Popen([sys.executable, "-c",
2355 'import time;'
2356 'time.sleep(3)'],
2357 stdout=subprocess.PIPE,
2358 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002359 self.addCleanup(p.stdout.close)
2360 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002361 ident = id(p)
2362 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002363 with support.check_warnings(('', ResourceWarning)):
2364 p = None
2365
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002366 os.kill(pid, signal.SIGKILL)
2367 # check that p is in the active processes list
2368 self.assertIn(ident, [id(o) for o in subprocess._active])
2369
2370 # let some time for the process to exit, and create a new Popen: this
2371 # should trigger the wait() of p
2372 time.sleep(0.2)
Andrew Svetlov3438fa42012-12-17 23:35:18 +02002373 with self.assertRaises(OSError) as c:
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002374 with subprocess.Popen(['nonexisting_i_hope'],
2375 stdout=subprocess.PIPE,
2376 stderr=subprocess.PIPE) as proc:
2377 pass
2378 # p should have been wait()ed on, and removed from the _active list
2379 self.assertRaises(OSError, os.waitpid, pid, 0)
2380 self.assertNotIn(ident, [id(o) for o in subprocess._active])
2381
Charles-François Natali249cdc32013-08-25 18:24:45 +02002382 def test_close_fds_after_preexec(self):
2383 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2384
2385 # this FD is used as dup2() target by preexec_fn, and should be closed
2386 # in the child process
2387 fd = os.dup(1)
2388 self.addCleanup(os.close, fd)
2389
2390 p = subprocess.Popen([sys.executable, fd_status],
2391 stdout=subprocess.PIPE, close_fds=True,
2392 preexec_fn=lambda: os.dup2(1, fd))
2393 output, ignored = p.communicate()
2394
2395 remaining_fds = set(map(int, output.split(b',')))
2396
2397 self.assertNotIn(fd, remaining_fds)
2398
Victor Stinner8f437aa2014-10-05 17:25:19 +02002399 @support.cpython_only
2400 def test_fork_exec(self):
2401 # Issue #22290: fork_exec() must not crash on memory allocation failure
2402 # or other errors
2403 import _posixsubprocess
2404 gc_enabled = gc.isenabled()
2405 try:
2406 # Use a preexec function and enable the garbage collector
2407 # to force fork_exec() to re-enable the garbage collector
2408 # on error.
2409 func = lambda: None
2410 gc.enable()
2411
Victor Stinner8f437aa2014-10-05 17:25:19 +02002412 for args, exe_list, cwd, env_list in (
2413 (123, [b"exe"], None, [b"env"]),
2414 ([b"arg"], 123, None, [b"env"]),
2415 ([b"arg"], [b"exe"], 123, [b"env"]),
2416 ([b"arg"], [b"exe"], None, 123),
2417 ):
2418 with self.assertRaises(TypeError):
2419 _posixsubprocess.fork_exec(
2420 args, exe_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002421 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02002422 -1, -1, -1, -1,
2423 1, 2, 3, 4,
2424 True, True, func)
2425 finally:
2426 if not gc_enabled:
2427 gc.disable()
2428
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002429 @support.cpython_only
2430 def test_fork_exec_sorted_fd_sanity_check(self):
2431 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
2432 import _posixsubprocess
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002433 class BadInt:
2434 first = True
2435 def __init__(self, value):
2436 self.value = value
2437 def __int__(self):
2438 if self.first:
2439 self.first = False
2440 return self.value
2441 raise ValueError
2442
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002443 gc_enabled = gc.isenabled()
2444 try:
2445 gc.enable()
2446
2447 for fds_to_keep in (
2448 (-1, 2, 3, 4, 5), # Negative number.
2449 ('str', 4), # Not an int.
2450 (18, 23, 42, 2**63), # Out of range.
2451 (5, 4), # Not sorted.
2452 (6, 7, 7, 8), # Duplicate.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002453 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002454 ):
2455 with self.assertRaises(
2456 ValueError,
2457 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
2458 _posixsubprocess.fork_exec(
2459 [b"false"], [b"false"],
2460 True, fds_to_keep, None, [b"env"],
2461 -1, -1, -1, -1,
2462 1, 2, 3, 4,
2463 True, True, None)
2464 self.assertIn('fds_to_keep', str(c.exception))
2465 finally:
2466 if not gc_enabled:
2467 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02002468
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00002469 def test_communicate_BrokenPipeError_stdin_close(self):
2470 # By not setting stdout or stderr or a timeout we force the fast path
2471 # that just calls _stdin_write() internally due to our mock.
2472 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2473 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2474 mock_proc_stdin.close.side_effect = BrokenPipeError
2475 proc.communicate() # Should swallow BrokenPipeError from close.
2476 mock_proc_stdin.close.assert_called_with()
2477
2478 def test_communicate_BrokenPipeError_stdin_write(self):
2479 # By not setting stdout or stderr or a timeout we force the fast path
2480 # that just calls _stdin_write() internally due to our mock.
2481 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2482 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2483 mock_proc_stdin.write.side_effect = BrokenPipeError
2484 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
2485 mock_proc_stdin.write.assert_called_once_with(b'stuff')
2486 mock_proc_stdin.close.assert_called_once_with()
2487
2488 def test_communicate_BrokenPipeError_stdin_flush(self):
2489 # Setting stdin and stdout forces the ._communicate() code path.
2490 # python -h exits faster than python -c pass (but spams stdout).
2491 proc = subprocess.Popen([sys.executable, '-h'],
2492 stdin=subprocess.PIPE,
2493 stdout=subprocess.PIPE)
2494 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
2495 open(os.devnull, 'wb') as dev_null:
2496 mock_proc_stdin.flush.side_effect = BrokenPipeError
2497 # because _communicate registers a selector using proc.stdin...
2498 mock_proc_stdin.fileno.return_value = dev_null.fileno()
2499 # _communicate() should swallow BrokenPipeError from flush.
2500 proc.communicate(b'stuff')
2501 mock_proc_stdin.flush.assert_called_once_with()
2502
2503 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
2504 # Setting stdin and stdout forces the ._communicate() code path.
2505 # python -h exits faster than python -c pass (but spams stdout).
2506 proc = subprocess.Popen([sys.executable, '-h'],
2507 stdin=subprocess.PIPE,
2508 stdout=subprocess.PIPE)
2509 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2510 mock_proc_stdin.close.side_effect = BrokenPipeError
2511 # _communicate() should swallow BrokenPipeError from close.
2512 proc.communicate(timeout=999)
2513 mock_proc_stdin.close.assert_called_once_with()
2514
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002515 _libc_file_extensions = {
2516 'Linux': 'so.6',
Gregory P. Smith21d333b2017-01-22 20:54:42 -08002517 'Darwin': 'dylib',
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002518 }
Gregory P. Smith1fa08bc2017-01-22 22:19:38 -08002519 @unittest.skipIf(not ctypes, 'ctypes module required.')
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002520 @unittest.skipIf(platform.uname()[0] not in _libc_file_extensions,
2521 'Test requires a libc this code can load with ctypes.')
2522 @unittest.skipIf(not sys.executable, 'Test requires sys.executable.')
2523 def test_child_terminated_in_stopped_state(self):
2524 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
2525 PTRACE_TRACEME = 0 # From glibc and MacOS (PT_TRACE_ME).
2526 libc_name = 'libc.' + self._libc_file_extensions[platform.uname()[0]]
2527 libc = ctypes.CDLL(libc_name)
2528 if not hasattr(libc, 'ptrace'):
2529 raise unittest.SkipTest('ptrace() required.')
2530 test_ptrace = subprocess.Popen(
2531 [sys.executable, '-c', """if True:
2532 import ctypes
2533 libc = ctypes.CDLL({libc_name!r})
2534 libc.ptrace({PTRACE_TRACEME}, 0, 0)
2535 """.format(libc_name=libc_name, PTRACE_TRACEME=PTRACE_TRACEME)
2536 ])
2537 if test_ptrace.wait() != 0:
2538 raise unittest.SkipTest('ptrace() failed - unable to test.')
2539 child = subprocess.Popen(
2540 [sys.executable, '-c', """if True:
2541 import ctypes
2542 libc = ctypes.CDLL({libc_name!r})
2543 libc.ptrace({PTRACE_TRACEME}, 0, 0)
2544 libc.printf(ctypes.c_char_p(0xdeadbeef)) # Crash the process.
2545 """.format(libc_name=libc_name, PTRACE_TRACEME=PTRACE_TRACEME)
2546 ])
2547 try:
2548 returncode = child.wait()
2549 except Exception as e:
2550 child.kill() # Clean up the hung stopped process.
2551 raise e
2552 self.assertNotEqual(0, returncode)
2553 self.assertLess(returncode, 0) # signal death, likely SIGSEGV.
2554
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002555
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002556@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00002557class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002558
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002559 def test_startupinfo(self):
2560 # startupinfo argument
2561 # We uses hardcoded constants, because we do not want to
2562 # depend on win32all.
2563 STARTF_USESHOWWINDOW = 1
2564 SW_MAXIMIZE = 3
2565 startupinfo = subprocess.STARTUPINFO()
2566 startupinfo.dwFlags = STARTF_USESHOWWINDOW
2567 startupinfo.wShowWindow = SW_MAXIMIZE
2568 # Since Python is a console process, it won't be affected
2569 # by wShowWindow, but the argument should be silently
2570 # ignored
2571 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002572 startupinfo=startupinfo)
2573
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05302574 def test_startupinfo_keywords(self):
2575 # startupinfo argument
2576 # We use hardcoded constants, because we do not want to
2577 # depend on win32all.
2578 STARTF_USERSHOWWINDOW = 1
2579 SW_MAXIMIZE = 3
2580 startupinfo = subprocess.STARTUPINFO(
2581 dwFlags=STARTF_USERSHOWWINDOW,
2582 wShowWindow=SW_MAXIMIZE
2583 )
2584 # Since Python is a console process, it won't be affected
2585 # by wShowWindow, but the argument should be silently
2586 # ignored
2587 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
2588 startupinfo=startupinfo)
2589
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002590 def test_creationflags(self):
2591 # creationflags argument
2592 CREATE_NEW_CONSOLE = 16
2593 sys.stderr.write(" a DOS box should flash briefly ...\n")
2594 subprocess.call(sys.executable +
2595 ' -c "import time; time.sleep(0.25)"',
2596 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002597
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002598 def test_invalid_args(self):
2599 # invalid arguments should raise ValueError
2600 self.assertRaises(ValueError, subprocess.call,
2601 [sys.executable, "-c",
2602 "import sys; sys.exit(47)"],
2603 preexec_fn=lambda: 1)
2604 self.assertRaises(ValueError, subprocess.call,
2605 [sys.executable, "-c",
2606 "import sys; sys.exit(47)"],
2607 stdout=subprocess.PIPE,
2608 close_fds=True)
2609
2610 def test_close_fds(self):
2611 # close file descriptors
2612 rc = subprocess.call([sys.executable, "-c",
2613 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002614 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002615 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002616
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002617 def test_shell_sequence(self):
2618 # Run command through the shell (sequence)
2619 newenv = os.environ.copy()
2620 newenv["FRUIT"] = "physalis"
2621 p = subprocess.Popen(["set"], shell=1,
2622 stdout=subprocess.PIPE,
2623 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002624 with p:
2625 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00002626
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002627 def test_shell_string(self):
2628 # Run command through the shell (string)
2629 newenv = os.environ.copy()
2630 newenv["FRUIT"] = "physalis"
2631 p = subprocess.Popen("set", shell=1,
2632 stdout=subprocess.PIPE,
2633 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002634 with p:
2635 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002636
Steve Dower050acae2016-09-06 20:16:17 -07002637 def test_shell_encodings(self):
2638 # Run command through the shell (string)
2639 for enc in ['ansi', 'oem']:
2640 newenv = os.environ.copy()
2641 newenv["FRUIT"] = "physalis"
2642 p = subprocess.Popen("set", shell=1,
2643 stdout=subprocess.PIPE,
2644 env=newenv,
2645 encoding=enc)
2646 with p:
2647 self.assertIn("physalis", p.stdout.read(), enc)
2648
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002649 def test_call_string(self):
2650 # call() function with string argument on Windows
2651 rc = subprocess.call(sys.executable +
2652 ' -c "import sys; sys.exit(47)"')
2653 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002654
Florent Xicluna4886d242010-03-08 13:27:26 +00002655 def _kill_process(self, method, *args):
2656 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00002657 p = subprocess.Popen([sys.executable, "-c", """if 1:
2658 import sys, time
2659 sys.stdout.write('x\\n')
2660 sys.stdout.flush()
2661 time.sleep(30)
2662 """],
2663 stdin=subprocess.PIPE,
2664 stdout=subprocess.PIPE,
2665 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002666 with p:
2667 # Wait for the interpreter to be completely initialized before
2668 # sending any signal.
2669 p.stdout.read(1)
2670 getattr(p, method)(*args)
2671 _, stderr = p.communicate()
2672 self.assertStderrEqual(stderr, b'')
2673 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00002674 self.assertNotEqual(returncode, 0)
2675
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002676 def _kill_dead_process(self, method, *args):
2677 p = subprocess.Popen([sys.executable, "-c", """if 1:
2678 import sys, time
2679 sys.stdout.write('x\\n')
2680 sys.stdout.flush()
2681 sys.exit(42)
2682 """],
2683 stdin=subprocess.PIPE,
2684 stdout=subprocess.PIPE,
2685 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002686 with p:
2687 # Wait for the interpreter to be completely initialized before
2688 # sending any signal.
2689 p.stdout.read(1)
2690 # The process should end after this
2691 time.sleep(1)
2692 # This shouldn't raise even though the child is now dead
2693 getattr(p, method)(*args)
2694 _, stderr = p.communicate()
2695 self.assertStderrEqual(stderr, b'')
2696 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002697 self.assertEqual(rc, 42)
2698
Florent Xicluna4886d242010-03-08 13:27:26 +00002699 def test_send_signal(self):
2700 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00002701
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002702 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002703 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00002704
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002705 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002706 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00002707
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002708 def test_send_signal_dead(self):
2709 self._kill_dead_process('send_signal', signal.SIGTERM)
2710
2711 def test_kill_dead(self):
2712 self._kill_dead_process('kill')
2713
2714 def test_terminate_dead(self):
2715 self._kill_dead_process('terminate')
2716
Martin Panter23172bd2016-04-16 11:28:10 +00002717class MiscTests(unittest.TestCase):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002718 def test_getoutput(self):
2719 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
2720 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
2721 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00002722
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002723 # we use mkdtemp in the next line to create an empty directory
2724 # under our exclusive control; from that, we can invent a pathname
2725 # that we _know_ won't exist. This is guaranteed to fail.
2726 dir = None
2727 try:
2728 dir = tempfile.mkdtemp()
2729 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00002730 status, output = subprocess.getstatusoutput(
2731 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002732 self.assertNotEqual(status, 0)
2733 finally:
2734 if dir is not None:
2735 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00002736
Gregory P. Smithace55862015-04-07 15:57:54 -07002737 def test__all__(self):
2738 """Ensure that __all__ is populated properly."""
Martin Panter528619b2016-04-16 23:42:37 +00002739 intentionally_excluded = {"list2cmdline", "Handle"}
Gregory P. Smithace55862015-04-07 15:57:54 -07002740 exported = set(subprocess.__all__)
2741 possible_exports = set()
2742 import types
2743 for name, value in subprocess.__dict__.items():
2744 if name.startswith('_'):
2745 continue
2746 if isinstance(value, (types.ModuleType,)):
2747 continue
2748 possible_exports.add(name)
2749 self.assertEqual(exported, possible_exports - intentionally_excluded)
2750
2751
Martin Panter23172bd2016-04-16 11:28:10 +00002752@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
2753 "Test needs selectors.PollSelector")
2754class ProcessTestCaseNoPoll(ProcessTestCase):
2755 def setUp(self):
2756 self.orig_selector = subprocess._PopenSelector
2757 subprocess._PopenSelector = selectors.SelectSelector
2758 ProcessTestCase.setUp(self)
2759
2760 def tearDown(self):
2761 subprocess._PopenSelector = self.orig_selector
2762 ProcessTestCase.tearDown(self)
2763
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002764
Tim Golden126c2962010-08-11 14:20:40 +00002765@unittest.skipUnless(mswindows, "Windows-specific tests")
2766class CommandsWithSpaces (BaseTestCase):
2767
2768 def setUp(self):
2769 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03002770 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00002771 self.fname = fname.lower ()
2772 os.write(f, b"import sys;"
2773 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
2774 )
2775 os.close(f)
2776
2777 def tearDown(self):
2778 os.remove(self.fname)
2779 super().tearDown()
2780
2781 def with_spaces(self, *args, **kwargs):
2782 kwargs['stdout'] = subprocess.PIPE
2783 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02002784 with p:
2785 self.assertEqual(
2786 p.stdout.read ().decode("mbcs"),
2787 "2 [%r, 'ab cd']" % self.fname
2788 )
Tim Golden126c2962010-08-11 14:20:40 +00002789
2790 def test_shell_string_with_spaces(self):
2791 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002792 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2793 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002794
2795 def test_shell_sequence_with_spaces(self):
2796 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002797 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002798
2799 def test_noshell_string_with_spaces(self):
2800 # call() function with string argument with spaces on Windows
2801 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2802 "ab cd"))
2803
2804 def test_noshell_sequence_with_spaces(self):
2805 # call() function with sequence argument with spaces on Windows
2806 self.with_spaces([sys.executable, self.fname, "ab cd"])
2807
Brian Curtin79cdb662010-12-03 02:46:02 +00002808
Georg Brandla86b2622012-02-20 21:34:57 +01002809class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00002810
2811 def test_pipe(self):
2812 with subprocess.Popen([sys.executable, "-c",
2813 "import sys;"
2814 "sys.stdout.write('stdout');"
2815 "sys.stderr.write('stderr');"],
2816 stdout=subprocess.PIPE,
2817 stderr=subprocess.PIPE) as proc:
2818 self.assertEqual(proc.stdout.read(), b"stdout")
2819 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2820
2821 self.assertTrue(proc.stdout.closed)
2822 self.assertTrue(proc.stderr.closed)
2823
2824 def test_returncode(self):
2825 with subprocess.Popen([sys.executable, "-c",
2826 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002827 pass
2828 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002829 self.assertEqual(proc.returncode, 100)
2830
2831 def test_communicate_stdin(self):
2832 with subprocess.Popen([sys.executable, "-c",
2833 "import sys;"
2834 "sys.exit(sys.stdin.read() == 'context')"],
2835 stdin=subprocess.PIPE) as proc:
2836 proc.communicate(b"context")
2837 self.assertEqual(proc.returncode, 1)
2838
2839 def test_invalid_args(self):
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +01002840 with self.assertRaises((FileNotFoundError, PermissionError)) as c:
Brian Curtin79cdb662010-12-03 02:46:02 +00002841 with subprocess.Popen(['nonexisting_i_hope'],
2842 stdout=subprocess.PIPE,
2843 stderr=subprocess.PIPE) as proc:
2844 pass
2845
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002846 def test_broken_pipe_cleanup(self):
2847 """Broken pipe error should not prevent wait() (Issue 21619)"""
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002848 proc = subprocess.Popen([sys.executable, '-c', 'pass'],
Victor Stinner20f4bd42015-03-05 02:38:41 +01002849 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01002850 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002851 proc = proc.__enter__()
2852 # Prepare to send enough data to overflow any OS pipe buffering and
2853 # guarantee a broken pipe error. Data is held in BufferedWriter
2854 # buffer until closed.
2855 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002856 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002857 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02002858 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002859 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002860 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002861
Brian Curtin79cdb662010-12-03 02:46:02 +00002862
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002863if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002864 unittest.main()