blob: 7fabe6ad7653326ca19e081a3dc580f658f3d85c [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
Gregory P. Smith56bc3b72017-05-23 07:49:13 -070024else:
25 import ctypes.util
Gregory P. Smith1fa08bc2017-01-22 22:19:38 -080026
27try:
Antoine Pitroua8392712013-08-30 23:38:13 +020028 import threading
29except ImportError:
30 threading = None
Benjamin Peterson964561b2011-12-10 12:31:42 -050031
Steve Dower22d06982016-09-06 19:38:15 -070032if support.PGO:
33 raise unittest.SkipTest("test is not helpful for PGO")
34
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000035mswindows = (sys.platform == "win32")
36
37#
38# Depends on the following external programs: Python
39#
40
41if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000042 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
43 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000044else:
45 SETBINARY = ''
46
Florent Xiclunab1e94e82010-02-27 22:12:37 +000047
Florent Xiclunac049d872010-03-27 22:47:23 +000048class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000049 def setUp(self):
50 # Try to minimize the number of children we have so this test
51 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000052 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000053
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000054 def tearDown(self):
55 for inst in subprocess._active:
56 inst.wait()
57 subprocess._cleanup()
58 self.assertFalse(subprocess._active, "subprocess._active not empty")
59
Florent Xiclunab1e94e82010-02-27 22:12:37 +000060 def assertStderrEqual(self, stderr, expected, msg=None):
61 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
62 # shutdown time. That frustrates tests trying to check stderr produced
63 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000064 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040065 # strip_python_stderr also strips whitespace, so we do too.
66 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000067 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000068
Florent Xiclunac049d872010-03-27 22:47:23 +000069
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080070class PopenTestException(Exception):
71 pass
72
73
74class PopenExecuteChildRaises(subprocess.Popen):
75 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
76 _execute_child fails.
77 """
78 def _execute_child(self, *args, **kwargs):
79 raise PopenTestException("Forced Exception for Test")
80
81
Florent Xiclunac049d872010-03-27 22:47:23 +000082class ProcessTestCase(BaseTestCase):
83
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070084 def test_io_buffered_by_default(self):
85 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
86 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
87 stderr=subprocess.PIPE)
88 try:
89 self.assertIsInstance(p.stdin, io.BufferedIOBase)
90 self.assertIsInstance(p.stdout, io.BufferedIOBase)
91 self.assertIsInstance(p.stderr, io.BufferedIOBase)
92 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -070093 p.stdin.close()
94 p.stdout.close()
95 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070096 p.wait()
97
98 def test_io_unbuffered_works(self):
99 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
100 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
101 stderr=subprocess.PIPE, bufsize=0)
102 try:
103 self.assertIsInstance(p.stdin, io.RawIOBase)
104 self.assertIsInstance(p.stdout, io.RawIOBase)
105 self.assertIsInstance(p.stderr, io.RawIOBase)
106 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700107 p.stdin.close()
108 p.stdout.close()
109 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700110 p.wait()
111
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000112 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000113 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000114 rc = subprocess.call([sys.executable, "-c",
115 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000116 self.assertEqual(rc, 47)
117
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400118 def test_call_timeout(self):
119 # call() function with timeout argument; we want to test that the child
120 # process gets killed when the timeout expires. If the child isn't
121 # killed, this call will deadlock since subprocess.call waits for the
122 # child.
123 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
124 [sys.executable, "-c", "while True: pass"],
125 timeout=0.1)
126
Peter Astrand454f7672005-01-01 09:36:35 +0000127 def test_check_call_zero(self):
128 # check_call() function with zero return code
129 rc = subprocess.check_call([sys.executable, "-c",
130 "import sys; sys.exit(0)"])
131 self.assertEqual(rc, 0)
132
133 def test_check_call_nonzero(self):
134 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000135 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000136 subprocess.check_call([sys.executable, "-c",
137 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000138 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000139
Georg Brandlf9734072008-12-07 15:30:06 +0000140 def test_check_output(self):
141 # check_output() function with zero return code
142 output = subprocess.check_output(
143 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000144 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000145
146 def test_check_output_nonzero(self):
147 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000148 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000149 subprocess.check_output(
150 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000151 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000152
153 def test_check_output_stderr(self):
154 # check_output() function stderr redirected to stdout
155 output = subprocess.check_output(
156 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
157 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000158 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000159
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300160 def test_check_output_stdin_arg(self):
161 # check_output() can be called with stdin set to a file
162 tf = tempfile.TemporaryFile()
163 self.addCleanup(tf.close)
164 tf.write(b'pear')
165 tf.seek(0)
166 output = subprocess.check_output(
167 [sys.executable, "-c",
168 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
169 stdin=tf)
170 self.assertIn(b'PEAR', output)
171
172 def test_check_output_input_arg(self):
173 # check_output() can be called with input set to a string
174 output = subprocess.check_output(
175 [sys.executable, "-c",
176 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
177 input=b'pear')
178 self.assertIn(b'PEAR', output)
179
Georg Brandlf9734072008-12-07 15:30:06 +0000180 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300181 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000182 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000183 output = subprocess.check_output(
184 [sys.executable, "-c", "print('will not be run')"],
185 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000186 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000187 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000188
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300189 def test_check_output_stdin_with_input_arg(self):
190 # check_output() refuses to accept 'stdin' with 'input'
191 tf = tempfile.TemporaryFile()
192 self.addCleanup(tf.close)
193 tf.write(b'pear')
194 tf.seek(0)
195 with self.assertRaises(ValueError) as c:
196 output = subprocess.check_output(
197 [sys.executable, "-c", "print('will not be run')"],
198 stdin=tf, input=b'hare')
199 self.fail("Expected ValueError when stdin and input args supplied.")
200 self.assertIn('stdin', c.exception.args[0])
201 self.assertIn('input', c.exception.args[0])
202
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400203 def test_check_output_timeout(self):
204 # check_output() function with timeout arg
205 with self.assertRaises(subprocess.TimeoutExpired) as c:
206 output = subprocess.check_output(
207 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200208 "import sys, time\n"
209 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400210 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200211 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400212 # Some heavily loaded buildbots (sparc Debian 3.x) require
213 # this much time to start and print.
214 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400215 self.fail("Expected TimeoutExpired.")
216 self.assertEqual(c.exception.output, b'BDFL')
217
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000218 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000219 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000220 newenv = os.environ.copy()
221 newenv["FRUIT"] = "banana"
222 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000223 'import sys, os;'
224 'sys.exit(os.getenv("FRUIT")=="banana")'],
225 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000226 self.assertEqual(rc, 1)
227
Victor Stinner87b9bc32011-06-01 00:57:47 +0200228 def test_invalid_args(self):
229 # Popen() called with invalid arguments should raise TypeError
230 # but Popen.__del__ should not complain (issue #12085)
231 with support.captured_stderr() as s:
232 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
233 argcount = subprocess.Popen.__init__.__code__.co_argcount
234 too_many_args = [0] * (argcount + 1)
235 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
236 self.assertEqual(s.getvalue(), '')
237
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000238 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000239 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000240 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000241 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000242 self.addCleanup(p.stdout.close)
243 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000244 p.wait()
245 self.assertEqual(p.stdin, None)
246
247 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200248 # .stdout is None when not redirected, and the child's stdout will
249 # be inherited from the parent. In order to test this we run a
250 # subprocess in a subprocess:
251 # this_test
252 # \-- subprocess created by this test (parent)
253 # \-- subprocess created by the parent subprocess (child)
254 # The parent doesn't specify stdout, so the child will use the
255 # parent's stdout. This test checks that the message printed by the
256 # child goes to the parent stdout. The parent also checks that the
257 # child's stdout is None. See #11963.
258 code = ('import sys; from subprocess import Popen, PIPE;'
259 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
260 ' stdin=PIPE, stderr=PIPE);'
261 'p.wait(); assert p.stdout is None;')
262 p = subprocess.Popen([sys.executable, "-c", code],
263 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
264 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000265 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200266 out, err = p.communicate()
267 self.assertEqual(p.returncode, 0, err)
268 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000269
270 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000271 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000272 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000273 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000274 self.addCleanup(p.stdout.close)
275 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000276 p.wait()
277 self.assertEqual(p.stderr, None)
278
Chris Jerdonek776cb192012-10-08 15:56:43 -0700279 def _assert_python(self, pre_args, **kwargs):
280 # We include sys.exit() to prevent the test runner from hanging
281 # whenever python is found.
282 args = pre_args + ["import sys; sys.exit(47)"]
283 p = subprocess.Popen(args, **kwargs)
284 p.wait()
285 self.assertEqual(47, p.returncode)
286
287 def test_executable(self):
288 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700289 #
290 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
291 # determine where its standard library is, so we need the directory
292 # of args[0] to be valid for the Popen() call to Python to succeed.
293 # See also issue #16170 and issue #7774.
294 doesnotexist = os.path.join(os.path.dirname(sys.executable),
295 "doesnotexist")
296 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700297
298 def test_executable_takes_precedence(self):
299 # Check that the executable argument takes precedence over args[0].
300 #
301 # Verify first that the call succeeds without the executable arg.
302 pre_args = [sys.executable, "-c"]
303 self._assert_python(pre_args)
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +0100304 self.assertRaises((FileNotFoundError, PermissionError),
305 self._assert_python, pre_args,
Chris Jerdonek776cb192012-10-08 15:56:43 -0700306 executable="doesnotexist")
307
308 @unittest.skipIf(mswindows, "executable argument replaces shell")
309 def test_executable_replaces_shell(self):
310 # Check that the executable argument replaces the default shell
311 # when shell=True.
312 self._assert_python([], executable=sys.executable, shell=True)
313
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700314 # For use in the test_cwd* tests below.
315 def _normalize_cwd(self, cwd):
316 # Normalize an expected cwd (for Tru64 support).
317 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
318 # strings. See bug #1063571.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +0300319 with support.change_cwd(cwd):
320 return os.getcwd()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700321
322 # For use in the test_cwd* tests below.
323 def _split_python_path(self):
324 # Return normalized (python_dir, python_base).
325 python_path = os.path.realpath(sys.executable)
326 return os.path.split(python_path)
327
328 # For use in the test_cwd* tests below.
329 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
330 # Invoke Python via Popen, and assert that (1) the call succeeds,
331 # and that (2) the current working directory of the child process
332 # matches *expected_cwd*.
333 p = subprocess.Popen([python_arg, "-c",
334 "import os, sys; "
335 "sys.stdout.write(os.getcwd()); "
336 "sys.exit(47)"],
337 stdout=subprocess.PIPE,
338 **kwargs)
339 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000340 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700341 self.assertEqual(47, p.returncode)
342 normcase = os.path.normcase
343 self.assertEqual(normcase(expected_cwd),
344 normcase(p.stdout.read().decode("utf-8")))
345
346 def test_cwd(self):
347 # Check that cwd changes the cwd for the child process.
348 temp_dir = tempfile.gettempdir()
349 temp_dir = self._normalize_cwd(temp_dir)
350 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
351
Sayan Chowdhuryd5c11f72017-02-26 22:36:10 +0530352 def test_cwd_with_pathlike(self):
353 temp_dir = tempfile.gettempdir()
354 temp_dir = self._normalize_cwd(temp_dir)
355
356 class _PathLikeObj:
357 def __fspath__(self):
358 return temp_dir
359
360 self._assert_cwd(temp_dir, sys.executable, cwd=_PathLikeObj())
361
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700362 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700363 def test_cwd_with_relative_arg(self):
364 # Check that Popen looks for args[0] relative to cwd if args[0]
365 # is relative.
366 python_dir, python_base = self._split_python_path()
367 rel_python = os.path.join(os.curdir, python_base)
368 with support.temp_cwd() as wrong_dir:
369 # Before calling with the correct cwd, confirm that the call fails
370 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700371 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700372 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700373 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700374 [rel_python], cwd=wrong_dir)
375 python_dir = self._normalize_cwd(python_dir)
376 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
377
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700378 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700379 def test_cwd_with_relative_executable(self):
380 # Check that Popen looks for executable relative to cwd if executable
381 # is relative (and that executable takes precedence over args[0]).
382 python_dir, python_base = self._split_python_path()
383 rel_python = os.path.join(os.curdir, python_base)
384 doesntexist = "somethingyoudonthave"
385 with support.temp_cwd() as wrong_dir:
386 # Before calling with the correct cwd, confirm that the call fails
387 # without cwd and with the wrong cwd.
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)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700390 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700391 [doesntexist], executable=rel_python,
392 cwd=wrong_dir)
393 python_dir = self._normalize_cwd(python_dir)
394 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
395 cwd=python_dir)
396
397 def test_cwd_with_absolute_arg(self):
398 # Check that Popen can find the executable when the cwd is wrong
399 # if args[0] is an absolute path.
400 python_dir, python_base = self._split_python_path()
401 abs_python = os.path.join(python_dir, python_base)
402 rel_python = os.path.join(os.curdir, python_base)
Berker Peksagce643912015-05-06 06:33:17 +0300403 with support.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700404 # Before calling with an absolute path, confirm that using a
405 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700406 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700407 [rel_python], cwd=wrong_dir)
408 wrong_dir = self._normalize_cwd(wrong_dir)
409 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
410
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100411 @unittest.skipIf(sys.base_prefix != sys.prefix,
412 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000413 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700414 python_dir, python_base = self._split_python_path()
415 python_dir = self._normalize_cwd(python_dir)
416 self._assert_cwd(python_dir, "somethingyoudonthave",
417 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000418
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100419 @unittest.skipIf(sys.base_prefix != sys.prefix,
420 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000421 @unittest.skipIf(sysconfig.is_python_build(),
422 "need an installed Python. See #7774")
423 def test_executable_without_cwd(self):
424 # For a normal installation, it should work without 'cwd'
425 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700426 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
427 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000428
429 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000430 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000431 p = subprocess.Popen([sys.executable, "-c",
432 'import sys; sys.exit(sys.stdin.read() == "pear")'],
433 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000434 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000435 p.stdin.close()
436 p.wait()
437 self.assertEqual(p.returncode, 1)
438
439 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000440 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000441 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000442 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000443 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000444 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000445 os.lseek(d, 0, 0)
446 p = subprocess.Popen([sys.executable, "-c",
447 'import sys; sys.exit(sys.stdin.read() == "pear")'],
448 stdin=d)
449 p.wait()
450 self.assertEqual(p.returncode, 1)
451
452 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000453 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000454 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000455 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000456 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000457 tf.seek(0)
458 p = subprocess.Popen([sys.executable, "-c",
459 'import sys; sys.exit(sys.stdin.read() == "pear")'],
460 stdin=tf)
461 p.wait()
462 self.assertEqual(p.returncode, 1)
463
464 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000465 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000466 p = subprocess.Popen([sys.executable, "-c",
467 'import sys; sys.stdout.write("orange")'],
468 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200469 with p:
470 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000471
472 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000473 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000474 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000475 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000476 d = tf.fileno()
477 p = subprocess.Popen([sys.executable, "-c",
478 'import sys; sys.stdout.write("orange")'],
479 stdout=d)
480 p.wait()
481 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000482 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000483
484 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000485 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000486 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000487 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000488 p = subprocess.Popen([sys.executable, "-c",
489 'import sys; sys.stdout.write("orange")'],
490 stdout=tf)
491 p.wait()
492 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000493 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000494
495 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000496 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000497 p = subprocess.Popen([sys.executable, "-c",
498 'import sys; sys.stderr.write("strawberry")'],
499 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +0200500 with p:
501 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000502
503 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000504 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000505 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000506 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000507 d = tf.fileno()
508 p = subprocess.Popen([sys.executable, "-c",
509 'import sys; sys.stderr.write("strawberry")'],
510 stderr=d)
511 p.wait()
512 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000513 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000514
515 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000516 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000517 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000518 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000519 p = subprocess.Popen([sys.executable, "-c",
520 'import sys; sys.stderr.write("strawberry")'],
521 stderr=tf)
522 p.wait()
523 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000524 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000525
Martin Panterc7635892016-05-13 01:54:44 +0000526 def test_stderr_redirect_with_no_stdout_redirect(self):
527 # test stderr=STDOUT while stdout=None (not set)
528
529 # - grandchild prints to stderr
530 # - child redirects grandchild's stderr to its stdout
531 # - the parent should get grandchild's stderr in child's stdout
532 p = subprocess.Popen([sys.executable, "-c",
533 'import sys, subprocess;'
534 'rc = subprocess.call([sys.executable, "-c",'
535 ' "import sys;"'
536 ' "sys.stderr.write(\'42\')"],'
537 ' stderr=subprocess.STDOUT);'
538 'sys.exit(rc)'],
539 stdout=subprocess.PIPE,
540 stderr=subprocess.PIPE)
541 stdout, stderr = p.communicate()
542 #NOTE: stdout should get stderr from grandchild
543 self.assertStderrEqual(stdout, b'42')
544 self.assertStderrEqual(stderr, b'') # should be empty
545 self.assertEqual(p.returncode, 0)
546
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000547 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000548 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000549 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000550 'import sys;'
551 'sys.stdout.write("apple");'
552 'sys.stdout.flush();'
553 'sys.stderr.write("orange")'],
554 stdout=subprocess.PIPE,
555 stderr=subprocess.STDOUT)
Victor Stinner7438c612016-05-20 12:43:15 +0200556 with p:
557 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000558
559 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000560 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000561 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000562 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000563 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000564 'import sys;'
565 'sys.stdout.write("apple");'
566 'sys.stdout.flush();'
567 'sys.stderr.write("orange")'],
568 stdout=tf,
569 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000570 p.wait()
571 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000572 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000573
Thomas Wouters89f507f2006-12-13 04:49:30 +0000574 def test_stdout_filedes_of_stdout(self):
575 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200576 # To avoid printing the text on stdout, we do something similar to
577 # test_stdout_none (see above). The parent subprocess calls the child
578 # subprocess passing stdout=1, and this test uses stdout=PIPE in
579 # order to capture and check the output of the parent. See #11963.
580 code = ('import sys, subprocess; '
581 'rc = subprocess.call([sys.executable, "-c", '
582 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
583 'b\'test with stdout=1\'))"], stdout=1); '
584 'assert rc == 18')
585 p = subprocess.Popen([sys.executable, "-c", code],
586 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
587 self.addCleanup(p.stdout.close)
588 self.addCleanup(p.stderr.close)
589 out, err = p.communicate()
590 self.assertEqual(p.returncode, 0, err)
591 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000592
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200593 def test_stdout_devnull(self):
594 p = subprocess.Popen([sys.executable, "-c",
595 'for i in range(10240):'
596 'print("x" * 1024)'],
597 stdout=subprocess.DEVNULL)
598 p.wait()
599 self.assertEqual(p.stdout, None)
600
601 def test_stderr_devnull(self):
602 p = subprocess.Popen([sys.executable, "-c",
603 'import sys\n'
604 'for i in range(10240):'
605 'sys.stderr.write("x" * 1024)'],
606 stderr=subprocess.DEVNULL)
607 p.wait()
608 self.assertEqual(p.stderr, None)
609
610 def test_stdin_devnull(self):
611 p = subprocess.Popen([sys.executable, "-c",
612 'import sys;'
613 'sys.stdin.read(1)'],
614 stdin=subprocess.DEVNULL)
615 p.wait()
616 self.assertEqual(p.stdin, None)
617
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000618 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000619 newenv = os.environ.copy()
620 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200621 with subprocess.Popen([sys.executable, "-c",
622 'import sys,os;'
623 'sys.stdout.write(os.getenv("FRUIT"))'],
624 stdout=subprocess.PIPE,
625 env=newenv) as p:
626 stdout, stderr = p.communicate()
627 self.assertEqual(stdout, b"orange")
628
Victor Stinner62d51182011-06-23 01:02:25 +0200629 # Windows requires at least the SYSTEMROOT environment variable to start
630 # Python
631 @unittest.skipIf(sys.platform == 'win32',
632 'cannot test an empty env on Windows')
Gregory P. Smithb3512482017-05-30 14:40:37 -0700633 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
634 'The Python shared library cannot be loaded '
635 'with an empty environment.')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200636 def test_empty_env(self):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700637 """Verify that env={} is as empty as possible."""
638
Gregory P. Smith85aba232017-05-30 16:21:47 -0700639 def is_env_var_to_ignore(n):
Gregory P. Smithb3512482017-05-30 14:40:37 -0700640 """Determine if an environment variable is under our control."""
641 # This excludes some __CF_* and VERSIONER_* keys MacOS insists
642 # on adding even when the environment in exec is empty.
643 # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist.
Gregory P. Smith85aba232017-05-30 16:21:47 -0700644 return ('VERSIONER' in n or '__CF' in n or # MacOS
645 n == 'LD_PRELOAD' or n.startswith('SANDBOX')) # Gentoo
Gregory P. Smithb3512482017-05-30 14:40:37 -0700646
Victor Stinnerf1512a22011-06-21 17:18:38 +0200647 with subprocess.Popen([sys.executable, "-c",
Gregory P. Smithb3512482017-05-30 14:40:37 -0700648 'import os; print(list(os.environ.keys()))'],
649 stdout=subprocess.PIPE, env={}) as p:
Victor Stinnerf1512a22011-06-21 17:18:38 +0200650 stdout, stderr = p.communicate()
Gregory P. Smithb3512482017-05-30 14:40:37 -0700651 child_env_names = eval(stdout.strip())
652 self.assertIsInstance(child_env_names, list)
653 child_env_names = [k for k in child_env_names
654 if not is_env_var_to_ignore(k)]
655 self.assertEqual(child_env_names, [])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000656
Peter Astrandcbac93c2005-03-03 20:24:28 +0000657 def test_communicate_stdin(self):
658 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000659 'import sys;'
660 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000661 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000662 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000663 self.assertEqual(p.returncode, 1)
664
665 def test_communicate_stdout(self):
666 p = subprocess.Popen([sys.executable, "-c",
667 'import sys; sys.stdout.write("pineapple")'],
668 stdout=subprocess.PIPE)
669 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000670 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000671 self.assertEqual(stderr, None)
672
673 def test_communicate_stderr(self):
674 p = subprocess.Popen([sys.executable, "-c",
675 'import sys; sys.stderr.write("pineapple")'],
676 stderr=subprocess.PIPE)
677 (stdout, stderr) = p.communicate()
678 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000679 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000680
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000681 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000682 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000683 'import sys,os;'
684 'sys.stderr.write("pineapple");'
685 'sys.stdout.write(sys.stdin.read())'],
686 stdin=subprocess.PIPE,
687 stdout=subprocess.PIPE,
688 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000689 self.addCleanup(p.stdout.close)
690 self.addCleanup(p.stderr.close)
691 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000692 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000693 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000694 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000695
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400696 def test_communicate_timeout(self):
697 p = subprocess.Popen([sys.executable, "-c",
698 'import sys,os,time;'
699 'sys.stderr.write("pineapple\\n");'
700 'time.sleep(1);'
701 'sys.stderr.write("pear\\n");'
702 'sys.stdout.write(sys.stdin.read())'],
703 universal_newlines=True,
704 stdin=subprocess.PIPE,
705 stdout=subprocess.PIPE,
706 stderr=subprocess.PIPE)
707 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
708 timeout=0.3)
709 # Make sure we can keep waiting for it, and that we get the whole output
710 # after it completes.
711 (stdout, stderr) = p.communicate()
712 self.assertEqual(stdout, "banana")
713 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
714
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700715 def test_communicate_timeout_large_output(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200716 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400717 p = subprocess.Popen([sys.executable, "-c",
718 'import sys,os,time;'
719 'sys.stdout.write("a" * (64 * 1024));'
720 'time.sleep(0.2);'
721 'sys.stdout.write("a" * (64 * 1024));'
722 'time.sleep(0.2);'
723 'sys.stdout.write("a" * (64 * 1024));'
724 'time.sleep(0.2);'
725 'sys.stdout.write("a" * (64 * 1024));'],
726 stdout=subprocess.PIPE)
727 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
728 (stdout, _) = p.communicate()
729 self.assertEqual(len(stdout), 4 * 64 * 1024)
730
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000731 # Test for the fd leak reported in http://bugs.python.org/issue2791.
732 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000733 for stdin_pipe in (False, True):
734 for stdout_pipe in (False, True):
735 for stderr_pipe in (False, True):
736 options = {}
737 if stdin_pipe:
738 options['stdin'] = subprocess.PIPE
739 if stdout_pipe:
740 options['stdout'] = subprocess.PIPE
741 if stderr_pipe:
742 options['stderr'] = subprocess.PIPE
743 if not options:
744 continue
745 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
746 p.communicate()
747 if p.stdin is not None:
748 self.assertTrue(p.stdin.closed)
749 if p.stdout is not None:
750 self.assertTrue(p.stdout.closed)
751 if p.stderr is not None:
752 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000753
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000754 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000755 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000756 p = subprocess.Popen([sys.executable, "-c",
757 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000758 (stdout, stderr) = p.communicate()
759 self.assertEqual(stdout, None)
760 self.assertEqual(stderr, None)
761
762 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000763 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000764 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000765 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000766 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000767 os.close(x)
768 os.close(y)
769 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000770 'import sys,os;'
771 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200772 'sys.stderr.write("x" * %d);'
773 'sys.stdout.write(sys.stdin.read())' %
774 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000775 stdin=subprocess.PIPE,
776 stdout=subprocess.PIPE,
777 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000778 self.addCleanup(p.stdout.close)
779 self.addCleanup(p.stderr.close)
780 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200781 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000782 (stdout, stderr) = p.communicate(string_to_write)
783 self.assertEqual(stdout, string_to_write)
784
785 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000786 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000787 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000788 'import sys,os;'
789 'sys.stdout.write(sys.stdin.read())'],
790 stdin=subprocess.PIPE,
791 stdout=subprocess.PIPE,
792 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000793 self.addCleanup(p.stdout.close)
794 self.addCleanup(p.stderr.close)
795 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000796 p.stdin.write(b"banana")
797 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000798 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000799 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000800
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000801 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000802 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000803 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200804 'buf = sys.stdout.buffer;'
805 'buf.write(sys.stdin.readline().encode());'
806 'buf.flush();'
807 'buf.write(b"line2\\n");'
808 'buf.flush();'
809 'buf.write(sys.stdin.read().encode());'
810 'buf.flush();'
811 'buf.write(b"line4\\n");'
812 'buf.flush();'
813 'buf.write(b"line5\\r\\n");'
814 'buf.flush();'
815 'buf.write(b"line6\\r");'
816 'buf.flush();'
817 'buf.write(b"\\nline7");'
818 'buf.flush();'
819 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200820 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000821 stdout=subprocess.PIPE,
822 universal_newlines=1)
Victor Stinner7438c612016-05-20 12:43:15 +0200823 with p:
824 p.stdin.write("line1\n")
825 p.stdin.flush()
826 self.assertEqual(p.stdout.readline(), "line1\n")
827 p.stdin.write("line3\n")
828 p.stdin.close()
829 self.addCleanup(p.stdout.close)
830 self.assertEqual(p.stdout.readline(),
831 "line2\n")
832 self.assertEqual(p.stdout.read(6),
833 "line3\n")
834 self.assertEqual(p.stdout.read(),
835 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000836
837 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000838 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000839 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000840 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200841 'buf = sys.stdout.buffer;'
842 'buf.write(b"line2\\n");'
843 'buf.flush();'
844 'buf.write(b"line4\\n");'
845 'buf.flush();'
846 'buf.write(b"line5\\r\\n");'
847 'buf.flush();'
848 'buf.write(b"line6\\r");'
849 'buf.flush();'
850 'buf.write(b"\\nline7");'
851 'buf.flush();'
852 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200853 stderr=subprocess.PIPE,
854 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000855 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000856 self.addCleanup(p.stdout.close)
857 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000858 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200859 self.assertEqual(stdout,
860 "line2\nline4\nline5\nline6\nline7\nline8")
861
862 def test_universal_newlines_communicate_stdin(self):
863 # universal newlines through communicate(), with only stdin
864 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300865 'import sys,os;' + SETBINARY + textwrap.dedent('''
866 s = sys.stdin.readline()
867 assert s == "line1\\n", repr(s)
868 s = sys.stdin.read()
869 assert s == "line3\\n", repr(s)
870 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200871 stdin=subprocess.PIPE,
872 universal_newlines=1)
873 (stdout, stderr) = p.communicate("line1\nline3\n")
874 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000875
Andrew Svetlovf3765072012-08-14 18:35:17 +0300876 def test_universal_newlines_communicate_input_none(self):
877 # Test communicate(input=None) with universal newlines.
878 #
879 # We set stdout to PIPE because, as of this writing, a different
880 # code path is tested when the number of pipes is zero or one.
881 p = subprocess.Popen([sys.executable, "-c", "pass"],
882 stdin=subprocess.PIPE,
883 stdout=subprocess.PIPE,
884 universal_newlines=True)
885 p.communicate()
886 self.assertEqual(p.returncode, 0)
887
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300888 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300889 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300890 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300891 'import sys,os;' + SETBINARY + textwrap.dedent('''
892 s = sys.stdin.buffer.readline()
893 sys.stdout.buffer.write(s)
894 sys.stdout.buffer.write(b"line2\\r")
895 sys.stderr.buffer.write(b"eline2\\n")
896 s = sys.stdin.buffer.read()
897 sys.stdout.buffer.write(s)
898 sys.stdout.buffer.write(b"line4\\n")
899 sys.stdout.buffer.write(b"line5\\r\\n")
900 sys.stderr.buffer.write(b"eline6\\r")
901 sys.stderr.buffer.write(b"eline7\\r\\nz")
902 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300903 stdin=subprocess.PIPE,
904 stderr=subprocess.PIPE,
905 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300906 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300907 self.addCleanup(p.stdout.close)
908 self.addCleanup(p.stderr.close)
909 (stdout, stderr) = p.communicate("line1\nline3\n")
910 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300911 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300912 # Python debug build push something like "[42442 refs]\n"
913 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300914 # Don't use assertStderrEqual because it strips CR and LF from output.
915 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300916
Andrew Svetlov82860712012-08-19 22:13:41 +0300917 def test_universal_newlines_communicate_encodings(self):
918 # Check that universal newlines mode works for various encodings,
919 # in particular for encodings in the UTF-16 and UTF-32 families.
920 # See issue #15595.
921 #
922 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
923 # without, and UTF-16 and UTF-32.
924 for encoding in ['utf-16', 'utf-32-be']:
Andrew Svetlov82860712012-08-19 22:13:41 +0300925 code = ("import sys; "
926 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
927 encoding)
928 args = [sys.executable, '-c', code]
Steve Dower050acae2016-09-06 20:16:17 -0700929 # We set stdin to be non-None because, as of this writing,
930 # a different code path is used when the number of pipes is
931 # zero or one.
932 popen = subprocess.Popen(args,
933 stdin=subprocess.PIPE,
934 stdout=subprocess.PIPE,
935 encoding=encoding)
936 stdout, stderr = popen.communicate(input='')
Andrew Svetlov82860712012-08-19 22:13:41 +0300937 self.assertEqual(stdout, '1\n2\n3\n4')
938
Steve Dower050acae2016-09-06 20:16:17 -0700939 def test_communicate_errors(self):
940 for errors, expected in [
941 ('ignore', ''),
942 ('replace', '\ufffd\ufffd'),
943 ('surrogateescape', '\udc80\udc80'),
944 ('backslashreplace', '\\x80\\x80'),
945 ]:
946 code = ("import sys; "
947 r"sys.stdout.buffer.write(b'[\x80\x80]')")
948 args = [sys.executable, '-c', code]
949 # We set stdin to be non-None because, as of this writing,
950 # a different code path is used when the number of pipes is
951 # zero or one.
952 popen = subprocess.Popen(args,
953 stdin=subprocess.PIPE,
954 stdout=subprocess.PIPE,
955 encoding='utf-8',
956 errors=errors)
957 stdout, stderr = popen.communicate(input='')
958 self.assertEqual(stdout, '[{}]'.format(expected))
959
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000960 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000961 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000962 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000963 max_handles = 1026 # too much for most UNIX systems
964 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000965 max_handles = 2050 # too much for (at least some) Windows setups
966 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400967 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000968 try:
969 for i in range(max_handles):
970 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400971 tmpfile = os.path.join(tmpdir, support.TESTFN)
972 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000973 except OSError as e:
974 if e.errno != errno.EMFILE:
975 raise
976 break
977 else:
978 self.skipTest("failed to reach the file descriptor limit "
979 "(tried %d)" % max_handles)
980 # Close a couple of them (should be enough for a subprocess)
981 for i in range(10):
982 os.close(handles.pop())
983 # Loop creating some subprocesses. If one of them leaks some fds,
984 # the next loop iteration will fail by reaching the max fd limit.
985 for i in range(15):
986 p = subprocess.Popen([sys.executable, "-c",
987 "import sys;"
988 "sys.stdout.write(sys.stdin.read())"],
989 stdin=subprocess.PIPE,
990 stdout=subprocess.PIPE,
991 stderr=subprocess.PIPE)
992 data = p.communicate(b"lime")[0]
993 self.assertEqual(data, b"lime")
994 finally:
995 for h in handles:
996 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400997 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000998
999 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001000 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
1001 '"a b c" d e')
1002 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
1003 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +00001004 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
1005 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001006 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
1007 'a\\\\\\b "de fg" h')
1008 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
1009 'a\\\\\\"b c d')
1010 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
1011 '"a\\\\b c" d e')
1012 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
1013 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001014 self.assertEqual(subprocess.list2cmdline(['ab', '']),
1015 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001016
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001017 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001018 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +02001019 "import os; os.read(0, 1)"],
1020 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001021 self.addCleanup(p.stdin.close)
1022 self.assertIsNone(p.poll())
1023 os.write(p.stdin.fileno(), b'A')
1024 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001025 # Subsequent invocations should just return the returncode
1026 self.assertEqual(p.poll(), 0)
1027
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001028 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001029 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001030 self.assertEqual(p.wait(), 0)
1031 # Subsequent invocations should just return the returncode
1032 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +00001033
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001034 def test_wait_timeout(self):
1035 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001036 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -04001037 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +02001038 p.wait(timeout=0.0001)
1039 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -04001040 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
1041 # time to start.
1042 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -04001043
Peter Astrand738131d2004-11-30 21:04:45 +00001044 def test_invalid_bufsize(self):
1045 # an invalid type of the bufsize argument should raise
1046 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001047 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +00001048 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001049
Guido van Rossum46a05a72007-06-07 21:56:45 +00001050 def test_bufsize_is_none(self):
1051 # bufsize=None should be the same as bufsize=0.
1052 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
1053 self.assertEqual(p.wait(), 0)
1054 # Again with keyword arg
1055 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
1056 self.assertEqual(p.wait(), 0)
1057
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001058 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1059 # subprocess may deadlock with bufsize=1, see issue #21332
1060 with subprocess.Popen([sys.executable, "-c", "import sys;"
1061 "sys.stdout.write(sys.stdin.readline());"
1062 "sys.stdout.flush()"],
1063 stdin=subprocess.PIPE,
1064 stdout=subprocess.PIPE,
1065 stderr=subprocess.DEVNULL,
1066 bufsize=1,
1067 universal_newlines=universal_newlines) as p:
1068 p.stdin.write(line) # expect that it flushes the line in text mode
1069 os.close(p.stdin.fileno()) # close it without flushing the buffer
1070 read_line = p.stdout.readline()
1071 try:
1072 p.stdin.close()
1073 except OSError:
1074 pass
1075 p.stdin = None
1076 self.assertEqual(p.returncode, 0)
1077 self.assertEqual(read_line, expected)
1078
1079 def test_bufsize_equal_one_text_mode(self):
1080 # line is flushed in text mode with bufsize=1.
1081 # we should get the full line in return
1082 line = "line\n"
1083 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1084
1085 def test_bufsize_equal_one_binary_mode(self):
1086 # line is not flushed in binary mode with bufsize=1.
1087 # we should get empty response
1088 line = b'line' + os.linesep.encode() # assume ascii-based locale
1089 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
1090
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001091 def test_leaking_fds_on_error(self):
1092 # see bug #5179: Popen leaks file descriptors to PIPEs if
1093 # the child fails to execute; this will eventually exhaust
1094 # the maximum number of open fds. 1024 seems a very common
1095 # value for that limit, but Windows has 2048, so we loop
1096 # 1024 times (each call leaked two fds).
1097 for i in range(1024):
Andrew Svetlov3438fa42012-12-17 23:35:18 +02001098 with self.assertRaises(OSError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001099 subprocess.Popen(['nonexisting_i_hope'],
1100 stdout=subprocess.PIPE,
1101 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -04001102 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -04001103 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001104 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001105
Antoine Pitroua8392712013-08-30 23:38:13 +02001106 @unittest.skipIf(threading is None, "threading required")
1107 def test_double_close_on_error(self):
1108 # Issue #18851
1109 fds = []
1110 def open_fds():
1111 for i in range(20):
1112 fds.extend(os.pipe())
1113 time.sleep(0.001)
1114 t = threading.Thread(target=open_fds)
1115 t.start()
1116 try:
1117 with self.assertRaises(EnvironmentError):
1118 subprocess.Popen(['nonexisting_i_hope'],
1119 stdin=subprocess.PIPE,
1120 stdout=subprocess.PIPE,
1121 stderr=subprocess.PIPE)
1122 finally:
1123 t.join()
1124 exc = None
1125 for fd in fds:
1126 # If a double close occurred, some of those fds will
1127 # already have been closed by mistake, and os.close()
1128 # here will raise.
1129 try:
1130 os.close(fd)
1131 except OSError as e:
1132 exc = e
1133 if exc is not None:
1134 raise exc
1135
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001136 @unittest.skipIf(threading is None, "threading required")
1137 def test_threadsafe_wait(self):
1138 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1139 proc = subprocess.Popen([sys.executable, '-c',
1140 'import time; time.sleep(12)'])
1141 self.assertEqual(proc.returncode, None)
1142 results = []
1143
1144 def kill_proc_timer_thread():
1145 results.append(('thread-start-poll-result', proc.poll()))
1146 # terminate it from the thread and wait for the result.
1147 proc.kill()
1148 proc.wait()
1149 results.append(('thread-after-kill-and-wait', proc.returncode))
1150 # this wait should be a no-op given the above.
1151 proc.wait()
1152 results.append(('thread-after-second-wait', proc.returncode))
1153
1154 # This is a timing sensitive test, the failure mode is
1155 # triggered when both the main thread and this thread are in
1156 # the wait() call at once. The delay here is to allow the
1157 # main thread to most likely be blocked in its wait() call.
1158 t = threading.Timer(0.2, kill_proc_timer_thread)
1159 t.start()
1160
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001161 if mswindows:
1162 expected_errorcode = 1
1163 else:
1164 # Should be -9 because of the proc.kill() from the thread.
1165 expected_errorcode = -9
1166
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001167 # Wait for the process to finish; the thread should kill it
1168 # long before it finishes on its own. Supplying a timeout
1169 # triggers a different code path for better coverage.
1170 proc.wait(timeout=20)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001171 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001172 msg="unexpected result in wait from main thread")
1173
1174 # This should be a no-op with no change in returncode.
1175 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001176 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001177 msg="unexpected result in second main wait.")
1178
1179 t.join()
1180 # Ensure that all of the thread results are as expected.
1181 # When a race condition occurs in wait(), the returncode could
1182 # be set by the wrong thread that doesn't actually have it
1183 # leading to an incorrect value.
1184 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001185 ('thread-after-kill-and-wait', expected_errorcode),
1186 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001187 results)
1188
Victor Stinnerb3693582010-05-21 20:13:12 +00001189 def test_issue8780(self):
1190 # Ensure that stdout is inherited from the parent
1191 # if stdout=PIPE is not used
1192 code = ';'.join((
1193 'import subprocess, sys',
1194 'retcode = subprocess.call('
1195 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1196 'assert retcode == 0'))
1197 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001198 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001199
Tim Goldenaf5ac392010-08-06 13:03:56 +00001200 def test_handles_closed_on_exception(self):
1201 # If CreateProcess exits with an error, ensure the
1202 # duplicate output handles are released
Berker Peksag16a1f282015-09-28 13:33:14 +03001203 ifhandle, ifname = tempfile.mkstemp()
1204 ofhandle, ofname = tempfile.mkstemp()
1205 efhandle, efname = tempfile.mkstemp()
Tim Goldenaf5ac392010-08-06 13:03:56 +00001206 try:
1207 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1208 stderr=efhandle)
1209 except OSError:
1210 os.close(ifhandle)
1211 os.remove(ifname)
1212 os.close(ofhandle)
1213 os.remove(ofname)
1214 os.close(efhandle)
1215 os.remove(efname)
1216 self.assertFalse(os.path.exists(ifname))
1217 self.assertFalse(os.path.exists(ofname))
1218 self.assertFalse(os.path.exists(efname))
1219
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001220 def test_communicate_epipe(self):
1221 # Issue 10963: communicate() should hide EPIPE
1222 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1223 stdin=subprocess.PIPE,
1224 stdout=subprocess.PIPE,
1225 stderr=subprocess.PIPE)
1226 self.addCleanup(p.stdout.close)
1227 self.addCleanup(p.stderr.close)
1228 self.addCleanup(p.stdin.close)
1229 p.communicate(b"x" * 2**20)
1230
1231 def test_communicate_epipe_only_stdin(self):
1232 # Issue 10963: communicate() should hide EPIPE
1233 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1234 stdin=subprocess.PIPE)
1235 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001236 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001237 p.communicate(b"x" * 2**20)
1238
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001239 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1240 "Requires signal.SIGUSR1")
1241 @unittest.skipUnless(hasattr(os, 'kill'),
1242 "Requires os.kill")
1243 @unittest.skipUnless(hasattr(os, 'getppid'),
1244 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001245 def test_communicate_eintr(self):
1246 # Issue #12493: communicate() should handle EINTR
1247 def handler(signum, frame):
1248 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001249 old_handler = signal.signal(signal.SIGUSR1, handler)
1250 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001251
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001252 args = [sys.executable, "-c",
1253 'import os, signal;'
1254 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001255 for stream in ('stdout', 'stderr'):
1256 kw = {stream: subprocess.PIPE}
1257 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001258 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001259 process.communicate()
1260
Tim Peterse718f612004-10-12 21:51:32 +00001261
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001262 # This test is Linux-ish specific for simplicity to at least have
1263 # some coverage. It is not a platform specific bug.
1264 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1265 "Linux specific")
1266 def test_failed_child_execute_fd_leak(self):
1267 """Test for the fork() failure fd leak reported in issue16327."""
1268 fd_directory = '/proc/%d/fd' % os.getpid()
1269 fds_before_popen = os.listdir(fd_directory)
1270 with self.assertRaises(PopenTestException):
1271 PopenExecuteChildRaises(
1272 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
1273 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1274
1275 # NOTE: This test doesn't verify that the real _execute_child
1276 # does not close the file descriptors itself on the way out
1277 # during an exception. Code inspection has confirmed that.
1278
1279 fds_after_exception = os.listdir(fd_directory)
1280 self.assertEqual(fds_before_popen, fds_after_exception)
1281
Gregory P. Smith6e730002015-04-14 16:14:25 -07001282
1283class RunFuncTestCase(BaseTestCase):
1284 def run_python(self, code, **kwargs):
1285 """Run Python code in a subprocess using subprocess.run"""
1286 argv = [sys.executable, "-c", code]
1287 return subprocess.run(argv, **kwargs)
1288
1289 def test_returncode(self):
1290 # call() function with sequence argument
1291 cp = self.run_python("import sys; sys.exit(47)")
1292 self.assertEqual(cp.returncode, 47)
1293 with self.assertRaises(subprocess.CalledProcessError):
1294 cp.check_returncode()
1295
1296 def test_check(self):
1297 with self.assertRaises(subprocess.CalledProcessError) as c:
1298 self.run_python("import sys; sys.exit(47)", check=True)
1299 self.assertEqual(c.exception.returncode, 47)
1300
1301 def test_check_zero(self):
1302 # check_returncode shouldn't raise when returncode is zero
1303 cp = self.run_python("import sys; sys.exit(0)", check=True)
1304 self.assertEqual(cp.returncode, 0)
1305
1306 def test_timeout(self):
1307 # run() function with timeout argument; we want to test that the child
1308 # process gets killed when the timeout expires. If the child isn't
1309 # killed, this call will deadlock since subprocess.run waits for the
1310 # child.
1311 with self.assertRaises(subprocess.TimeoutExpired):
1312 self.run_python("while True: pass", timeout=0.0001)
1313
1314 def test_capture_stdout(self):
1315 # capture stdout with zero return code
1316 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1317 self.assertIn(b'BDFL', cp.stdout)
1318
1319 def test_capture_stderr(self):
1320 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1321 stderr=subprocess.PIPE)
1322 self.assertIn(b'BDFL', cp.stderr)
1323
1324 def test_check_output_stdin_arg(self):
1325 # run() can be called with stdin set to a file
1326 tf = tempfile.TemporaryFile()
1327 self.addCleanup(tf.close)
1328 tf.write(b'pear')
1329 tf.seek(0)
1330 cp = self.run_python(
1331 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1332 stdin=tf, stdout=subprocess.PIPE)
1333 self.assertIn(b'PEAR', cp.stdout)
1334
1335 def test_check_output_input_arg(self):
1336 # check_output() can be called with input set to a string
1337 cp = self.run_python(
1338 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1339 input=b'pear', stdout=subprocess.PIPE)
1340 self.assertIn(b'PEAR', cp.stdout)
1341
1342 def test_check_output_stdin_with_input_arg(self):
1343 # run() refuses to accept 'stdin' with 'input'
1344 tf = tempfile.TemporaryFile()
1345 self.addCleanup(tf.close)
1346 tf.write(b'pear')
1347 tf.seek(0)
1348 with self.assertRaises(ValueError,
1349 msg="Expected ValueError when stdin and input args supplied.") as c:
1350 output = self.run_python("print('will not be run')",
1351 stdin=tf, input=b'hare')
1352 self.assertIn('stdin', c.exception.args[0])
1353 self.assertIn('input', c.exception.args[0])
1354
1355 def test_check_output_timeout(self):
1356 with self.assertRaises(subprocess.TimeoutExpired) as c:
1357 cp = self.run_python((
1358 "import sys, time\n"
1359 "sys.stdout.write('BDFL')\n"
1360 "sys.stdout.flush()\n"
1361 "time.sleep(3600)"),
1362 # Some heavily loaded buildbots (sparc Debian 3.x) require
1363 # this much time to start and print.
1364 timeout=3, stdout=subprocess.PIPE)
1365 self.assertEqual(c.exception.output, b'BDFL')
1366 # output is aliased to stdout
1367 self.assertEqual(c.exception.stdout, b'BDFL')
1368
1369 def test_run_kwargs(self):
1370 newenv = os.environ.copy()
1371 newenv["FRUIT"] = "banana"
1372 cp = self.run_python(('import sys, os;'
1373 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1374 env=newenv)
1375 self.assertEqual(cp.returncode, 33)
1376
1377
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001378@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001379class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001380
Gregory P. Smith5591b022012-10-10 03:34:47 -07001381 def setUp(self):
1382 super().setUp()
1383 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1384
1385 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001386 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001387 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001388 except OSError as e:
1389 # This avoids hard coding the errno value or the OS perror()
1390 # string and instead capture the exception that we want to see
1391 # below for comparison.
1392 desired_exception = e
Gregory P. Smith5591b022012-10-10 03:34:47 -07001393 desired_exception.strerror += ': ' + repr(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001394 else:
Martin Pantereb995702016-07-28 01:11:04 +00001395 self.fail("chdir to nonexistent directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001396 self._nonexistent_dir)
1397 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001398
Gregory P. Smith5591b022012-10-10 03:34:47 -07001399 def test_exception_cwd(self):
1400 """Test error in the child raised in the parent for a bad cwd."""
1401 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001402 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001403 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001404 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001405 except OSError as e:
1406 # Test that the child process chdir failure actually makes
1407 # it up to the parent process as the correct exception.
1408 self.assertEqual(desired_exception.errno, e.errno)
1409 self.assertEqual(desired_exception.strerror, e.strerror)
1410 else:
1411 self.fail("Expected OSError: %s" % desired_exception)
1412
Gregory P. Smith5591b022012-10-10 03:34:47 -07001413 def test_exception_bad_executable(self):
1414 """Test error in the child raised in the parent for a bad executable."""
1415 desired_exception = self._get_chdir_exception()
1416 try:
1417 p = subprocess.Popen([sys.executable, "-c", ""],
1418 executable=self._nonexistent_dir)
1419 except OSError as e:
1420 # Test that the child process exec failure actually makes
1421 # it up to the parent process as the correct exception.
1422 self.assertEqual(desired_exception.errno, e.errno)
1423 self.assertEqual(desired_exception.strerror, e.strerror)
1424 else:
1425 self.fail("Expected OSError: %s" % desired_exception)
1426
1427 def test_exception_bad_args_0(self):
1428 """Test error in the child raised in the parent for a bad args[0]."""
1429 desired_exception = self._get_chdir_exception()
1430 try:
1431 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1432 except OSError as e:
1433 # Test that the child process exec failure actually makes
1434 # it up to the parent process as the correct exception.
1435 self.assertEqual(desired_exception.errno, e.errno)
1436 self.assertEqual(desired_exception.strerror, e.strerror)
1437 else:
1438 self.fail("Expected OSError: %s" % desired_exception)
1439
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001440 def test_restore_signals(self):
1441 # Code coverage for both values of restore_signals to make sure it
1442 # at least does not blow up.
1443 # A test for behavior would be complex. Contributions welcome.
1444 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1445 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1446
1447 def test_start_new_session(self):
1448 # For code coverage of calling setsid(). We don't care if we get an
1449 # EPERM error from it depending on the test execution environment, that
1450 # still indicates that it was called.
1451 try:
1452 output = subprocess.check_output(
1453 [sys.executable, "-c",
1454 "import os; print(os.getpgid(os.getpid()))"],
1455 start_new_session=True)
1456 except OSError as e:
1457 if e.errno != errno.EPERM:
1458 raise
1459 else:
1460 parent_pgid = os.getpgid(os.getpid())
1461 child_pgid = int(output)
1462 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001463
1464 def test_run_abort(self):
1465 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001466 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001467 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001468 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001469 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001470 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001471
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001472 def test_CalledProcessError_str_signal(self):
1473 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
1474 error_string = str(err)
1475 # We're relying on the repr() of the signal.Signals intenum to provide
1476 # the word signal, the signal name and the numeric value.
1477 self.assertIn("signal", error_string.lower())
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)b4149062016-06-03 06:19:35 +00001478 # We're not being specific about the signal name as some signals have
1479 # multiple names and which name is revealed can vary.
1480 self.assertIn("SIG", error_string)
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)d6da7602016-06-03 06:14:06 +00001481 self.assertIn(str(signal.SIGABRT), error_string)
1482
1483 def test_CalledProcessError_str_unknown_signal(self):
1484 err = subprocess.CalledProcessError(-9876543, "fake cmd")
1485 error_string = str(err)
1486 self.assertIn("unknown signal 9876543.", error_string)
1487
1488 def test_CalledProcessError_str_non_zero(self):
1489 err = subprocess.CalledProcessError(2, "fake cmd")
1490 error_string = str(err)
1491 self.assertIn("non-zero exit status 2.", error_string)
1492
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001493 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001494 # DISCLAIMER: Setting environment variables is *not* a good use
1495 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001496 p = subprocess.Popen([sys.executable, "-c",
1497 'import sys,os;'
1498 'sys.stdout.write(os.getenv("FRUIT"))'],
1499 stdout=subprocess.PIPE,
1500 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Victor Stinner7438c612016-05-20 12:43:15 +02001501 with p:
1502 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001503
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001504 def test_preexec_exception(self):
1505 def raise_it():
1506 raise ValueError("What if two swallows carried a coconut?")
1507 try:
1508 p = subprocess.Popen([sys.executable, "-c", ""],
1509 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001510 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001511 self.assertTrue(
1512 subprocess._posixsubprocess,
1513 "Expected a ValueError from the preexec_fn")
1514 except ValueError as e:
1515 self.assertIn("coconut", e.args[0])
1516 else:
1517 self.fail("Exception raised by preexec_fn did not make it "
1518 "to the parent process.")
1519
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001520 class _TestExecuteChildPopen(subprocess.Popen):
1521 """Used to test behavior at the end of _execute_child."""
1522 def __init__(self, testcase, *args, **kwargs):
1523 self._testcase = testcase
1524 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001525
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001526 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001527 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001528 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001529 finally:
1530 # Open a bunch of file descriptors and verify that
1531 # none of them are the same as the ones the Popen
1532 # instance is using for stdin/stdout/stderr.
1533 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1534 for _ in range(8)]
1535 try:
1536 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001537 self._testcase.assertNotIn(
1538 fd, (self.stdin.fileno(), self.stdout.fileno(),
1539 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001540 msg="At least one fd was closed early.")
1541 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01001542 for fd in devzero_fds:
1543 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001544
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001545 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1546 def test_preexec_errpipe_does_not_double_close_pipes(self):
1547 """Issue16140: Don't double close pipes on preexec error."""
1548
1549 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08001550 raise subprocess.SubprocessError(
1551 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001552
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08001553 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001554 self._TestExecuteChildPopen(
1555 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001556 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1557 stderr=subprocess.PIPE, preexec_fn=raise_it)
1558
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001559 def test_preexec_gc_module_failure(self):
1560 # This tests the code that disables garbage collection if the child
1561 # process will execute any Python.
1562 def raise_runtime_error():
1563 raise RuntimeError("this shouldn't escape")
1564 enabled = gc.isenabled()
1565 orig_gc_disable = gc.disable
1566 orig_gc_isenabled = gc.isenabled
1567 try:
1568 gc.disable()
1569 self.assertFalse(gc.isenabled())
1570 subprocess.call([sys.executable, '-c', ''],
1571 preexec_fn=lambda: None)
1572 self.assertFalse(gc.isenabled(),
1573 "Popen enabled gc when it shouldn't.")
1574
1575 gc.enable()
1576 self.assertTrue(gc.isenabled())
1577 subprocess.call([sys.executable, '-c', ''],
1578 preexec_fn=lambda: None)
1579 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1580
1581 gc.disable = raise_runtime_error
1582 self.assertRaises(RuntimeError, subprocess.Popen,
1583 [sys.executable, '-c', ''],
1584 preexec_fn=lambda: None)
1585
1586 del gc.isenabled # force an AttributeError
1587 self.assertRaises(AttributeError, subprocess.Popen,
1588 [sys.executable, '-c', ''],
1589 preexec_fn=lambda: None)
1590 finally:
1591 gc.disable = orig_gc_disable
1592 gc.isenabled = orig_gc_isenabled
1593 if not enabled:
1594 gc.disable()
1595
Martin Panterf7fdbda2015-12-05 09:51:52 +00001596 @unittest.skipIf(
1597 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
Martin Panterafdd5132015-11-30 02:21:41 +00001598 def test_preexec_fork_failure(self):
1599 # The internal code did not preserve the previous exception when
1600 # re-enabling garbage collection
1601 try:
1602 from resource import getrlimit, setrlimit, RLIMIT_NPROC
1603 except ImportError as err:
1604 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
1605 limits = getrlimit(RLIMIT_NPROC)
1606 [_, hard] = limits
1607 setrlimit(RLIMIT_NPROC, (0, hard))
1608 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
Martin Panter5cf791b2015-12-11 05:40:14 +00001609 try:
Martin Panterafdd5132015-11-30 02:21:41 +00001610 subprocess.call([sys.executable, '-c', ''],
1611 preexec_fn=lambda: None)
Martin Panter5cf791b2015-12-11 05:40:14 +00001612 except BlockingIOError:
1613 # Forking should raise EAGAIN, translated to BlockingIOError
1614 pass
1615 else:
1616 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
Martin Panterafdd5132015-11-30 02:21:41 +00001617
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001618 def test_args_string(self):
1619 # args is a string
Berker Peksag16a1f282015-09-28 13:33:14 +03001620 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001621 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001622 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001623 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001624 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1625 sys.executable)
1626 os.chmod(fname, 0o700)
1627 p = subprocess.Popen(fname)
1628 p.wait()
1629 os.remove(fname)
1630 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001631
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001632 def test_invalid_args(self):
1633 # invalid arguments should raise ValueError
1634 self.assertRaises(ValueError, subprocess.call,
1635 [sys.executable, "-c",
1636 "import sys; sys.exit(47)"],
1637 startupinfo=47)
1638 self.assertRaises(ValueError, subprocess.call,
1639 [sys.executable, "-c",
1640 "import sys; sys.exit(47)"],
1641 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001642
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001643 def test_shell_sequence(self):
1644 # Run command through the shell (sequence)
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")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001652
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001653 def test_shell_string(self):
1654 # Run command through the shell (string)
1655 newenv = os.environ.copy()
1656 newenv["FRUIT"] = "apple"
1657 p = subprocess.Popen("echo $FRUIT", shell=1,
1658 stdout=subprocess.PIPE,
1659 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02001660 with p:
1661 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001662
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001663 def test_call_string(self):
1664 # call() function with string argument on UNIX
Berker Peksag16a1f282015-09-28 13:33:14 +03001665 fd, fname = tempfile.mkstemp()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001666 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001667 with open(fd, "w", errors="surrogateescape") as fobj:
Xavier de Gayed1415312016-07-22 12:15:29 +02001668 fobj.write("#!%s\n" % support.unix_shell)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001669 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1670 sys.executable)
1671 os.chmod(fname, 0o700)
1672 rc = subprocess.call(fname)
1673 os.remove(fname)
1674 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001675
Stefan Krah9542cc62010-07-19 14:20:53 +00001676 def test_specific_shell(self):
1677 # Issue #9265: Incorrect name passed as arg[0].
1678 shells = []
1679 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1680 for name in ['bash', 'ksh']:
1681 sh = os.path.join(prefix, name)
1682 if os.path.isfile(sh):
1683 shells.append(sh)
1684 if not shells: # Will probably work for any shell but csh.
1685 self.skipTest("bash or ksh required for this test")
1686 sh = '/bin/sh'
1687 if os.path.isfile(sh) and not os.path.islink(sh):
1688 # Test will fail if /bin/sh is a symlink to csh.
1689 shells.append(sh)
1690 for sh in shells:
1691 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1692 stdout=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02001693 with p:
1694 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
Stefan Krah9542cc62010-07-19 14:20:53 +00001695
Florent Xicluna4886d242010-03-08 13:27:26 +00001696 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001697 # Do not inherit file handles from the parent.
1698 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07001699 # Also set the SIGINT handler to the default to make sure it's not
1700 # being ignored (some tests rely on that.)
1701 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
1702 try:
1703 p = subprocess.Popen([sys.executable, "-c", """if 1:
1704 import sys, time
1705 sys.stdout.write('x\\n')
1706 sys.stdout.flush()
1707 time.sleep(30)
1708 """],
1709 close_fds=True,
1710 stdin=subprocess.PIPE,
1711 stdout=subprocess.PIPE,
1712 stderr=subprocess.PIPE)
1713 finally:
1714 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001715 # Wait for the interpreter to be completely initialized before
1716 # sending any signal.
1717 p.stdout.read(1)
1718 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001719 return p
1720
Charles-François Natali53221e32013-01-12 16:52:20 +01001721 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1722 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001723 def _kill_dead_process(self, method, *args):
1724 # Do not inherit file handles from the parent.
1725 # It should fix failures on some platforms.
1726 p = subprocess.Popen([sys.executable, "-c", """if 1:
1727 import sys, time
1728 sys.stdout.write('x\\n')
1729 sys.stdout.flush()
1730 """],
1731 close_fds=True,
1732 stdin=subprocess.PIPE,
1733 stdout=subprocess.PIPE,
1734 stderr=subprocess.PIPE)
1735 # Wait for the interpreter to be completely initialized before
1736 # sending any signal.
1737 p.stdout.read(1)
1738 # The process should end after this
1739 time.sleep(1)
1740 # This shouldn't raise even though the child is now dead
1741 getattr(p, method)(*args)
1742 p.communicate()
1743
Florent Xicluna4886d242010-03-08 13:27:26 +00001744 def test_send_signal(self):
1745 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001746 _, stderr = p.communicate()
1747 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001748 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001749
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001750 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001751 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001752 _, stderr = p.communicate()
1753 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001754 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001755
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001756 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001757 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001758 _, stderr = p.communicate()
1759 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001760 self.assertEqual(p.wait(), -signal.SIGTERM)
1761
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001762 def test_send_signal_dead(self):
1763 # Sending a signal to a dead process
1764 self._kill_dead_process('send_signal', signal.SIGINT)
1765
1766 def test_kill_dead(self):
1767 # Killing a dead process
1768 self._kill_dead_process('kill')
1769
1770 def test_terminate_dead(self):
1771 # Terminating a dead process
1772 self._kill_dead_process('terminate')
1773
Victor Stinnerdaf45552013-08-28 00:53:59 +02001774 def _save_fds(self, save_fds):
1775 fds = []
1776 for fd in save_fds:
1777 inheritable = os.get_inheritable(fd)
1778 saved = os.dup(fd)
1779 fds.append((fd, saved, inheritable))
1780 return fds
1781
1782 def _restore_fds(self, fds):
1783 for fd, saved, inheritable in fds:
1784 os.dup2(saved, fd, inheritable=inheritable)
1785 os.close(saved)
1786
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001787 def check_close_std_fds(self, fds):
1788 # Issue #9905: test that subprocess pipes still work properly with
1789 # some standard fds closed
1790 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02001791 saved_fds = self._save_fds(fds)
1792 for fd, saved, inheritable in saved_fds:
1793 if fd == 0:
1794 stdin = saved
1795 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001796 try:
1797 for fd in fds:
1798 os.close(fd)
1799 out, err = subprocess.Popen([sys.executable, "-c",
1800 'import sys;'
1801 'sys.stdout.write("apple");'
1802 'sys.stdout.flush();'
1803 'sys.stderr.write("orange")'],
1804 stdin=stdin,
1805 stdout=subprocess.PIPE,
1806 stderr=subprocess.PIPE).communicate()
1807 err = support.strip_python_stderr(err)
1808 self.assertEqual((out, err), (b'apple', b'orange'))
1809 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001810 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001811
1812 def test_close_fd_0(self):
1813 self.check_close_std_fds([0])
1814
1815 def test_close_fd_1(self):
1816 self.check_close_std_fds([1])
1817
1818 def test_close_fd_2(self):
1819 self.check_close_std_fds([2])
1820
1821 def test_close_fds_0_1(self):
1822 self.check_close_std_fds([0, 1])
1823
1824 def test_close_fds_0_2(self):
1825 self.check_close_std_fds([0, 2])
1826
1827 def test_close_fds_1_2(self):
1828 self.check_close_std_fds([1, 2])
1829
1830 def test_close_fds_0_1_2(self):
1831 # Issue #10806: test that subprocess pipes still work properly with
1832 # all standard fds closed.
1833 self.check_close_std_fds([0, 1, 2])
1834
Gregory P. Smith53dd8162013-12-01 16:03:24 -08001835 def test_small_errpipe_write_fd(self):
1836 """Issue #15798: Popen should work when stdio fds are available."""
1837 new_stdin = os.dup(0)
1838 new_stdout = os.dup(1)
1839 try:
1840 os.close(0)
1841 os.close(1)
1842
1843 # Side test: if errpipe_write fails to have its CLOEXEC
1844 # flag set this should cause the parent to think the exec
1845 # failed. Extremely unlikely: everyone supports CLOEXEC.
1846 subprocess.Popen([
1847 sys.executable, "-c",
1848 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
1849 finally:
1850 # Restore original stdin and stdout
1851 os.dup2(new_stdin, 0)
1852 os.dup2(new_stdout, 1)
1853 os.close(new_stdin)
1854 os.close(new_stdout)
1855
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001856 def test_remapping_std_fds(self):
1857 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03001858 temps = [tempfile.mkstemp() for i in range(3)]
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001859 try:
1860 temp_fds = [fd for fd, fname in temps]
1861
1862 # unlink the files -- we won't need to reopen them
1863 for fd, fname in temps:
1864 os.unlink(fname)
1865
1866 # write some data to what will become stdin, and rewind
1867 os.write(temp_fds[1], b"STDIN")
1868 os.lseek(temp_fds[1], 0, 0)
1869
1870 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02001871 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001872 try:
1873 # duplicate the file objects over the standard fd's
1874 for fd, temp_fd in enumerate(temp_fds):
1875 os.dup2(temp_fd, fd)
1876
1877 # now use those files in the "wrong" order, so that subprocess
1878 # has to rearrange them in the child
1879 p = subprocess.Popen([sys.executable, "-c",
1880 'import sys; got = sys.stdin.read();'
1881 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1882 stdin=temp_fds[1],
1883 stdout=temp_fds[2],
1884 stderr=temp_fds[0])
1885 p.wait()
1886 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001887 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001888
1889 for fd in temp_fds:
1890 os.lseek(fd, 0, 0)
1891
1892 out = os.read(temp_fds[2], 1024)
1893 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1894 self.assertEqual(out, b"got STDIN")
1895 self.assertEqual(err, b"err")
1896
1897 finally:
1898 for fd in temp_fds:
1899 os.close(fd)
1900
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001901 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1902 # open up some temporary files
Berker Peksag16a1f282015-09-28 13:33:14 +03001903 temps = [tempfile.mkstemp() for i in range(3)]
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001904 temp_fds = [fd for fd, fname in temps]
1905 try:
1906 # unlink the files -- we won't need to reopen them
1907 for fd, fname in temps:
1908 os.unlink(fname)
1909
1910 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02001911 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001912 try:
1913 # duplicate the temp files over the standard fd's 0, 1, 2
1914 for fd, temp_fd in enumerate(temp_fds):
1915 os.dup2(temp_fd, fd)
1916
1917 # write some data to what will become stdin, and rewind
1918 os.write(stdin_no, b"STDIN")
1919 os.lseek(stdin_no, 0, 0)
1920
1921 # now use those files in the given order, so that subprocess
1922 # has to rearrange them in the child
1923 p = subprocess.Popen([sys.executable, "-c",
1924 'import sys; got = sys.stdin.read();'
1925 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1926 stdin=stdin_no,
1927 stdout=stdout_no,
1928 stderr=stderr_no)
1929 p.wait()
1930
1931 for fd in temp_fds:
1932 os.lseek(fd, 0, 0)
1933
1934 out = os.read(stdout_no, 1024)
1935 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1936 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001937 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001938
1939 self.assertEqual(out, b"got STDIN")
1940 self.assertEqual(err, b"err")
1941
1942 finally:
1943 for fd in temp_fds:
1944 os.close(fd)
1945
1946 # When duping fds, if there arises a situation where one of the fds is
1947 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1948 # This tests all combinations of this.
1949 def test_swap_fds(self):
1950 self.check_swap_fds(0, 1, 2)
1951 self.check_swap_fds(0, 2, 1)
1952 self.check_swap_fds(1, 0, 2)
1953 self.check_swap_fds(1, 2, 0)
1954 self.check_swap_fds(2, 0, 1)
1955 self.check_swap_fds(2, 1, 0)
1956
Victor Stinner13bb71c2010-04-23 21:41:56 +00001957 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001958 def prepare():
1959 raise ValueError("surrogate:\uDCff")
1960
1961 try:
1962 subprocess.call(
1963 [sys.executable, "-c", "pass"],
1964 preexec_fn=prepare)
1965 except ValueError as err:
1966 # Pure Python implementations keeps the message
1967 self.assertIsNone(subprocess._posixsubprocess)
1968 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001969 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00001970 # _posixsubprocess uses a default message
1971 self.assertIsNotNone(subprocess._posixsubprocess)
1972 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1973 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001974 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00001975
Victor Stinner13bb71c2010-04-23 21:41:56 +00001976 def test_undecodable_env(self):
1977 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01001978 encoded_value = value.encode("ascii", "surrogateescape")
1979
Victor Stinner13bb71c2010-04-23 21:41:56 +00001980 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001981 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001982 env = os.environ.copy()
1983 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01001984 # Use C locale to get ASCII for the locale encoding to force
Victor Stinner89f3ad12010-10-14 10:43:31 +00001985 # surrogate-escaping of \xFF in the child process; otherwise it can
1986 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001987 env['LC_ALL'] = 'C'
Victor Stinner5323fb02013-11-19 23:46:06 +01001988 if sys.platform.startswith("aix"):
1989 # On AIX, the C locale uses the Latin1 encoding
1990 decoded_value = encoded_value.decode("latin1", "surrogateescape")
1991 else:
1992 # On other UNIXes, the C locale uses the ASCII encoding
1993 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001994 stdout = subprocess.check_output(
1995 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001996 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001997 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01001998 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001999
2000 # test bytes
2001 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00002002 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002003 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01002004 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00002005 stdout = subprocess.check_output(
2006 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00002007 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00002008 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01002009 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00002010
Victor Stinnerb745a742010-05-18 17:17:23 +00002011 def test_bytes_program(self):
2012 abs_program = os.fsencode(sys.executable)
2013 path, program = os.path.split(sys.executable)
2014 program = os.fsencode(program)
2015
2016 # absolute bytes path
2017 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00002018 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002019
Victor Stinner7b3b20a2011-03-03 12:54:05 +00002020 # absolute bytes path as a string
2021 cmd = b"'" + abs_program + b"' -c pass"
2022 exitcode = subprocess.call(cmd, shell=True)
2023 self.assertEqual(exitcode, 0)
2024
Victor Stinnerb745a742010-05-18 17:17:23 +00002025 # bytes program, unicode PATH
2026 env = os.environ.copy()
2027 env["PATH"] = path
2028 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002029 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002030
2031 # bytes program, bytes PATH
2032 envb = os.environb.copy()
2033 envb[b"PATH"] = os.fsencode(path)
2034 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002035 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00002036
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002037 def test_pipe_cloexec(self):
2038 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2039 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2040
2041 p1 = subprocess.Popen([sys.executable, sleeper],
2042 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2043 stderr=subprocess.PIPE, close_fds=False)
2044
2045 self.addCleanup(p1.communicate, b'')
2046
2047 p2 = subprocess.Popen([sys.executable, fd_status],
2048 stdout=subprocess.PIPE, close_fds=False)
2049
2050 output, error = p2.communicate()
2051 result_fds = set(map(int, output.split(b',')))
2052 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2053 p1.stderr.fileno()])
2054
2055 self.assertFalse(result_fds & unwanted_fds,
2056 "Expected no fds from %r to be open in child, "
2057 "found %r" %
2058 (unwanted_fds, result_fds & unwanted_fds))
2059
2060 def test_pipe_cloexec_real_tools(self):
2061 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2062 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2063
2064 subdata = b'zxcvbn'
2065 data = subdata * 4 + b'\n'
2066
2067 p1 = subprocess.Popen([sys.executable, qcat],
2068 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2069 close_fds=False)
2070
2071 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2072 stdin=p1.stdout, stdout=subprocess.PIPE,
2073 close_fds=False)
2074
2075 self.addCleanup(p1.wait)
2076 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08002077 def kill_p1():
2078 try:
2079 p1.terminate()
2080 except ProcessLookupError:
2081 pass
2082 def kill_p2():
2083 try:
2084 p2.terminate()
2085 except ProcessLookupError:
2086 pass
2087 self.addCleanup(kill_p1)
2088 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002089
2090 p1.stdin.write(data)
2091 p1.stdin.close()
2092
2093 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2094
2095 self.assertTrue(readfiles, "The child hung")
2096 self.assertEqual(p2.stdout.read(), data)
2097
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002098 p1.stdout.close()
2099 p2.stdout.close()
2100
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002101 def test_close_fds(self):
2102 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2103
2104 fds = os.pipe()
2105 self.addCleanup(os.close, fds[0])
2106 self.addCleanup(os.close, fds[1])
2107
2108 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002109 # add a bunch more fds
2110 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002111 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002112 self.addCleanup(os.close, fd)
2113 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002114
Victor Stinnerdaf45552013-08-28 00:53:59 +02002115 for fd in open_fds:
2116 os.set_inheritable(fd, True)
2117
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002118 p = subprocess.Popen([sys.executable, fd_status],
2119 stdout=subprocess.PIPE, close_fds=False)
2120 output, ignored = p.communicate()
2121 remaining_fds = set(map(int, output.split(b',')))
2122
2123 self.assertEqual(remaining_fds & open_fds, open_fds,
2124 "Some fds were closed")
2125
2126 p = subprocess.Popen([sys.executable, fd_status],
2127 stdout=subprocess.PIPE, close_fds=True)
2128 output, ignored = p.communicate()
2129 remaining_fds = set(map(int, output.split(b',')))
2130
2131 self.assertFalse(remaining_fds & open_fds,
2132 "Some fds were left open")
2133 self.assertIn(1, remaining_fds, "Subprocess failed")
2134
Gregory P. Smith8facece2012-01-21 14:01:08 -08002135 # Keep some of the fd's we opened open in the subprocess.
2136 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2137 fds_to_keep = set(open_fds.pop() for _ in range(8))
2138 p = subprocess.Popen([sys.executable, fd_status],
2139 stdout=subprocess.PIPE, close_fds=True,
2140 pass_fds=())
2141 output, ignored = p.communicate()
2142 remaining_fds = set(map(int, output.split(b',')))
2143
2144 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
2145 "Some fds not in pass_fds were left open")
2146 self.assertIn(1, remaining_fds, "Subprocess failed")
2147
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002148
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002149 @unittest.skipIf(sys.platform.startswith("freebsd") and
2150 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2151 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002152 def test_close_fds_when_max_fd_is_lowered(self):
2153 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2154 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2155
Gregory P. Smith634aa682014-06-15 17:51:04 -07002156 # This launches the meat of the test in a child process to
2157 # avoid messing with the larger unittest processes maximum
2158 # number of file descriptors.
2159 # This process launches:
2160 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2161 # a bunch of high open fds above the new lower rlimit.
2162 # Those are reported via stdout before launching a new
2163 # process with close_fds=False to run the actual test:
2164 # +--> The TEST: This one launches a fd_status.py
2165 # subprocess with close_fds=True so we can find out if
2166 # any of the fds above the lowered rlimit are still open.
2167 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2168 '''
2169 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002170 open_fds = set()
2171 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002172 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002173 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002174 open_fds.add(fd)
2175
2176 # Leave a two pairs of low ones available for use by the
2177 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002178 # We also leave 10 more open as some Python buildbots run into
2179 # "too many open files" errors during the test if we do not.
2180 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002181 os.close(fd)
2182 open_fds.remove(fd)
2183
2184 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002185 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002186 os.set_inheritable(fd, True)
2187
2188 max_fd_open = max(open_fds)
2189
Gregory P. Smith634aa682014-06-15 17:51:04 -07002190 # Communicate the open_fds to the parent unittest.TestCase process.
2191 print(','.join(map(str, sorted(open_fds))))
2192 sys.stdout.flush()
2193
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002194 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2195 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002196 # 29 is lower than the highest fds we are leaving open.
2197 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002198 # Launch a new Python interpreter with our low fd rlim_cur that
2199 # inherits open fds above that limit. It then uses subprocess
2200 # with close_fds=True to get a report of open fds in the child.
2201 # An explicit list of fds to check is passed to fd_status.py as
2202 # letting fd_status rely on its default logic would miss the
2203 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002204 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002205 [sys.executable, '-c',
2206 textwrap.dedent("""
2207 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002208 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002209 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002210 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002211 """.format(max_fd=max_fd_open+1))],
2212 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002213 finally:
2214 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002215 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002216
2217 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002218 output_lines = output.splitlines()
2219 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002220 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002221 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2222 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002223
Gregory P. Smith634aa682014-06-15 17:51:04 -07002224 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002225 msg="Some fds were left open.")
2226
2227
Victor Stinner88701e22011-06-01 13:13:04 +02002228 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2229 # descriptor of a pipe closed in the parent process is valid in the
2230 # child process according to fstat(), but the mode of the file
2231 # descriptor is invalid, and read or write raise an error.
2232 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002233 def test_pass_fds(self):
2234 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2235
2236 open_fds = set()
2237
2238 for x in range(5):
2239 fds = os.pipe()
2240 self.addCleanup(os.close, fds[0])
2241 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002242 os.set_inheritable(fds[0], True)
2243 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002244 open_fds.update(fds)
2245
2246 for fd in open_fds:
2247 p = subprocess.Popen([sys.executable, fd_status],
2248 stdout=subprocess.PIPE, close_fds=True,
2249 pass_fds=(fd, ))
2250 output, ignored = p.communicate()
2251
2252 remaining_fds = set(map(int, output.split(b',')))
2253 to_be_closed = open_fds - {fd}
2254
2255 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2256 self.assertFalse(remaining_fds & to_be_closed,
2257 "fd to be closed passed")
2258
2259 # pass_fds overrides close_fds with a warning.
2260 with self.assertWarns(RuntimeWarning) as context:
2261 self.assertFalse(subprocess.call(
2262 [sys.executable, "-c", "import sys; sys.exit(0)"],
2263 close_fds=False, pass_fds=(fd, )))
2264 self.assertIn('overriding close_fds', str(context.warning))
2265
Victor Stinnerdaf45552013-08-28 00:53:59 +02002266 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002267 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002268
2269 inheritable, non_inheritable = os.pipe()
2270 self.addCleanup(os.close, inheritable)
2271 self.addCleanup(os.close, non_inheritable)
2272 os.set_inheritable(inheritable, True)
2273 os.set_inheritable(non_inheritable, False)
2274 pass_fds = (inheritable, non_inheritable)
2275 args = [sys.executable, script]
2276 args += list(map(str, pass_fds))
2277
2278 p = subprocess.Popen(args,
2279 stdout=subprocess.PIPE, close_fds=True,
2280 pass_fds=pass_fds)
2281 output, ignored = p.communicate()
2282 fds = set(map(int, output.split(b',')))
2283
2284 # the inheritable file descriptor must be inherited, so its inheritable
2285 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002286 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002287
2288 # inheritable flag must not be changed in the parent process
2289 self.assertEqual(os.get_inheritable(inheritable), True)
2290 self.assertEqual(os.get_inheritable(non_inheritable), False)
2291
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002292 def test_stdout_stdin_are_single_inout_fd(self):
2293 with io.open(os.devnull, "r+") as inout:
2294 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2295 stdout=inout, stdin=inout)
2296 p.wait()
2297
2298 def test_stdout_stderr_are_single_inout_fd(self):
2299 with io.open(os.devnull, "r+") as inout:
2300 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2301 stdout=inout, stderr=inout)
2302 p.wait()
2303
2304 def test_stderr_stdin_are_single_inout_fd(self):
2305 with io.open(os.devnull, "r+") as inout:
2306 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2307 stderr=inout, stdin=inout)
2308 p.wait()
2309
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002310 def test_wait_when_sigchild_ignored(self):
2311 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2312 sigchild_ignore = support.findfile("sigchild_ignore.py",
2313 subdir="subprocessdata")
2314 p = subprocess.Popen([sys.executable, sigchild_ignore],
2315 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2316 stdout, stderr = p.communicate()
2317 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002318 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002319 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002320
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002321 def test_select_unbuffered(self):
2322 # Issue #11459: bufsize=0 should really set the pipes as
2323 # unbuffered (and therefore let select() work properly).
2324 select = support.import_module("select")
2325 p = subprocess.Popen([sys.executable, "-c",
2326 'import sys;'
2327 'sys.stdout.write("apple")'],
2328 stdout=subprocess.PIPE,
2329 bufsize=0)
2330 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002331 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002332 try:
2333 self.assertEqual(f.read(4), b"appl")
2334 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2335 finally:
2336 p.wait()
2337
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002338 def test_zombie_fast_process_del(self):
2339 # Issue #12650: on Unix, if Popen.__del__() was called before the
2340 # process exited, it wouldn't be added to subprocess._active, and would
2341 # remain a zombie.
2342 # spawn a Popen, and delete its reference before it exits
2343 p = subprocess.Popen([sys.executable, "-c",
2344 'import sys, time;'
2345 'time.sleep(0.2)'],
2346 stdout=subprocess.PIPE,
2347 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002348 self.addCleanup(p.stdout.close)
2349 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002350 ident = id(p)
2351 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002352 with support.check_warnings(('', ResourceWarning)):
2353 p = None
2354
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002355 # check that p is in the active processes list
2356 self.assertIn(ident, [id(o) for o in subprocess._active])
2357
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002358 def test_leak_fast_process_del_killed(self):
2359 # Issue #12650: on Unix, if Popen.__del__() was called before the
2360 # process exited, and the process got killed by a signal, it would never
2361 # be removed from subprocess._active, which triggered a FD and memory
2362 # leak.
2363 # spawn a Popen, delete its reference and kill it
2364 p = subprocess.Popen([sys.executable, "-c",
2365 'import time;'
2366 'time.sleep(3)'],
2367 stdout=subprocess.PIPE,
2368 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002369 self.addCleanup(p.stdout.close)
2370 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002371 ident = id(p)
2372 pid = p.pid
Victor Stinner5a48e212016-05-20 12:11:15 +02002373 with support.check_warnings(('', ResourceWarning)):
2374 p = None
2375
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002376 os.kill(pid, signal.SIGKILL)
2377 # check that p is in the active processes list
2378 self.assertIn(ident, [id(o) for o in subprocess._active])
2379
2380 # let some time for the process to exit, and create a new Popen: this
2381 # should trigger the wait() of p
2382 time.sleep(0.2)
Andrew Svetlov3438fa42012-12-17 23:35:18 +02002383 with self.assertRaises(OSError) as c:
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002384 with subprocess.Popen(['nonexisting_i_hope'],
2385 stdout=subprocess.PIPE,
2386 stderr=subprocess.PIPE) as proc:
2387 pass
2388 # p should have been wait()ed on, and removed from the _active list
2389 self.assertRaises(OSError, os.waitpid, pid, 0)
2390 self.assertNotIn(ident, [id(o) for o in subprocess._active])
2391
Charles-François Natali249cdc32013-08-25 18:24:45 +02002392 def test_close_fds_after_preexec(self):
2393 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2394
2395 # this FD is used as dup2() target by preexec_fn, and should be closed
2396 # in the child process
2397 fd = os.dup(1)
2398 self.addCleanup(os.close, fd)
2399
2400 p = subprocess.Popen([sys.executable, fd_status],
2401 stdout=subprocess.PIPE, close_fds=True,
2402 preexec_fn=lambda: os.dup2(1, fd))
2403 output, ignored = p.communicate()
2404
2405 remaining_fds = set(map(int, output.split(b',')))
2406
2407 self.assertNotIn(fd, remaining_fds)
2408
Victor Stinner8f437aa2014-10-05 17:25:19 +02002409 @support.cpython_only
2410 def test_fork_exec(self):
2411 # Issue #22290: fork_exec() must not crash on memory allocation failure
2412 # or other errors
2413 import _posixsubprocess
2414 gc_enabled = gc.isenabled()
2415 try:
2416 # Use a preexec function and enable the garbage collector
2417 # to force fork_exec() to re-enable the garbage collector
2418 # on error.
2419 func = lambda: None
2420 gc.enable()
2421
Victor Stinner8f437aa2014-10-05 17:25:19 +02002422 for args, exe_list, cwd, env_list in (
2423 (123, [b"exe"], None, [b"env"]),
2424 ([b"arg"], 123, None, [b"env"]),
2425 ([b"arg"], [b"exe"], 123, [b"env"]),
2426 ([b"arg"], [b"exe"], None, 123),
2427 ):
2428 with self.assertRaises(TypeError):
2429 _posixsubprocess.fork_exec(
2430 args, exe_list,
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002431 True, (), cwd, env_list,
Victor Stinner8f437aa2014-10-05 17:25:19 +02002432 -1, -1, -1, -1,
2433 1, 2, 3, 4,
2434 True, True, func)
2435 finally:
2436 if not gc_enabled:
2437 gc.disable()
2438
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002439 @support.cpython_only
2440 def test_fork_exec_sorted_fd_sanity_check(self):
2441 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
2442 import _posixsubprocess
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002443 class BadInt:
2444 first = True
2445 def __init__(self, value):
2446 self.value = value
2447 def __int__(self):
2448 if self.first:
2449 self.first = False
2450 return self.value
2451 raise ValueError
2452
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002453 gc_enabled = gc.isenabled()
2454 try:
2455 gc.enable()
2456
2457 for fds_to_keep in (
2458 (-1, 2, 3, 4, 5), # Negative number.
2459 ('str', 4), # Not an int.
2460 (18, 23, 42, 2**63), # Out of range.
2461 (5, 4), # Not sorted.
2462 (6, 7, 7, 8), # Duplicate.
Serhiy Storchaka66bffd12017-04-19 21:12:46 +03002463 (BadInt(1), BadInt(2)),
Gregory P. Smithd0a5b1c2015-11-15 21:15:26 -08002464 ):
2465 with self.assertRaises(
2466 ValueError,
2467 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
2468 _posixsubprocess.fork_exec(
2469 [b"false"], [b"false"],
2470 True, fds_to_keep, None, [b"env"],
2471 -1, -1, -1, -1,
2472 1, 2, 3, 4,
2473 True, True, None)
2474 self.assertIn('fds_to_keep', str(c.exception))
2475 finally:
2476 if not gc_enabled:
2477 gc.disable()
Victor Stinner8f437aa2014-10-05 17:25:19 +02002478
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)2daf8e72016-06-05 02:57:47 +00002479 def test_communicate_BrokenPipeError_stdin_close(self):
2480 # By not setting stdout or stderr or a timeout we force the fast path
2481 # that just calls _stdin_write() internally due to our mock.
2482 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2483 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2484 mock_proc_stdin.close.side_effect = BrokenPipeError
2485 proc.communicate() # Should swallow BrokenPipeError from close.
2486 mock_proc_stdin.close.assert_called_with()
2487
2488 def test_communicate_BrokenPipeError_stdin_write(self):
2489 # By not setting stdout or stderr or a timeout we force the fast path
2490 # that just calls _stdin_write() internally due to our mock.
2491 proc = subprocess.Popen([sys.executable, '-c', 'pass'])
2492 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2493 mock_proc_stdin.write.side_effect = BrokenPipeError
2494 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
2495 mock_proc_stdin.write.assert_called_once_with(b'stuff')
2496 mock_proc_stdin.close.assert_called_once_with()
2497
2498 def test_communicate_BrokenPipeError_stdin_flush(self):
2499 # Setting stdin and stdout forces the ._communicate() code path.
2500 # python -h exits faster than python -c pass (but spams stdout).
2501 proc = subprocess.Popen([sys.executable, '-h'],
2502 stdin=subprocess.PIPE,
2503 stdout=subprocess.PIPE)
2504 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
2505 open(os.devnull, 'wb') as dev_null:
2506 mock_proc_stdin.flush.side_effect = BrokenPipeError
2507 # because _communicate registers a selector using proc.stdin...
2508 mock_proc_stdin.fileno.return_value = dev_null.fileno()
2509 # _communicate() should swallow BrokenPipeError from flush.
2510 proc.communicate(b'stuff')
2511 mock_proc_stdin.flush.assert_called_once_with()
2512
2513 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
2514 # Setting stdin and stdout forces the ._communicate() code path.
2515 # python -h exits faster than python -c pass (but spams stdout).
2516 proc = subprocess.Popen([sys.executable, '-h'],
2517 stdin=subprocess.PIPE,
2518 stdout=subprocess.PIPE)
2519 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
2520 mock_proc_stdin.close.side_effect = BrokenPipeError
2521 # _communicate() should swallow BrokenPipeError from close.
2522 proc.communicate(timeout=999)
2523 mock_proc_stdin.close.assert_called_once_with()
2524
Gregory P. Smith1fa08bc2017-01-22 22:19:38 -08002525 @unittest.skipIf(not ctypes, 'ctypes module required.')
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002526 @unittest.skipIf(not sys.executable, 'Test requires sys.executable.')
2527 def test_child_terminated_in_stopped_state(self):
2528 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
2529 PTRACE_TRACEME = 0 # From glibc and MacOS (PT_TRACE_ME).
Gregory P. Smith56bc3b72017-05-23 07:49:13 -07002530 libc_name = ctypes.util.find_library('c')
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002531 libc = ctypes.CDLL(libc_name)
2532 if not hasattr(libc, 'ptrace'):
2533 raise unittest.SkipTest('ptrace() required.')
2534 test_ptrace = subprocess.Popen(
2535 [sys.executable, '-c', """if True:
2536 import ctypes
2537 libc = ctypes.CDLL({libc_name!r})
2538 libc.ptrace({PTRACE_TRACEME}, 0, 0)
2539 """.format(libc_name=libc_name, PTRACE_TRACEME=PTRACE_TRACEME)
2540 ])
2541 if test_ptrace.wait() != 0:
2542 raise unittest.SkipTest('ptrace() failed - unable to test.')
2543 child = subprocess.Popen(
2544 [sys.executable, '-c', """if True:
Gregory P. Smith56bc3b72017-05-23 07:49:13 -07002545 import ctypes, faulthandler
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002546 libc = ctypes.CDLL({libc_name!r})
2547 libc.ptrace({PTRACE_TRACEME}, 0, 0)
Gregory P. Smith56bc3b72017-05-23 07:49:13 -07002548 faulthandler._sigsegv() # Crash the process.
Gregory P. Smith50e16e32017-01-22 17:28:38 -08002549 """.format(libc_name=libc_name, PTRACE_TRACEME=PTRACE_TRACEME)
2550 ])
2551 try:
2552 returncode = child.wait()
2553 except Exception as e:
2554 child.kill() # Clean up the hung stopped process.
2555 raise e
2556 self.assertNotEqual(0, returncode)
2557 self.assertLess(returncode, 0) # signal death, likely SIGSEGV.
2558
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002559
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002560@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00002561class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002562
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002563 def test_startupinfo(self):
2564 # startupinfo argument
2565 # We uses hardcoded constants, because we do not want to
2566 # depend on win32all.
2567 STARTF_USESHOWWINDOW = 1
2568 SW_MAXIMIZE = 3
2569 startupinfo = subprocess.STARTUPINFO()
2570 startupinfo.dwFlags = STARTF_USESHOWWINDOW
2571 startupinfo.wShowWindow = SW_MAXIMIZE
2572 # Since Python is a console process, it won't be affected
2573 # by wShowWindow, but the argument should be silently
2574 # ignored
2575 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002576 startupinfo=startupinfo)
2577
Subhendu Ghoshae160bb2017-02-25 20:29:05 +05302578 def test_startupinfo_keywords(self):
2579 # startupinfo argument
2580 # We use hardcoded constants, because we do not want to
2581 # depend on win32all.
2582 STARTF_USERSHOWWINDOW = 1
2583 SW_MAXIMIZE = 3
2584 startupinfo = subprocess.STARTUPINFO(
2585 dwFlags=STARTF_USERSHOWWINDOW,
2586 wShowWindow=SW_MAXIMIZE
2587 )
2588 # Since Python is a console process, it won't be affected
2589 # by wShowWindow, but the argument should be silently
2590 # ignored
2591 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
2592 startupinfo=startupinfo)
2593
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002594 def test_creationflags(self):
2595 # creationflags argument
2596 CREATE_NEW_CONSOLE = 16
2597 sys.stderr.write(" a DOS box should flash briefly ...\n")
2598 subprocess.call(sys.executable +
2599 ' -c "import time; time.sleep(0.25)"',
2600 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002601
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002602 def test_invalid_args(self):
2603 # invalid arguments should raise ValueError
2604 self.assertRaises(ValueError, subprocess.call,
2605 [sys.executable, "-c",
2606 "import sys; sys.exit(47)"],
2607 preexec_fn=lambda: 1)
2608 self.assertRaises(ValueError, subprocess.call,
2609 [sys.executable, "-c",
2610 "import sys; sys.exit(47)"],
2611 stdout=subprocess.PIPE,
2612 close_fds=True)
2613
2614 def test_close_fds(self):
2615 # close file descriptors
2616 rc = subprocess.call([sys.executable, "-c",
2617 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002618 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002619 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002620
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002621 def test_shell_sequence(self):
2622 # Run command through the shell (sequence)
2623 newenv = os.environ.copy()
2624 newenv["FRUIT"] = "physalis"
2625 p = subprocess.Popen(["set"], shell=1,
2626 stdout=subprocess.PIPE,
2627 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002628 with p:
2629 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00002630
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002631 def test_shell_string(self):
2632 # Run command through the shell (string)
2633 newenv = os.environ.copy()
2634 newenv["FRUIT"] = "physalis"
2635 p = subprocess.Popen("set", shell=1,
2636 stdout=subprocess.PIPE,
2637 env=newenv)
Victor Stinner7438c612016-05-20 12:43:15 +02002638 with p:
2639 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002640
Steve Dower050acae2016-09-06 20:16:17 -07002641 def test_shell_encodings(self):
2642 # Run command through the shell (string)
2643 for enc in ['ansi', 'oem']:
2644 newenv = os.environ.copy()
2645 newenv["FRUIT"] = "physalis"
2646 p = subprocess.Popen("set", shell=1,
2647 stdout=subprocess.PIPE,
2648 env=newenv,
2649 encoding=enc)
2650 with p:
2651 self.assertIn("physalis", p.stdout.read(), enc)
2652
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002653 def test_call_string(self):
2654 # call() function with string argument on Windows
2655 rc = subprocess.call(sys.executable +
2656 ' -c "import sys; sys.exit(47)"')
2657 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002658
Florent Xicluna4886d242010-03-08 13:27:26 +00002659 def _kill_process(self, method, *args):
2660 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00002661 p = subprocess.Popen([sys.executable, "-c", """if 1:
2662 import sys, time
2663 sys.stdout.write('x\\n')
2664 sys.stdout.flush()
2665 time.sleep(30)
2666 """],
2667 stdin=subprocess.PIPE,
2668 stdout=subprocess.PIPE,
2669 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002670 with p:
2671 # Wait for the interpreter to be completely initialized before
2672 # sending any signal.
2673 p.stdout.read(1)
2674 getattr(p, method)(*args)
2675 _, stderr = p.communicate()
2676 self.assertStderrEqual(stderr, b'')
2677 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00002678 self.assertNotEqual(returncode, 0)
2679
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002680 def _kill_dead_process(self, method, *args):
2681 p = subprocess.Popen([sys.executable, "-c", """if 1:
2682 import sys, time
2683 sys.stdout.write('x\\n')
2684 sys.stdout.flush()
2685 sys.exit(42)
2686 """],
2687 stdin=subprocess.PIPE,
2688 stdout=subprocess.PIPE,
2689 stderr=subprocess.PIPE)
Victor Stinner7438c612016-05-20 12:43:15 +02002690 with p:
2691 # Wait for the interpreter to be completely initialized before
2692 # sending any signal.
2693 p.stdout.read(1)
2694 # The process should end after this
2695 time.sleep(1)
2696 # This shouldn't raise even though the child is now dead
2697 getattr(p, method)(*args)
2698 _, stderr = p.communicate()
2699 self.assertStderrEqual(stderr, b'')
2700 rc = p.wait()
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002701 self.assertEqual(rc, 42)
2702
Florent Xicluna4886d242010-03-08 13:27:26 +00002703 def test_send_signal(self):
2704 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00002705
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002706 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002707 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00002708
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002709 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002710 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00002711
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002712 def test_send_signal_dead(self):
2713 self._kill_dead_process('send_signal', signal.SIGTERM)
2714
2715 def test_kill_dead(self):
2716 self._kill_dead_process('kill')
2717
2718 def test_terminate_dead(self):
2719 self._kill_dead_process('terminate')
2720
Martin Panter23172bd2016-04-16 11:28:10 +00002721class MiscTests(unittest.TestCase):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002722 def test_getoutput(self):
2723 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
2724 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
2725 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00002726
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002727 # we use mkdtemp in the next line to create an empty directory
2728 # under our exclusive control; from that, we can invent a pathname
2729 # that we _know_ won't exist. This is guaranteed to fail.
2730 dir = None
2731 try:
2732 dir = tempfile.mkdtemp()
2733 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00002734 status, output = subprocess.getstatusoutput(
2735 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002736 self.assertNotEqual(status, 0)
2737 finally:
2738 if dir is not None:
2739 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00002740
Gregory P. Smithace55862015-04-07 15:57:54 -07002741 def test__all__(self):
2742 """Ensure that __all__ is populated properly."""
Martin Panter528619b2016-04-16 23:42:37 +00002743 intentionally_excluded = {"list2cmdline", "Handle"}
Gregory P. Smithace55862015-04-07 15:57:54 -07002744 exported = set(subprocess.__all__)
2745 possible_exports = set()
2746 import types
2747 for name, value in subprocess.__dict__.items():
2748 if name.startswith('_'):
2749 continue
2750 if isinstance(value, (types.ModuleType,)):
2751 continue
2752 possible_exports.add(name)
2753 self.assertEqual(exported, possible_exports - intentionally_excluded)
2754
2755
Martin Panter23172bd2016-04-16 11:28:10 +00002756@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
2757 "Test needs selectors.PollSelector")
2758class ProcessTestCaseNoPoll(ProcessTestCase):
2759 def setUp(self):
2760 self.orig_selector = subprocess._PopenSelector
2761 subprocess._PopenSelector = selectors.SelectSelector
2762 ProcessTestCase.setUp(self)
2763
2764 def tearDown(self):
2765 subprocess._PopenSelector = self.orig_selector
2766 ProcessTestCase.tearDown(self)
2767
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002768
Tim Golden126c2962010-08-11 14:20:40 +00002769@unittest.skipUnless(mswindows, "Windows-specific tests")
2770class CommandsWithSpaces (BaseTestCase):
2771
2772 def setUp(self):
2773 super().setUp()
Berker Peksag16a1f282015-09-28 13:33:14 +03002774 f, fname = tempfile.mkstemp(".py", "te st")
Tim Golden126c2962010-08-11 14:20:40 +00002775 self.fname = fname.lower ()
2776 os.write(f, b"import sys;"
2777 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
2778 )
2779 os.close(f)
2780
2781 def tearDown(self):
2782 os.remove(self.fname)
2783 super().tearDown()
2784
2785 def with_spaces(self, *args, **kwargs):
2786 kwargs['stdout'] = subprocess.PIPE
2787 p = subprocess.Popen(*args, **kwargs)
Victor Stinner7438c612016-05-20 12:43:15 +02002788 with p:
2789 self.assertEqual(
2790 p.stdout.read ().decode("mbcs"),
2791 "2 [%r, 'ab cd']" % self.fname
2792 )
Tim Golden126c2962010-08-11 14:20:40 +00002793
2794 def test_shell_string_with_spaces(self):
2795 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002796 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2797 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002798
2799 def test_shell_sequence_with_spaces(self):
2800 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002801 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002802
2803 def test_noshell_string_with_spaces(self):
2804 # call() function with string argument with spaces on Windows
2805 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2806 "ab cd"))
2807
2808 def test_noshell_sequence_with_spaces(self):
2809 # call() function with sequence argument with spaces on Windows
2810 self.with_spaces([sys.executable, self.fname, "ab cd"])
2811
Brian Curtin79cdb662010-12-03 02:46:02 +00002812
Georg Brandla86b2622012-02-20 21:34:57 +01002813class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00002814
2815 def test_pipe(self):
2816 with subprocess.Popen([sys.executable, "-c",
2817 "import sys;"
2818 "sys.stdout.write('stdout');"
2819 "sys.stderr.write('stderr');"],
2820 stdout=subprocess.PIPE,
2821 stderr=subprocess.PIPE) as proc:
2822 self.assertEqual(proc.stdout.read(), b"stdout")
2823 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2824
2825 self.assertTrue(proc.stdout.closed)
2826 self.assertTrue(proc.stderr.closed)
2827
2828 def test_returncode(self):
2829 with subprocess.Popen([sys.executable, "-c",
2830 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002831 pass
2832 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002833 self.assertEqual(proc.returncode, 100)
2834
2835 def test_communicate_stdin(self):
2836 with subprocess.Popen([sys.executable, "-c",
2837 "import sys;"
2838 "sys.exit(sys.stdin.read() == 'context')"],
2839 stdin=subprocess.PIPE) as proc:
2840 proc.communicate(b"context")
2841 self.assertEqual(proc.returncode, 1)
2842
2843 def test_invalid_args(self):
Xavier de Gaye38c8b7d2016-11-14 17:14:42 +01002844 with self.assertRaises((FileNotFoundError, PermissionError)) as c:
Brian Curtin79cdb662010-12-03 02:46:02 +00002845 with subprocess.Popen(['nonexisting_i_hope'],
2846 stdout=subprocess.PIPE,
2847 stderr=subprocess.PIPE) as proc:
2848 pass
2849
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002850 def test_broken_pipe_cleanup(self):
2851 """Broken pipe error should not prevent wait() (Issue 21619)"""
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002852 proc = subprocess.Popen([sys.executable, '-c', 'pass'],
Victor Stinner20f4bd42015-03-05 02:38:41 +01002853 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01002854 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002855 proc = proc.__enter__()
2856 # Prepare to send enough data to overflow any OS pipe buffering and
2857 # guarantee a broken pipe error. Data is held in BufferedWriter
2858 # buffer until closed.
2859 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002860 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002861 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02002862 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002863 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002864 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002865
Brian Curtin79cdb662010-12-03 02:46:02 +00002866
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002867if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002868 unittest.main()