blob: 9c0229ae563db35e86eb558dcfca01b40abcb53f [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
Berker Peksagce643912015-05-06 06:33:17 +03002from test.support import script_helper
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003from test import support
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00004import subprocess
5import sys
6import signal
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04007import io
Andrew Svetlov82860712012-08-19 22:13:41 +03008import locale
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
Tim Peters3761e8d2004-10-13 04:07:12 +000013import re
Charles-François Natali3a4586a2013-11-08 19:56:59 +010014import selectors
Ezio Melotti184bdfb2010-02-18 09:37:05 +000015import sysconfig
Gregory P. Smithd23047b2010-12-04 09:10:44 +000016import warnings
Gregory P. Smith51ee2702010-12-13 07:59:39 +000017import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040018import shutil
Benjamin Petersonb870aa12011-12-10 12:44:25 -050019import gc
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030020import textwrap
Benjamin Peterson964561b2011-12-10 12:31:42 -050021
22try:
Antoine Pitroua8392712013-08-30 23:38:13 +020023 import threading
24except ImportError:
25 threading = None
Benjamin Peterson964561b2011-12-10 12:31:42 -050026
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000027mswindows = (sys.platform == "win32")
28
29#
30# Depends on the following external programs: Python
31#
32
33if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000034 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
35 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000036else:
37 SETBINARY = ''
38
Florent Xiclunab1e94e82010-02-27 22:12:37 +000039
40try:
41 mkstemp = tempfile.mkstemp
42except AttributeError:
43 # tempfile.mkstemp is not available
44 def mkstemp():
45 """Replacement for mkstemp, calling mktemp."""
46 fname = tempfile.mktemp()
47 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
48
Tim Peters3761e8d2004-10-13 04:07:12 +000049
Florent Xiclunac049d872010-03-27 22:47:23 +000050class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000051 def setUp(self):
52 # Try to minimize the number of children we have so this test
53 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000054 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000055
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000056 def tearDown(self):
57 for inst in subprocess._active:
58 inst.wait()
59 subprocess._cleanup()
60 self.assertFalse(subprocess._active, "subprocess._active not empty")
61
Florent Xiclunab1e94e82010-02-27 22:12:37 +000062 def assertStderrEqual(self, stderr, expected, msg=None):
63 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
64 # shutdown time. That frustrates tests trying to check stderr produced
65 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000066 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040067 # strip_python_stderr also strips whitespace, so we do too.
68 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000069 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000070
Florent Xiclunac049d872010-03-27 22:47:23 +000071
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080072class PopenTestException(Exception):
73 pass
74
75
76class PopenExecuteChildRaises(subprocess.Popen):
77 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
78 _execute_child fails.
79 """
80 def _execute_child(self, *args, **kwargs):
81 raise PopenTestException("Forced Exception for Test")
82
83
Florent Xiclunac049d872010-03-27 22:47:23 +000084class ProcessTestCase(BaseTestCase):
85
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070086 def test_io_buffered_by_default(self):
87 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
88 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
89 stderr=subprocess.PIPE)
90 try:
91 self.assertIsInstance(p.stdin, io.BufferedIOBase)
92 self.assertIsInstance(p.stdout, io.BufferedIOBase)
93 self.assertIsInstance(p.stderr, io.BufferedIOBase)
94 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -070095 p.stdin.close()
96 p.stdout.close()
97 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -070098 p.wait()
99
100 def test_io_unbuffered_works(self):
101 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
102 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
103 stderr=subprocess.PIPE, bufsize=0)
104 try:
105 self.assertIsInstance(p.stdin, io.RawIOBase)
106 self.assertIsInstance(p.stdout, io.RawIOBase)
107 self.assertIsInstance(p.stderr, io.RawIOBase)
108 finally:
Gregory P. Smitha1b9ed32013-03-23 11:54:22 -0700109 p.stdin.close()
110 p.stdout.close()
111 p.stderr.close()
Gregory P. Smitha1ed5392013-03-23 11:44:25 -0700112 p.wait()
113
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000114 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000115 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +0000116 rc = subprocess.call([sys.executable, "-c",
117 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000118 self.assertEqual(rc, 47)
119
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400120 def test_call_timeout(self):
121 # call() function with timeout argument; we want to test that the child
122 # process gets killed when the timeout expires. If the child isn't
123 # killed, this call will deadlock since subprocess.call waits for the
124 # child.
125 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
126 [sys.executable, "-c", "while True: pass"],
127 timeout=0.1)
128
Peter Astrand454f7672005-01-01 09:36:35 +0000129 def test_check_call_zero(self):
130 # check_call() function with zero return code
131 rc = subprocess.check_call([sys.executable, "-c",
132 "import sys; sys.exit(0)"])
133 self.assertEqual(rc, 0)
134
135 def test_check_call_nonzero(self):
136 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000137 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000138 subprocess.check_call([sys.executable, "-c",
139 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000140 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000141
Georg Brandlf9734072008-12-07 15:30:06 +0000142 def test_check_output(self):
143 # check_output() function with zero return code
144 output = subprocess.check_output(
145 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000146 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000147
148 def test_check_output_nonzero(self):
149 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000150 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000151 subprocess.check_output(
152 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000153 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000154
155 def test_check_output_stderr(self):
156 # check_output() function stderr redirected to stdout
157 output = subprocess.check_output(
158 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
159 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000160 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000161
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300162 def test_check_output_stdin_arg(self):
163 # check_output() can be called with stdin set to a file
164 tf = tempfile.TemporaryFile()
165 self.addCleanup(tf.close)
166 tf.write(b'pear')
167 tf.seek(0)
168 output = subprocess.check_output(
169 [sys.executable, "-c",
170 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
171 stdin=tf)
172 self.assertIn(b'PEAR', output)
173
174 def test_check_output_input_arg(self):
175 # check_output() can be called with input set to a string
176 output = subprocess.check_output(
177 [sys.executable, "-c",
178 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
179 input=b'pear')
180 self.assertIn(b'PEAR', output)
181
Georg Brandlf9734072008-12-07 15:30:06 +0000182 def test_check_output_stdout_arg(self):
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300183 # check_output() refuses to accept 'stdout' argument
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000184 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000185 output = subprocess.check_output(
186 [sys.executable, "-c", "print('will not be run')"],
187 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000188 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000189 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000190
Serhiy Storchakafcd9f222013-04-22 20:20:54 +0300191 def test_check_output_stdin_with_input_arg(self):
192 # check_output() refuses to accept 'stdin' with 'input'
193 tf = tempfile.TemporaryFile()
194 self.addCleanup(tf.close)
195 tf.write(b'pear')
196 tf.seek(0)
197 with self.assertRaises(ValueError) as c:
198 output = subprocess.check_output(
199 [sys.executable, "-c", "print('will not be run')"],
200 stdin=tf, input=b'hare')
201 self.fail("Expected ValueError when stdin and input args supplied.")
202 self.assertIn('stdin', c.exception.args[0])
203 self.assertIn('input', c.exception.args[0])
204
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400205 def test_check_output_timeout(self):
206 # check_output() function with timeout arg
207 with self.assertRaises(subprocess.TimeoutExpired) as c:
208 output = subprocess.check_output(
209 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200210 "import sys, time\n"
211 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400212 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200213 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400214 # Some heavily loaded buildbots (sparc Debian 3.x) require
215 # this much time to start and print.
216 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400217 self.fail("Expected TimeoutExpired.")
218 self.assertEqual(c.exception.output, b'BDFL')
219
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000220 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000221 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000222 newenv = os.environ.copy()
223 newenv["FRUIT"] = "banana"
224 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000225 'import sys, os;'
226 'sys.exit(os.getenv("FRUIT")=="banana")'],
227 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000228 self.assertEqual(rc, 1)
229
Victor Stinner87b9bc32011-06-01 00:57:47 +0200230 def test_invalid_args(self):
231 # Popen() called with invalid arguments should raise TypeError
232 # but Popen.__del__ should not complain (issue #12085)
233 with support.captured_stderr() as s:
234 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
235 argcount = subprocess.Popen.__init__.__code__.co_argcount
236 too_many_args = [0] * (argcount + 1)
237 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
238 self.assertEqual(s.getvalue(), '')
239
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000240 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000241 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000242 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000243 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000244 self.addCleanup(p.stdout.close)
245 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000246 p.wait()
247 self.assertEqual(p.stdin, None)
248
249 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200250 # .stdout is None when not redirected, and the child's stdout will
251 # be inherited from the parent. In order to test this we run a
252 # subprocess in a subprocess:
253 # this_test
254 # \-- subprocess created by this test (parent)
255 # \-- subprocess created by the parent subprocess (child)
256 # The parent doesn't specify stdout, so the child will use the
257 # parent's stdout. This test checks that the message printed by the
258 # child goes to the parent stdout. The parent also checks that the
259 # child's stdout is None. See #11963.
260 code = ('import sys; from subprocess import Popen, PIPE;'
261 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
262 ' stdin=PIPE, stderr=PIPE);'
263 'p.wait(); assert p.stdout is None;')
264 p = subprocess.Popen([sys.executable, "-c", code],
265 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
266 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000267 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200268 out, err = p.communicate()
269 self.assertEqual(p.returncode, 0, err)
270 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000271
272 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000273 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000274 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000275 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000276 self.addCleanup(p.stdout.close)
277 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000278 p.wait()
279 self.assertEqual(p.stderr, None)
280
Chris Jerdonek776cb192012-10-08 15:56:43 -0700281 def _assert_python(self, pre_args, **kwargs):
282 # We include sys.exit() to prevent the test runner from hanging
283 # whenever python is found.
284 args = pre_args + ["import sys; sys.exit(47)"]
285 p = subprocess.Popen(args, **kwargs)
286 p.wait()
287 self.assertEqual(47, p.returncode)
288
289 def test_executable(self):
290 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700291 #
292 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
293 # determine where its standard library is, so we need the directory
294 # of args[0] to be valid for the Popen() call to Python to succeed.
295 # See also issue #16170 and issue #7774.
296 doesnotexist = os.path.join(os.path.dirname(sys.executable),
297 "doesnotexist")
298 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700299
300 def test_executable_takes_precedence(self):
301 # Check that the executable argument takes precedence over args[0].
302 #
303 # Verify first that the call succeeds without the executable arg.
304 pre_args = [sys.executable, "-c"]
305 self._assert_python(pre_args)
306 self.assertRaises(FileNotFoundError, self._assert_python, pre_args,
307 executable="doesnotexist")
308
309 @unittest.skipIf(mswindows, "executable argument replaces shell")
310 def test_executable_replaces_shell(self):
311 # Check that the executable argument replaces the default shell
312 # when shell=True.
313 self._assert_python([], executable=sys.executable, shell=True)
314
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700315 # For use in the test_cwd* tests below.
316 def _normalize_cwd(self, cwd):
317 # Normalize an expected cwd (for Tru64 support).
318 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
319 # strings. See bug #1063571.
320 original_cwd = os.getcwd()
321 os.chdir(cwd)
322 cwd = os.getcwd()
323 os.chdir(original_cwd)
324 return cwd
325
326 # For use in the test_cwd* tests below.
327 def _split_python_path(self):
328 # Return normalized (python_dir, python_base).
329 python_path = os.path.realpath(sys.executable)
330 return os.path.split(python_path)
331
332 # For use in the test_cwd* tests below.
333 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
334 # Invoke Python via Popen, and assert that (1) the call succeeds,
335 # and that (2) the current working directory of the child process
336 # matches *expected_cwd*.
337 p = subprocess.Popen([python_arg, "-c",
338 "import os, sys; "
339 "sys.stdout.write(os.getcwd()); "
340 "sys.exit(47)"],
341 stdout=subprocess.PIPE,
342 **kwargs)
343 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000344 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700345 self.assertEqual(47, p.returncode)
346 normcase = os.path.normcase
347 self.assertEqual(normcase(expected_cwd),
348 normcase(p.stdout.read().decode("utf-8")))
349
350 def test_cwd(self):
351 # Check that cwd changes the cwd for the child process.
352 temp_dir = tempfile.gettempdir()
353 temp_dir = self._normalize_cwd(temp_dir)
354 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
355
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700356 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700357 def test_cwd_with_relative_arg(self):
358 # Check that Popen looks for args[0] relative to cwd if args[0]
359 # is relative.
360 python_dir, python_base = self._split_python_path()
361 rel_python = os.path.join(os.curdir, python_base)
362 with support.temp_cwd() as wrong_dir:
363 # Before calling with the correct cwd, confirm that the call fails
364 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700365 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700366 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700367 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700368 [rel_python], cwd=wrong_dir)
369 python_dir = self._normalize_cwd(python_dir)
370 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
371
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700372 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700373 def test_cwd_with_relative_executable(self):
374 # Check that Popen looks for executable relative to cwd if executable
375 # is relative (and that executable takes precedence over args[0]).
376 python_dir, python_base = self._split_python_path()
377 rel_python = os.path.join(os.curdir, python_base)
378 doesntexist = "somethingyoudonthave"
379 with support.temp_cwd() as wrong_dir:
380 # Before calling with the correct cwd, confirm that the call fails
381 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700382 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700383 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700384 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700385 [doesntexist], executable=rel_python,
386 cwd=wrong_dir)
387 python_dir = self._normalize_cwd(python_dir)
388 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
389 cwd=python_dir)
390
391 def test_cwd_with_absolute_arg(self):
392 # Check that Popen can find the executable when the cwd is wrong
393 # if args[0] is an absolute path.
394 python_dir, python_base = self._split_python_path()
395 abs_python = os.path.join(python_dir, python_base)
396 rel_python = os.path.join(os.curdir, python_base)
Berker Peksagce643912015-05-06 06:33:17 +0300397 with support.temp_dir() as wrong_dir:
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700398 # Before calling with an absolute path, confirm that using a
399 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700400 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700401 [rel_python], cwd=wrong_dir)
402 wrong_dir = self._normalize_cwd(wrong_dir)
403 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
404
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100405 @unittest.skipIf(sys.base_prefix != sys.prefix,
406 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000407 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700408 python_dir, python_base = self._split_python_path()
409 python_dir = self._normalize_cwd(python_dir)
410 self._assert_cwd(python_dir, "somethingyoudonthave",
411 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000412
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100413 @unittest.skipIf(sys.base_prefix != sys.prefix,
414 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000415 @unittest.skipIf(sysconfig.is_python_build(),
416 "need an installed Python. See #7774")
417 def test_executable_without_cwd(self):
418 # For a normal installation, it should work without 'cwd'
419 # argument. For test runs in the build directory, see #7774.
Ned Deilye92dfbf2013-08-02 18:02:21 -0700420 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
421 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000422
423 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000424 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000425 p = subprocess.Popen([sys.executable, "-c",
426 'import sys; sys.exit(sys.stdin.read() == "pear")'],
427 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000428 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000429 p.stdin.close()
430 p.wait()
431 self.assertEqual(p.returncode, 1)
432
433 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000434 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000435 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000436 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000437 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000438 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000439 os.lseek(d, 0, 0)
440 p = subprocess.Popen([sys.executable, "-c",
441 'import sys; sys.exit(sys.stdin.read() == "pear")'],
442 stdin=d)
443 p.wait()
444 self.assertEqual(p.returncode, 1)
445
446 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000447 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000448 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000449 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000450 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000451 tf.seek(0)
452 p = subprocess.Popen([sys.executable, "-c",
453 'import sys; sys.exit(sys.stdin.read() == "pear")'],
454 stdin=tf)
455 p.wait()
456 self.assertEqual(p.returncode, 1)
457
458 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000459 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000460 p = subprocess.Popen([sys.executable, "-c",
461 'import sys; sys.stdout.write("orange")'],
462 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000463 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000464 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000465
466 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000467 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000468 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000469 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000470 d = tf.fileno()
471 p = subprocess.Popen([sys.executable, "-c",
472 'import sys; sys.stdout.write("orange")'],
473 stdout=d)
474 p.wait()
475 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000476 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000477
478 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000479 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000480 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000481 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000482 p = subprocess.Popen([sys.executable, "-c",
483 'import sys; sys.stdout.write("orange")'],
484 stdout=tf)
485 p.wait()
486 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000487 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000488
489 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000490 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000491 p = subprocess.Popen([sys.executable, "-c",
492 'import sys; sys.stderr.write("strawberry")'],
493 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000494 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000495 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000496
497 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000498 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000499 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000500 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000501 d = tf.fileno()
502 p = subprocess.Popen([sys.executable, "-c",
503 'import sys; sys.stderr.write("strawberry")'],
504 stderr=d)
505 p.wait()
506 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000507 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000508
509 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000510 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000511 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000512 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000513 p = subprocess.Popen([sys.executable, "-c",
514 'import sys; sys.stderr.write("strawberry")'],
515 stderr=tf)
516 p.wait()
517 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000518 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000519
520 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000521 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000522 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000523 'import sys;'
524 'sys.stdout.write("apple");'
525 'sys.stdout.flush();'
526 'sys.stderr.write("orange")'],
527 stdout=subprocess.PIPE,
528 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000529 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000530 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000531
532 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000533 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000534 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000535 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000536 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000537 'import sys;'
538 'sys.stdout.write("apple");'
539 'sys.stdout.flush();'
540 'sys.stderr.write("orange")'],
541 stdout=tf,
542 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000543 p.wait()
544 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000545 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000546
Thomas Wouters89f507f2006-12-13 04:49:30 +0000547 def test_stdout_filedes_of_stdout(self):
548 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200549 # To avoid printing the text on stdout, we do something similar to
550 # test_stdout_none (see above). The parent subprocess calls the child
551 # subprocess passing stdout=1, and this test uses stdout=PIPE in
552 # order to capture and check the output of the parent. See #11963.
553 code = ('import sys, subprocess; '
554 'rc = subprocess.call([sys.executable, "-c", '
555 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
556 'b\'test with stdout=1\'))"], stdout=1); '
557 'assert rc == 18')
558 p = subprocess.Popen([sys.executable, "-c", code],
559 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
560 self.addCleanup(p.stdout.close)
561 self.addCleanup(p.stderr.close)
562 out, err = p.communicate()
563 self.assertEqual(p.returncode, 0, err)
564 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000565
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200566 def test_stdout_devnull(self):
567 p = subprocess.Popen([sys.executable, "-c",
568 'for i in range(10240):'
569 'print("x" * 1024)'],
570 stdout=subprocess.DEVNULL)
571 p.wait()
572 self.assertEqual(p.stdout, None)
573
574 def test_stderr_devnull(self):
575 p = subprocess.Popen([sys.executable, "-c",
576 'import sys\n'
577 'for i in range(10240):'
578 'sys.stderr.write("x" * 1024)'],
579 stderr=subprocess.DEVNULL)
580 p.wait()
581 self.assertEqual(p.stderr, None)
582
583 def test_stdin_devnull(self):
584 p = subprocess.Popen([sys.executable, "-c",
585 'import sys;'
586 'sys.stdin.read(1)'],
587 stdin=subprocess.DEVNULL)
588 p.wait()
589 self.assertEqual(p.stdin, None)
590
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000591 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000592 newenv = os.environ.copy()
593 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200594 with subprocess.Popen([sys.executable, "-c",
595 'import sys,os;'
596 'sys.stdout.write(os.getenv("FRUIT"))'],
597 stdout=subprocess.PIPE,
598 env=newenv) as p:
599 stdout, stderr = p.communicate()
600 self.assertEqual(stdout, b"orange")
601
Victor Stinner62d51182011-06-23 01:02:25 +0200602 # Windows requires at least the SYSTEMROOT environment variable to start
603 # Python
604 @unittest.skipIf(sys.platform == 'win32',
605 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200606 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200607 'the python library cannot be loaded '
608 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200609 def test_empty_env(self):
610 with subprocess.Popen([sys.executable, "-c",
611 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200612 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200613 stdout=subprocess.PIPE,
614 env={}) as p:
615 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200616 self.assertIn(stdout.strip(),
617 (b"[]",
618 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
619 # environment
620 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000621
Peter Astrandcbac93c2005-03-03 20:24:28 +0000622 def test_communicate_stdin(self):
623 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000624 'import sys;'
625 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000626 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000627 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000628 self.assertEqual(p.returncode, 1)
629
630 def test_communicate_stdout(self):
631 p = subprocess.Popen([sys.executable, "-c",
632 'import sys; sys.stdout.write("pineapple")'],
633 stdout=subprocess.PIPE)
634 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000635 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000636 self.assertEqual(stderr, None)
637
638 def test_communicate_stderr(self):
639 p = subprocess.Popen([sys.executable, "-c",
640 'import sys; sys.stderr.write("pineapple")'],
641 stderr=subprocess.PIPE)
642 (stdout, stderr) = p.communicate()
643 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000644 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000645
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000646 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000647 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000648 'import sys,os;'
649 'sys.stderr.write("pineapple");'
650 'sys.stdout.write(sys.stdin.read())'],
651 stdin=subprocess.PIPE,
652 stdout=subprocess.PIPE,
653 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000654 self.addCleanup(p.stdout.close)
655 self.addCleanup(p.stderr.close)
656 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000657 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000658 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000659 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000660
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400661 def test_communicate_timeout(self):
662 p = subprocess.Popen([sys.executable, "-c",
663 'import sys,os,time;'
664 'sys.stderr.write("pineapple\\n");'
665 'time.sleep(1);'
666 'sys.stderr.write("pear\\n");'
667 'sys.stdout.write(sys.stdin.read())'],
668 universal_newlines=True,
669 stdin=subprocess.PIPE,
670 stdout=subprocess.PIPE,
671 stderr=subprocess.PIPE)
672 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
673 timeout=0.3)
674 # Make sure we can keep waiting for it, and that we get the whole output
675 # after it completes.
676 (stdout, stderr) = p.communicate()
677 self.assertEqual(stdout, "banana")
678 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
679
680 def test_communicate_timeout_large_ouput(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200681 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400682 p = subprocess.Popen([sys.executable, "-c",
683 'import sys,os,time;'
684 'sys.stdout.write("a" * (64 * 1024));'
685 'time.sleep(0.2);'
686 'sys.stdout.write("a" * (64 * 1024));'
687 'time.sleep(0.2);'
688 'sys.stdout.write("a" * (64 * 1024));'
689 'time.sleep(0.2);'
690 'sys.stdout.write("a" * (64 * 1024));'],
691 stdout=subprocess.PIPE)
692 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
693 (stdout, _) = p.communicate()
694 self.assertEqual(len(stdout), 4 * 64 * 1024)
695
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000696 # Test for the fd leak reported in http://bugs.python.org/issue2791.
697 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000698 for stdin_pipe in (False, True):
699 for stdout_pipe in (False, True):
700 for stderr_pipe in (False, True):
701 options = {}
702 if stdin_pipe:
703 options['stdin'] = subprocess.PIPE
704 if stdout_pipe:
705 options['stdout'] = subprocess.PIPE
706 if stderr_pipe:
707 options['stderr'] = subprocess.PIPE
708 if not options:
709 continue
710 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
711 p.communicate()
712 if p.stdin is not None:
713 self.assertTrue(p.stdin.closed)
714 if p.stdout is not None:
715 self.assertTrue(p.stdout.closed)
716 if p.stderr is not None:
717 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000718
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000719 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000720 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000721 p = subprocess.Popen([sys.executable, "-c",
722 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000723 (stdout, stderr) = p.communicate()
724 self.assertEqual(stdout, None)
725 self.assertEqual(stderr, None)
726
727 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000728 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000729 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000730 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000731 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000732 os.close(x)
733 os.close(y)
734 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000735 'import sys,os;'
736 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200737 'sys.stderr.write("x" * %d);'
738 'sys.stdout.write(sys.stdin.read())' %
739 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000740 stdin=subprocess.PIPE,
741 stdout=subprocess.PIPE,
742 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000743 self.addCleanup(p.stdout.close)
744 self.addCleanup(p.stderr.close)
745 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200746 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000747 (stdout, stderr) = p.communicate(string_to_write)
748 self.assertEqual(stdout, string_to_write)
749
750 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000751 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000752 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000753 'import sys,os;'
754 'sys.stdout.write(sys.stdin.read())'],
755 stdin=subprocess.PIPE,
756 stdout=subprocess.PIPE,
757 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000758 self.addCleanup(p.stdout.close)
759 self.addCleanup(p.stderr.close)
760 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000761 p.stdin.write(b"banana")
762 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000763 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000764 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000765
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000766 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000767 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000768 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200769 'buf = sys.stdout.buffer;'
770 'buf.write(sys.stdin.readline().encode());'
771 'buf.flush();'
772 'buf.write(b"line2\\n");'
773 'buf.flush();'
774 'buf.write(sys.stdin.read().encode());'
775 'buf.flush();'
776 'buf.write(b"line4\\n");'
777 'buf.flush();'
778 'buf.write(b"line5\\r\\n");'
779 'buf.flush();'
780 'buf.write(b"line6\\r");'
781 'buf.flush();'
782 'buf.write(b"\\nline7");'
783 'buf.flush();'
784 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200785 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000786 stdout=subprocess.PIPE,
787 universal_newlines=1)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200788 p.stdin.write("line1\n")
Antoine Pitrouc644e7c2014-05-09 00:24:50 +0200789 p.stdin.flush()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200790 self.assertEqual(p.stdout.readline(), "line1\n")
791 p.stdin.write("line3\n")
792 p.stdin.close()
Brian Curtin3c6a9512010-11-05 03:58:52 +0000793 self.addCleanup(p.stdout.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200794 self.assertEqual(p.stdout.readline(),
795 "line2\n")
796 self.assertEqual(p.stdout.read(6),
797 "line3\n")
798 self.assertEqual(p.stdout.read(),
799 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000800
801 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000802 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000803 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000804 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200805 'buf = sys.stdout.buffer;'
806 'buf.write(b"line2\\n");'
807 'buf.flush();'
808 'buf.write(b"line4\\n");'
809 'buf.flush();'
810 'buf.write(b"line5\\r\\n");'
811 'buf.flush();'
812 'buf.write(b"line6\\r");'
813 'buf.flush();'
814 'buf.write(b"\\nline7");'
815 'buf.flush();'
816 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200817 stderr=subprocess.PIPE,
818 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000819 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000820 self.addCleanup(p.stdout.close)
821 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000822 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200823 self.assertEqual(stdout,
824 "line2\nline4\nline5\nline6\nline7\nline8")
825
826 def test_universal_newlines_communicate_stdin(self):
827 # universal newlines through communicate(), with only stdin
828 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300829 'import sys,os;' + SETBINARY + textwrap.dedent('''
830 s = sys.stdin.readline()
831 assert s == "line1\\n", repr(s)
832 s = sys.stdin.read()
833 assert s == "line3\\n", repr(s)
834 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200835 stdin=subprocess.PIPE,
836 universal_newlines=1)
837 (stdout, stderr) = p.communicate("line1\nline3\n")
838 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000839
Andrew Svetlovf3765072012-08-14 18:35:17 +0300840 def test_universal_newlines_communicate_input_none(self):
841 # Test communicate(input=None) with universal newlines.
842 #
843 # We set stdout to PIPE because, as of this writing, a different
844 # code path is tested when the number of pipes is zero or one.
845 p = subprocess.Popen([sys.executable, "-c", "pass"],
846 stdin=subprocess.PIPE,
847 stdout=subprocess.PIPE,
848 universal_newlines=True)
849 p.communicate()
850 self.assertEqual(p.returncode, 0)
851
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300852 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300853 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300854 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300855 'import sys,os;' + SETBINARY + textwrap.dedent('''
856 s = sys.stdin.buffer.readline()
857 sys.stdout.buffer.write(s)
858 sys.stdout.buffer.write(b"line2\\r")
859 sys.stderr.buffer.write(b"eline2\\n")
860 s = sys.stdin.buffer.read()
861 sys.stdout.buffer.write(s)
862 sys.stdout.buffer.write(b"line4\\n")
863 sys.stdout.buffer.write(b"line5\\r\\n")
864 sys.stderr.buffer.write(b"eline6\\r")
865 sys.stderr.buffer.write(b"eline7\\r\\nz")
866 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300867 stdin=subprocess.PIPE,
868 stderr=subprocess.PIPE,
869 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300870 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300871 self.addCleanup(p.stdout.close)
872 self.addCleanup(p.stderr.close)
873 (stdout, stderr) = p.communicate("line1\nline3\n")
874 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300875 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300876 # Python debug build push something like "[42442 refs]\n"
877 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300878 # Don't use assertStderrEqual because it strips CR and LF from output.
879 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300880
Andrew Svetlov82860712012-08-19 22:13:41 +0300881 def test_universal_newlines_communicate_encodings(self):
882 # Check that universal newlines mode works for various encodings,
883 # in particular for encodings in the UTF-16 and UTF-32 families.
884 # See issue #15595.
885 #
886 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
887 # without, and UTF-16 and UTF-32.
Antoine Pitroufd4722c2013-10-12 00:13:50 +0200888 import _bootlocale
Andrew Svetlov82860712012-08-19 22:13:41 +0300889 for encoding in ['utf-16', 'utf-32-be']:
Antoine Pitroufd4722c2013-10-12 00:13:50 +0200890 old_getpreferredencoding = _bootlocale.getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300891 # Indirectly via io.TextIOWrapper, Popen() defaults to
892 # locale.getpreferredencoding(False) and earlier in Python 3.2 to
893 # locale.getpreferredencoding().
894 def getpreferredencoding(do_setlocale=True):
895 return encoding
896 code = ("import sys; "
897 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
898 encoding)
899 args = [sys.executable, '-c', code]
900 try:
Antoine Pitroufd4722c2013-10-12 00:13:50 +0200901 _bootlocale.getpreferredencoding = getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300902 # We set stdin to be non-None because, as of this writing,
903 # a different code path is used when the number of pipes is
904 # zero or one.
905 popen = subprocess.Popen(args, universal_newlines=True,
906 stdin=subprocess.PIPE,
907 stdout=subprocess.PIPE)
908 stdout, stderr = popen.communicate(input='')
909 finally:
Antoine Pitroufd4722c2013-10-12 00:13:50 +0200910 _bootlocale.getpreferredencoding = old_getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300911 self.assertEqual(stdout, '1\n2\n3\n4')
912
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000913 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000914 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000915 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000916 max_handles = 1026 # too much for most UNIX systems
917 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000918 max_handles = 2050 # too much for (at least some) Windows setups
919 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400920 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000921 try:
922 for i in range(max_handles):
923 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400924 tmpfile = os.path.join(tmpdir, support.TESTFN)
925 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000926 except OSError as e:
927 if e.errno != errno.EMFILE:
928 raise
929 break
930 else:
931 self.skipTest("failed to reach the file descriptor limit "
932 "(tried %d)" % max_handles)
933 # Close a couple of them (should be enough for a subprocess)
934 for i in range(10):
935 os.close(handles.pop())
936 # Loop creating some subprocesses. If one of them leaks some fds,
937 # the next loop iteration will fail by reaching the max fd limit.
938 for i in range(15):
939 p = subprocess.Popen([sys.executable, "-c",
940 "import sys;"
941 "sys.stdout.write(sys.stdin.read())"],
942 stdin=subprocess.PIPE,
943 stdout=subprocess.PIPE,
944 stderr=subprocess.PIPE)
945 data = p.communicate(b"lime")[0]
946 self.assertEqual(data, b"lime")
947 finally:
948 for h in handles:
949 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400950 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000951
952 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000953 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
954 '"a b c" d e')
955 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
956 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000957 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
958 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000959 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
960 'a\\\\\\b "de fg" h')
961 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
962 'a\\\\\\"b c d')
963 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
964 '"a\\\\b c" d e')
965 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
966 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000967 self.assertEqual(subprocess.list2cmdline(['ab', '']),
968 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000969
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000970 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200971 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +0200972 "import os; os.read(0, 1)"],
973 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200974 self.addCleanup(p.stdin.close)
975 self.assertIsNone(p.poll())
976 os.write(p.stdin.fileno(), b'A')
977 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000978 # Subsequent invocations should just return the returncode
979 self.assertEqual(p.poll(), 0)
980
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000981 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200982 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000983 self.assertEqual(p.wait(), 0)
984 # Subsequent invocations should just return the returncode
985 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000986
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400987 def test_wait_timeout(self):
988 p = subprocess.Popen([sys.executable,
Antoine Pitroudc49b2b2013-05-19 15:55:40 +0200989 "-c", "import time; time.sleep(0.3)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -0400990 with self.assertRaises(subprocess.TimeoutExpired) as c:
Antoine Pitroudc49b2b2013-05-19 15:55:40 +0200991 p.wait(timeout=0.0001)
992 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -0400993 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
994 # time to start.
995 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400996
Peter Astrand738131d2004-11-30 21:04:45 +0000997 def test_invalid_bufsize(self):
998 # an invalid type of the bufsize argument should raise
999 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001000 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +00001001 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +00001002
Guido van Rossum46a05a72007-06-07 21:56:45 +00001003 def test_bufsize_is_none(self):
1004 # bufsize=None should be the same as bufsize=0.
1005 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
1006 self.assertEqual(p.wait(), 0)
1007 # Again with keyword arg
1008 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
1009 self.assertEqual(p.wait(), 0)
1010
Antoine Pitrouafe8d062014-09-21 21:10:56 +02001011 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1012 # subprocess may deadlock with bufsize=1, see issue #21332
1013 with subprocess.Popen([sys.executable, "-c", "import sys;"
1014 "sys.stdout.write(sys.stdin.readline());"
1015 "sys.stdout.flush()"],
1016 stdin=subprocess.PIPE,
1017 stdout=subprocess.PIPE,
1018 stderr=subprocess.DEVNULL,
1019 bufsize=1,
1020 universal_newlines=universal_newlines) as p:
1021 p.stdin.write(line) # expect that it flushes the line in text mode
1022 os.close(p.stdin.fileno()) # close it without flushing the buffer
1023 read_line = p.stdout.readline()
1024 try:
1025 p.stdin.close()
1026 except OSError:
1027 pass
1028 p.stdin = None
1029 self.assertEqual(p.returncode, 0)
1030 self.assertEqual(read_line, expected)
1031
1032 def test_bufsize_equal_one_text_mode(self):
1033 # line is flushed in text mode with bufsize=1.
1034 # we should get the full line in return
1035 line = "line\n"
1036 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1037
1038 def test_bufsize_equal_one_binary_mode(self):
1039 # line is not flushed in binary mode with bufsize=1.
1040 # we should get empty response
1041 line = b'line' + os.linesep.encode() # assume ascii-based locale
1042 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
1043
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001044 def test_leaking_fds_on_error(self):
1045 # see bug #5179: Popen leaks file descriptors to PIPEs if
1046 # the child fails to execute; this will eventually exhaust
1047 # the maximum number of open fds. 1024 seems a very common
1048 # value for that limit, but Windows has 2048, so we loop
1049 # 1024 times (each call leaked two fds).
1050 for i in range(1024):
Andrew Svetlov3438fa42012-12-17 23:35:18 +02001051 with self.assertRaises(OSError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001052 subprocess.Popen(['nonexisting_i_hope'],
1053 stdout=subprocess.PIPE,
1054 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -04001055 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -04001056 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001057 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +00001058
Antoine Pitroua8392712013-08-30 23:38:13 +02001059 @unittest.skipIf(threading is None, "threading required")
1060 def test_double_close_on_error(self):
1061 # Issue #18851
1062 fds = []
1063 def open_fds():
1064 for i in range(20):
1065 fds.extend(os.pipe())
1066 time.sleep(0.001)
1067 t = threading.Thread(target=open_fds)
1068 t.start()
1069 try:
1070 with self.assertRaises(EnvironmentError):
1071 subprocess.Popen(['nonexisting_i_hope'],
1072 stdin=subprocess.PIPE,
1073 stdout=subprocess.PIPE,
1074 stderr=subprocess.PIPE)
1075 finally:
1076 t.join()
1077 exc = None
1078 for fd in fds:
1079 # If a double close occurred, some of those fds will
1080 # already have been closed by mistake, and os.close()
1081 # here will raise.
1082 try:
1083 os.close(fd)
1084 except OSError as e:
1085 exc = e
1086 if exc is not None:
1087 raise exc
1088
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001089 @unittest.skipIf(threading is None, "threading required")
1090 def test_threadsafe_wait(self):
1091 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1092 proc = subprocess.Popen([sys.executable, '-c',
1093 'import time; time.sleep(12)'])
1094 self.assertEqual(proc.returncode, None)
1095 results = []
1096
1097 def kill_proc_timer_thread():
1098 results.append(('thread-start-poll-result', proc.poll()))
1099 # terminate it from the thread and wait for the result.
1100 proc.kill()
1101 proc.wait()
1102 results.append(('thread-after-kill-and-wait', proc.returncode))
1103 # this wait should be a no-op given the above.
1104 proc.wait()
1105 results.append(('thread-after-second-wait', proc.returncode))
1106
1107 # This is a timing sensitive test, the failure mode is
1108 # triggered when both the main thread and this thread are in
1109 # the wait() call at once. The delay here is to allow the
1110 # main thread to most likely be blocked in its wait() call.
1111 t = threading.Timer(0.2, kill_proc_timer_thread)
1112 t.start()
1113
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001114 if mswindows:
1115 expected_errorcode = 1
1116 else:
1117 # Should be -9 because of the proc.kill() from the thread.
1118 expected_errorcode = -9
1119
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001120 # Wait for the process to finish; the thread should kill it
1121 # long before it finishes on its own. Supplying a timeout
1122 # triggers a different code path for better coverage.
1123 proc.wait(timeout=20)
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001124 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001125 msg="unexpected result in wait from main thread")
1126
1127 # This should be a no-op with no change in returncode.
1128 proc.wait()
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001129 self.assertEqual(proc.returncode, expected_errorcode,
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001130 msg="unexpected result in second main wait.")
1131
1132 t.join()
1133 # Ensure that all of the thread results are as expected.
1134 # When a race condition occurs in wait(), the returncode could
1135 # be set by the wrong thread that doesn't actually have it
1136 # leading to an incorrect value.
1137 self.assertEqual([('thread-start-poll-result', None),
Gregory P. Smithab2719f2014-04-23 08:38:36 -07001138 ('thread-after-kill-and-wait', expected_errorcode),
1139 ('thread-after-second-wait', expected_errorcode)],
Gregory P. Smithd65ba512014-04-23 00:27:17 -07001140 results)
1141
Victor Stinnerb3693582010-05-21 20:13:12 +00001142 def test_issue8780(self):
1143 # Ensure that stdout is inherited from the parent
1144 # if stdout=PIPE is not used
1145 code = ';'.join((
1146 'import subprocess, sys',
1147 'retcode = subprocess.call('
1148 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1149 'assert retcode == 0'))
1150 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001151 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +00001152
Tim Goldenaf5ac392010-08-06 13:03:56 +00001153 def test_handles_closed_on_exception(self):
1154 # If CreateProcess exits with an error, ensure the
1155 # duplicate output handles are released
1156 ifhandle, ifname = mkstemp()
1157 ofhandle, ofname = mkstemp()
1158 efhandle, efname = mkstemp()
1159 try:
1160 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1161 stderr=efhandle)
1162 except OSError:
1163 os.close(ifhandle)
1164 os.remove(ifname)
1165 os.close(ofhandle)
1166 os.remove(ofname)
1167 os.close(efhandle)
1168 os.remove(efname)
1169 self.assertFalse(os.path.exists(ifname))
1170 self.assertFalse(os.path.exists(ofname))
1171 self.assertFalse(os.path.exists(efname))
1172
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001173 def test_communicate_epipe(self):
1174 # Issue 10963: communicate() should hide EPIPE
1175 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1176 stdin=subprocess.PIPE,
1177 stdout=subprocess.PIPE,
1178 stderr=subprocess.PIPE)
1179 self.addCleanup(p.stdout.close)
1180 self.addCleanup(p.stderr.close)
1181 self.addCleanup(p.stdin.close)
1182 p.communicate(b"x" * 2**20)
1183
1184 def test_communicate_epipe_only_stdin(self):
1185 # Issue 10963: communicate() should hide EPIPE
1186 p = subprocess.Popen([sys.executable, "-c", 'pass'],
1187 stdin=subprocess.PIPE)
1188 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001189 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +02001190 p.communicate(b"x" * 2**20)
1191
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001192 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1193 "Requires signal.SIGUSR1")
1194 @unittest.skipUnless(hasattr(os, 'kill'),
1195 "Requires os.kill")
1196 @unittest.skipUnless(hasattr(os, 'getppid'),
1197 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001198 def test_communicate_eintr(self):
1199 # Issue #12493: communicate() should handle EINTR
1200 def handler(signum, frame):
1201 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001202 old_handler = signal.signal(signal.SIGUSR1, handler)
1203 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001204
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001205 args = [sys.executable, "-c",
1206 'import os, signal;'
1207 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001208 for stream in ('stdout', 'stderr'):
1209 kw = {stream: subprocess.PIPE}
1210 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001211 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001212 process.communicate()
1213
Tim Peterse718f612004-10-12 21:51:32 +00001214
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001215 # This test is Linux-ish specific for simplicity to at least have
1216 # some coverage. It is not a platform specific bug.
1217 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1218 "Linux specific")
1219 def test_failed_child_execute_fd_leak(self):
1220 """Test for the fork() failure fd leak reported in issue16327."""
1221 fd_directory = '/proc/%d/fd' % os.getpid()
1222 fds_before_popen = os.listdir(fd_directory)
1223 with self.assertRaises(PopenTestException):
1224 PopenExecuteChildRaises(
1225 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
1226 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1227
1228 # NOTE: This test doesn't verify that the real _execute_child
1229 # does not close the file descriptors itself on the way out
1230 # during an exception. Code inspection has confirmed that.
1231
1232 fds_after_exception = os.listdir(fd_directory)
1233 self.assertEqual(fds_before_popen, fds_after_exception)
1234
Gregory P. Smith6e730002015-04-14 16:14:25 -07001235
1236class RunFuncTestCase(BaseTestCase):
1237 def run_python(self, code, **kwargs):
1238 """Run Python code in a subprocess using subprocess.run"""
1239 argv = [sys.executable, "-c", code]
1240 return subprocess.run(argv, **kwargs)
1241
1242 def test_returncode(self):
1243 # call() function with sequence argument
1244 cp = self.run_python("import sys; sys.exit(47)")
1245 self.assertEqual(cp.returncode, 47)
1246 with self.assertRaises(subprocess.CalledProcessError):
1247 cp.check_returncode()
1248
1249 def test_check(self):
1250 with self.assertRaises(subprocess.CalledProcessError) as c:
1251 self.run_python("import sys; sys.exit(47)", check=True)
1252 self.assertEqual(c.exception.returncode, 47)
1253
1254 def test_check_zero(self):
1255 # check_returncode shouldn't raise when returncode is zero
1256 cp = self.run_python("import sys; sys.exit(0)", check=True)
1257 self.assertEqual(cp.returncode, 0)
1258
1259 def test_timeout(self):
1260 # run() function with timeout argument; we want to test that the child
1261 # process gets killed when the timeout expires. If the child isn't
1262 # killed, this call will deadlock since subprocess.run waits for the
1263 # child.
1264 with self.assertRaises(subprocess.TimeoutExpired):
1265 self.run_python("while True: pass", timeout=0.0001)
1266
1267 def test_capture_stdout(self):
1268 # capture stdout with zero return code
1269 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1270 self.assertIn(b'BDFL', cp.stdout)
1271
1272 def test_capture_stderr(self):
1273 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1274 stderr=subprocess.PIPE)
1275 self.assertIn(b'BDFL', cp.stderr)
1276
1277 def test_check_output_stdin_arg(self):
1278 # run() can be called with stdin set to a file
1279 tf = tempfile.TemporaryFile()
1280 self.addCleanup(tf.close)
1281 tf.write(b'pear')
1282 tf.seek(0)
1283 cp = self.run_python(
1284 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1285 stdin=tf, stdout=subprocess.PIPE)
1286 self.assertIn(b'PEAR', cp.stdout)
1287
1288 def test_check_output_input_arg(self):
1289 # check_output() can be called with input set to a string
1290 cp = self.run_python(
1291 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1292 input=b'pear', stdout=subprocess.PIPE)
1293 self.assertIn(b'PEAR', cp.stdout)
1294
1295 def test_check_output_stdin_with_input_arg(self):
1296 # run() refuses to accept 'stdin' with 'input'
1297 tf = tempfile.TemporaryFile()
1298 self.addCleanup(tf.close)
1299 tf.write(b'pear')
1300 tf.seek(0)
1301 with self.assertRaises(ValueError,
1302 msg="Expected ValueError when stdin and input args supplied.") as c:
1303 output = self.run_python("print('will not be run')",
1304 stdin=tf, input=b'hare')
1305 self.assertIn('stdin', c.exception.args[0])
1306 self.assertIn('input', c.exception.args[0])
1307
1308 def test_check_output_timeout(self):
1309 with self.assertRaises(subprocess.TimeoutExpired) as c:
1310 cp = self.run_python((
1311 "import sys, time\n"
1312 "sys.stdout.write('BDFL')\n"
1313 "sys.stdout.flush()\n"
1314 "time.sleep(3600)"),
1315 # Some heavily loaded buildbots (sparc Debian 3.x) require
1316 # this much time to start and print.
1317 timeout=3, stdout=subprocess.PIPE)
1318 self.assertEqual(c.exception.output, b'BDFL')
1319 # output is aliased to stdout
1320 self.assertEqual(c.exception.stdout, b'BDFL')
1321
1322 def test_run_kwargs(self):
1323 newenv = os.environ.copy()
1324 newenv["FRUIT"] = "banana"
1325 cp = self.run_python(('import sys, os;'
1326 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1327 env=newenv)
1328 self.assertEqual(cp.returncode, 33)
1329
1330
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001331@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001332class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001333
Gregory P. Smith5591b022012-10-10 03:34:47 -07001334 def setUp(self):
1335 super().setUp()
1336 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1337
1338 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001339 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001340 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001341 except OSError as e:
1342 # This avoids hard coding the errno value or the OS perror()
1343 # string and instead capture the exception that we want to see
1344 # below for comparison.
1345 desired_exception = e
Gregory P. Smith5591b022012-10-10 03:34:47 -07001346 desired_exception.strerror += ': ' + repr(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001347 else:
1348 self.fail("chdir to nonexistant directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001349 self._nonexistent_dir)
1350 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001351
Gregory P. Smith5591b022012-10-10 03:34:47 -07001352 def test_exception_cwd(self):
1353 """Test error in the child raised in the parent for a bad cwd."""
1354 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001355 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001356 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001357 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001358 except OSError as e:
1359 # Test that the child process chdir failure actually makes
1360 # it up to the parent process as the correct exception.
1361 self.assertEqual(desired_exception.errno, e.errno)
1362 self.assertEqual(desired_exception.strerror, e.strerror)
1363 else:
1364 self.fail("Expected OSError: %s" % desired_exception)
1365
Gregory P. Smith5591b022012-10-10 03:34:47 -07001366 def test_exception_bad_executable(self):
1367 """Test error in the child raised in the parent for a bad executable."""
1368 desired_exception = self._get_chdir_exception()
1369 try:
1370 p = subprocess.Popen([sys.executable, "-c", ""],
1371 executable=self._nonexistent_dir)
1372 except OSError as e:
1373 # Test that the child process exec failure actually makes
1374 # it up to the parent process as the correct exception.
1375 self.assertEqual(desired_exception.errno, e.errno)
1376 self.assertEqual(desired_exception.strerror, e.strerror)
1377 else:
1378 self.fail("Expected OSError: %s" % desired_exception)
1379
1380 def test_exception_bad_args_0(self):
1381 """Test error in the child raised in the parent for a bad args[0]."""
1382 desired_exception = self._get_chdir_exception()
1383 try:
1384 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1385 except OSError as e:
1386 # Test that the child process exec failure actually makes
1387 # it up to the parent process as the correct exception.
1388 self.assertEqual(desired_exception.errno, e.errno)
1389 self.assertEqual(desired_exception.strerror, e.strerror)
1390 else:
1391 self.fail("Expected OSError: %s" % desired_exception)
1392
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001393 def test_restore_signals(self):
1394 # Code coverage for both values of restore_signals to make sure it
1395 # at least does not blow up.
1396 # A test for behavior would be complex. Contributions welcome.
1397 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1398 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1399
1400 def test_start_new_session(self):
1401 # For code coverage of calling setsid(). We don't care if we get an
1402 # EPERM error from it depending on the test execution environment, that
1403 # still indicates that it was called.
1404 try:
1405 output = subprocess.check_output(
1406 [sys.executable, "-c",
1407 "import os; print(os.getpgid(os.getpid()))"],
1408 start_new_session=True)
1409 except OSError as e:
1410 if e.errno != errno.EPERM:
1411 raise
1412 else:
1413 parent_pgid = os.getpgid(os.getpid())
1414 child_pgid = int(output)
1415 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001416
1417 def test_run_abort(self):
1418 # returncode handles signal termination
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001419 with support.SuppressCrashReport():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001420 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001421 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001422 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001423 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001424
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001425 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001426 # DISCLAIMER: Setting environment variables is *not* a good use
1427 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001428 p = subprocess.Popen([sys.executable, "-c",
1429 'import sys,os;'
1430 'sys.stdout.write(os.getenv("FRUIT"))'],
1431 stdout=subprocess.PIPE,
1432 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +00001433 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001434 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001435
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001436 def test_preexec_exception(self):
1437 def raise_it():
1438 raise ValueError("What if two swallows carried a coconut?")
1439 try:
1440 p = subprocess.Popen([sys.executable, "-c", ""],
1441 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001442 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001443 self.assertTrue(
1444 subprocess._posixsubprocess,
1445 "Expected a ValueError from the preexec_fn")
1446 except ValueError as e:
1447 self.assertIn("coconut", e.args[0])
1448 else:
1449 self.fail("Exception raised by preexec_fn did not make it "
1450 "to the parent process.")
1451
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001452 class _TestExecuteChildPopen(subprocess.Popen):
1453 """Used to test behavior at the end of _execute_child."""
1454 def __init__(self, testcase, *args, **kwargs):
1455 self._testcase = testcase
1456 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001457
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001458 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001459 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001460 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001461 finally:
1462 # Open a bunch of file descriptors and verify that
1463 # none of them are the same as the ones the Popen
1464 # instance is using for stdin/stdout/stderr.
1465 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1466 for _ in range(8)]
1467 try:
1468 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001469 self._testcase.assertNotIn(
1470 fd, (self.stdin.fileno(), self.stdout.fileno(),
1471 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001472 msg="At least one fd was closed early.")
1473 finally:
Richard Oudkerk0e547b62013-06-10 16:29:19 +01001474 for fd in devzero_fds:
1475 os.close(fd)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001476
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001477 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1478 def test_preexec_errpipe_does_not_double_close_pipes(self):
1479 """Issue16140: Don't double close pipes on preexec error."""
1480
1481 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08001482 raise subprocess.SubprocessError(
1483 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001484
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08001485 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001486 self._TestExecuteChildPopen(
1487 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001488 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1489 stderr=subprocess.PIPE, preexec_fn=raise_it)
1490
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001491 def test_preexec_gc_module_failure(self):
1492 # This tests the code that disables garbage collection if the child
1493 # process will execute any Python.
1494 def raise_runtime_error():
1495 raise RuntimeError("this shouldn't escape")
1496 enabled = gc.isenabled()
1497 orig_gc_disable = gc.disable
1498 orig_gc_isenabled = gc.isenabled
1499 try:
1500 gc.disable()
1501 self.assertFalse(gc.isenabled())
1502 subprocess.call([sys.executable, '-c', ''],
1503 preexec_fn=lambda: None)
1504 self.assertFalse(gc.isenabled(),
1505 "Popen enabled gc when it shouldn't.")
1506
1507 gc.enable()
1508 self.assertTrue(gc.isenabled())
1509 subprocess.call([sys.executable, '-c', ''],
1510 preexec_fn=lambda: None)
1511 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1512
1513 gc.disable = raise_runtime_error
1514 self.assertRaises(RuntimeError, subprocess.Popen,
1515 [sys.executable, '-c', ''],
1516 preexec_fn=lambda: None)
1517
1518 del gc.isenabled # force an AttributeError
1519 self.assertRaises(AttributeError, subprocess.Popen,
1520 [sys.executable, '-c', ''],
1521 preexec_fn=lambda: None)
1522 finally:
1523 gc.disable = orig_gc_disable
1524 gc.isenabled = orig_gc_isenabled
1525 if not enabled:
1526 gc.disable()
1527
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001528 def test_args_string(self):
1529 # args is a string
1530 fd, fname = mkstemp()
1531 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001532 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001533 fobj.write("#!/bin/sh\n")
1534 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1535 sys.executable)
1536 os.chmod(fname, 0o700)
1537 p = subprocess.Popen(fname)
1538 p.wait()
1539 os.remove(fname)
1540 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001541
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001542 def test_invalid_args(self):
1543 # invalid arguments should raise ValueError
1544 self.assertRaises(ValueError, subprocess.call,
1545 [sys.executable, "-c",
1546 "import sys; sys.exit(47)"],
1547 startupinfo=47)
1548 self.assertRaises(ValueError, subprocess.call,
1549 [sys.executable, "-c",
1550 "import sys; sys.exit(47)"],
1551 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001552
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001553 def test_shell_sequence(self):
1554 # Run command through the shell (sequence)
1555 newenv = os.environ.copy()
1556 newenv["FRUIT"] = "apple"
1557 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1558 stdout=subprocess.PIPE,
1559 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001560 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001561 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001562
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001563 def test_shell_string(self):
1564 # Run command through the shell (string)
1565 newenv = os.environ.copy()
1566 newenv["FRUIT"] = "apple"
1567 p = subprocess.Popen("echo $FRUIT", shell=1,
1568 stdout=subprocess.PIPE,
1569 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001570 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001571 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001572
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001573 def test_call_string(self):
1574 # call() function with string argument on UNIX
1575 fd, fname = mkstemp()
1576 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001577 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001578 fobj.write("#!/bin/sh\n")
1579 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1580 sys.executable)
1581 os.chmod(fname, 0o700)
1582 rc = subprocess.call(fname)
1583 os.remove(fname)
1584 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001585
Stefan Krah9542cc62010-07-19 14:20:53 +00001586 def test_specific_shell(self):
1587 # Issue #9265: Incorrect name passed as arg[0].
1588 shells = []
1589 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1590 for name in ['bash', 'ksh']:
1591 sh = os.path.join(prefix, name)
1592 if os.path.isfile(sh):
1593 shells.append(sh)
1594 if not shells: # Will probably work for any shell but csh.
1595 self.skipTest("bash or ksh required for this test")
1596 sh = '/bin/sh'
1597 if os.path.isfile(sh) and not os.path.islink(sh):
1598 # Test will fail if /bin/sh is a symlink to csh.
1599 shells.append(sh)
1600 for sh in shells:
1601 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1602 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001603 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001604 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1605
Florent Xicluna4886d242010-03-08 13:27:26 +00001606 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001607 # Do not inherit file handles from the parent.
1608 # It should fix failures on some platforms.
Gregory P. Smithdee04342013-08-29 13:35:27 -07001609 # Also set the SIGINT handler to the default to make sure it's not
1610 # being ignored (some tests rely on that.)
1611 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
1612 try:
1613 p = subprocess.Popen([sys.executable, "-c", """if 1:
1614 import sys, time
1615 sys.stdout.write('x\\n')
1616 sys.stdout.flush()
1617 time.sleep(30)
1618 """],
1619 close_fds=True,
1620 stdin=subprocess.PIPE,
1621 stdout=subprocess.PIPE,
1622 stderr=subprocess.PIPE)
1623 finally:
1624 signal.signal(signal.SIGINT, old_handler)
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001625 # Wait for the interpreter to be completely initialized before
1626 # sending any signal.
1627 p.stdout.read(1)
1628 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001629 return p
1630
Charles-François Natali53221e32013-01-12 16:52:20 +01001631 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1632 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001633 def _kill_dead_process(self, method, *args):
1634 # Do not inherit file handles from the parent.
1635 # It should fix failures on some platforms.
1636 p = subprocess.Popen([sys.executable, "-c", """if 1:
1637 import sys, time
1638 sys.stdout.write('x\\n')
1639 sys.stdout.flush()
1640 """],
1641 close_fds=True,
1642 stdin=subprocess.PIPE,
1643 stdout=subprocess.PIPE,
1644 stderr=subprocess.PIPE)
1645 # Wait for the interpreter to be completely initialized before
1646 # sending any signal.
1647 p.stdout.read(1)
1648 # The process should end after this
1649 time.sleep(1)
1650 # This shouldn't raise even though the child is now dead
1651 getattr(p, method)(*args)
1652 p.communicate()
1653
Florent Xicluna4886d242010-03-08 13:27:26 +00001654 def test_send_signal(self):
1655 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001656 _, stderr = p.communicate()
1657 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001658 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001659
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001660 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001661 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001662 _, stderr = p.communicate()
1663 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001664 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001665
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001666 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001667 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001668 _, stderr = p.communicate()
1669 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001670 self.assertEqual(p.wait(), -signal.SIGTERM)
1671
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001672 def test_send_signal_dead(self):
1673 # Sending a signal to a dead process
1674 self._kill_dead_process('send_signal', signal.SIGINT)
1675
1676 def test_kill_dead(self):
1677 # Killing a dead process
1678 self._kill_dead_process('kill')
1679
1680 def test_terminate_dead(self):
1681 # Terminating a dead process
1682 self._kill_dead_process('terminate')
1683
Victor Stinnerdaf45552013-08-28 00:53:59 +02001684 def _save_fds(self, save_fds):
1685 fds = []
1686 for fd in save_fds:
1687 inheritable = os.get_inheritable(fd)
1688 saved = os.dup(fd)
1689 fds.append((fd, saved, inheritable))
1690 return fds
1691
1692 def _restore_fds(self, fds):
1693 for fd, saved, inheritable in fds:
1694 os.dup2(saved, fd, inheritable=inheritable)
1695 os.close(saved)
1696
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001697 def check_close_std_fds(self, fds):
1698 # Issue #9905: test that subprocess pipes still work properly with
1699 # some standard fds closed
1700 stdin = 0
Victor Stinnerdaf45552013-08-28 00:53:59 +02001701 saved_fds = self._save_fds(fds)
1702 for fd, saved, inheritable in saved_fds:
1703 if fd == 0:
1704 stdin = saved
1705 break
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001706 try:
1707 for fd in fds:
1708 os.close(fd)
1709 out, err = subprocess.Popen([sys.executable, "-c",
1710 'import sys;'
1711 'sys.stdout.write("apple");'
1712 'sys.stdout.flush();'
1713 'sys.stderr.write("orange")'],
1714 stdin=stdin,
1715 stdout=subprocess.PIPE,
1716 stderr=subprocess.PIPE).communicate()
1717 err = support.strip_python_stderr(err)
1718 self.assertEqual((out, err), (b'apple', b'orange'))
1719 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001720 self._restore_fds(saved_fds)
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001721
1722 def test_close_fd_0(self):
1723 self.check_close_std_fds([0])
1724
1725 def test_close_fd_1(self):
1726 self.check_close_std_fds([1])
1727
1728 def test_close_fd_2(self):
1729 self.check_close_std_fds([2])
1730
1731 def test_close_fds_0_1(self):
1732 self.check_close_std_fds([0, 1])
1733
1734 def test_close_fds_0_2(self):
1735 self.check_close_std_fds([0, 2])
1736
1737 def test_close_fds_1_2(self):
1738 self.check_close_std_fds([1, 2])
1739
1740 def test_close_fds_0_1_2(self):
1741 # Issue #10806: test that subprocess pipes still work properly with
1742 # all standard fds closed.
1743 self.check_close_std_fds([0, 1, 2])
1744
Gregory P. Smith53dd8162013-12-01 16:03:24 -08001745 def test_small_errpipe_write_fd(self):
1746 """Issue #15798: Popen should work when stdio fds are available."""
1747 new_stdin = os.dup(0)
1748 new_stdout = os.dup(1)
1749 try:
1750 os.close(0)
1751 os.close(1)
1752
1753 # Side test: if errpipe_write fails to have its CLOEXEC
1754 # flag set this should cause the parent to think the exec
1755 # failed. Extremely unlikely: everyone supports CLOEXEC.
1756 subprocess.Popen([
1757 sys.executable, "-c",
1758 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
1759 finally:
1760 # Restore original stdin and stdout
1761 os.dup2(new_stdin, 0)
1762 os.dup2(new_stdout, 1)
1763 os.close(new_stdin)
1764 os.close(new_stdout)
1765
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001766 def test_remapping_std_fds(self):
1767 # open up some temporary files
1768 temps = [mkstemp() for i in range(3)]
1769 try:
1770 temp_fds = [fd for fd, fname in temps]
1771
1772 # unlink the files -- we won't need to reopen them
1773 for fd, fname in temps:
1774 os.unlink(fname)
1775
1776 # write some data to what will become stdin, and rewind
1777 os.write(temp_fds[1], b"STDIN")
1778 os.lseek(temp_fds[1], 0, 0)
1779
1780 # move the standard file descriptors out of the way
Victor Stinnerdaf45552013-08-28 00:53:59 +02001781 saved_fds = self._save_fds(range(3))
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001782 try:
1783 # duplicate the file objects over the standard fd's
1784 for fd, temp_fd in enumerate(temp_fds):
1785 os.dup2(temp_fd, fd)
1786
1787 # now use those files in the "wrong" order, so that subprocess
1788 # has to rearrange them in the child
1789 p = subprocess.Popen([sys.executable, "-c",
1790 'import sys; got = sys.stdin.read();'
1791 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1792 stdin=temp_fds[1],
1793 stdout=temp_fds[2],
1794 stderr=temp_fds[0])
1795 p.wait()
1796 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001797 self._restore_fds(saved_fds)
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001798
1799 for fd in temp_fds:
1800 os.lseek(fd, 0, 0)
1801
1802 out = os.read(temp_fds[2], 1024)
1803 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1804 self.assertEqual(out, b"got STDIN")
1805 self.assertEqual(err, b"err")
1806
1807 finally:
1808 for fd in temp_fds:
1809 os.close(fd)
1810
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001811 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1812 # open up some temporary files
1813 temps = [mkstemp() for i in range(3)]
1814 temp_fds = [fd for fd, fname in temps]
1815 try:
1816 # unlink the files -- we won't need to reopen them
1817 for fd, fname in temps:
1818 os.unlink(fname)
1819
1820 # save a copy of the standard file descriptors
Victor Stinnerdaf45552013-08-28 00:53:59 +02001821 saved_fds = self._save_fds(range(3))
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001822 try:
1823 # duplicate the temp files over the standard fd's 0, 1, 2
1824 for fd, temp_fd in enumerate(temp_fds):
1825 os.dup2(temp_fd, fd)
1826
1827 # write some data to what will become stdin, and rewind
1828 os.write(stdin_no, b"STDIN")
1829 os.lseek(stdin_no, 0, 0)
1830
1831 # now use those files in the given order, so that subprocess
1832 # has to rearrange them in the child
1833 p = subprocess.Popen([sys.executable, "-c",
1834 'import sys; got = sys.stdin.read();'
1835 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1836 stdin=stdin_no,
1837 stdout=stdout_no,
1838 stderr=stderr_no)
1839 p.wait()
1840
1841 for fd in temp_fds:
1842 os.lseek(fd, 0, 0)
1843
1844 out = os.read(stdout_no, 1024)
1845 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1846 finally:
Victor Stinnerdaf45552013-08-28 00:53:59 +02001847 self._restore_fds(saved_fds)
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001848
1849 self.assertEqual(out, b"got STDIN")
1850 self.assertEqual(err, b"err")
1851
1852 finally:
1853 for fd in temp_fds:
1854 os.close(fd)
1855
1856 # When duping fds, if there arises a situation where one of the fds is
1857 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1858 # This tests all combinations of this.
1859 def test_swap_fds(self):
1860 self.check_swap_fds(0, 1, 2)
1861 self.check_swap_fds(0, 2, 1)
1862 self.check_swap_fds(1, 0, 2)
1863 self.check_swap_fds(1, 2, 0)
1864 self.check_swap_fds(2, 0, 1)
1865 self.check_swap_fds(2, 1, 0)
1866
Victor Stinner13bb71c2010-04-23 21:41:56 +00001867 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001868 def prepare():
1869 raise ValueError("surrogate:\uDCff")
1870
1871 try:
1872 subprocess.call(
1873 [sys.executable, "-c", "pass"],
1874 preexec_fn=prepare)
1875 except ValueError as err:
1876 # Pure Python implementations keeps the message
1877 self.assertIsNone(subprocess._posixsubprocess)
1878 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001879 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00001880 # _posixsubprocess uses a default message
1881 self.assertIsNotNone(subprocess._posixsubprocess)
1882 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1883 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001884 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00001885
Victor Stinner13bb71c2010-04-23 21:41:56 +00001886 def test_undecodable_env(self):
1887 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner5323fb02013-11-19 23:46:06 +01001888 encoded_value = value.encode("ascii", "surrogateescape")
1889
Victor Stinner13bb71c2010-04-23 21:41:56 +00001890 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001891 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001892 env = os.environ.copy()
1893 env[key] = value
Victor Stinner5323fb02013-11-19 23:46:06 +01001894 # Use C locale to get ASCII for the locale encoding to force
Victor Stinner89f3ad12010-10-14 10:43:31 +00001895 # surrogate-escaping of \xFF in the child process; otherwise it can
1896 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001897 env['LC_ALL'] = 'C'
Victor Stinner5323fb02013-11-19 23:46:06 +01001898 if sys.platform.startswith("aix"):
1899 # On AIX, the C locale uses the Latin1 encoding
1900 decoded_value = encoded_value.decode("latin1", "surrogateescape")
1901 else:
1902 # On other UNIXes, the C locale uses the ASCII encoding
1903 decoded_value = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001904 stdout = subprocess.check_output(
1905 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001906 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001907 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01001908 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001909
1910 # test bytes
1911 key = key.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001912 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001913 env = os.environ.copy()
Victor Stinner5323fb02013-11-19 23:46:06 +01001914 env[key] = encoded_value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001915 stdout = subprocess.check_output(
1916 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001917 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001918 stdout = stdout.rstrip(b'\n\r')
Victor Stinner5323fb02013-11-19 23:46:06 +01001919 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001920
Victor Stinnerb745a742010-05-18 17:17:23 +00001921 def test_bytes_program(self):
1922 abs_program = os.fsencode(sys.executable)
1923 path, program = os.path.split(sys.executable)
1924 program = os.fsencode(program)
1925
1926 # absolute bytes path
1927 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001928 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001929
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001930 # absolute bytes path as a string
1931 cmd = b"'" + abs_program + b"' -c pass"
1932 exitcode = subprocess.call(cmd, shell=True)
1933 self.assertEqual(exitcode, 0)
1934
Victor Stinnerb745a742010-05-18 17:17:23 +00001935 # bytes program, unicode PATH
1936 env = os.environ.copy()
1937 env["PATH"] = path
1938 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001939 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001940
1941 # bytes program, bytes PATH
1942 envb = os.environb.copy()
1943 envb[b"PATH"] = os.fsencode(path)
1944 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001945 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001946
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001947 def test_pipe_cloexec(self):
1948 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1949 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1950
1951 p1 = subprocess.Popen([sys.executable, sleeper],
1952 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1953 stderr=subprocess.PIPE, close_fds=False)
1954
1955 self.addCleanup(p1.communicate, b'')
1956
1957 p2 = subprocess.Popen([sys.executable, fd_status],
1958 stdout=subprocess.PIPE, close_fds=False)
1959
1960 output, error = p2.communicate()
1961 result_fds = set(map(int, output.split(b',')))
1962 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1963 p1.stderr.fileno()])
1964
1965 self.assertFalse(result_fds & unwanted_fds,
1966 "Expected no fds from %r to be open in child, "
1967 "found %r" %
1968 (unwanted_fds, result_fds & unwanted_fds))
1969
1970 def test_pipe_cloexec_real_tools(self):
1971 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1972 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1973
1974 subdata = b'zxcvbn'
1975 data = subdata * 4 + b'\n'
1976
1977 p1 = subprocess.Popen([sys.executable, qcat],
1978 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1979 close_fds=False)
1980
1981 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1982 stdin=p1.stdout, stdout=subprocess.PIPE,
1983 close_fds=False)
1984
1985 self.addCleanup(p1.wait)
1986 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001987 def kill_p1():
1988 try:
1989 p1.terminate()
1990 except ProcessLookupError:
1991 pass
1992 def kill_p2():
1993 try:
1994 p2.terminate()
1995 except ProcessLookupError:
1996 pass
1997 self.addCleanup(kill_p1)
1998 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001999
2000 p1.stdin.write(data)
2001 p1.stdin.close()
2002
2003 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
2004
2005 self.assertTrue(readfiles, "The child hung")
2006 self.assertEqual(p2.stdout.read(), data)
2007
Victor Stinnerfaa8c132011-01-03 16:36:00 +00002008 p1.stdout.close()
2009 p2.stdout.close()
2010
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002011 def test_close_fds(self):
2012 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2013
2014 fds = os.pipe()
2015 self.addCleanup(os.close, fds[0])
2016 self.addCleanup(os.close, fds[1])
2017
2018 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002019 # add a bunch more fds
2020 for _ in range(9):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002021 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smith8facece2012-01-21 14:01:08 -08002022 self.addCleanup(os.close, fd)
2023 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002024
Victor Stinnerdaf45552013-08-28 00:53:59 +02002025 for fd in open_fds:
2026 os.set_inheritable(fd, True)
2027
Gregory P. Smith51ee2702010-12-13 07:59:39 +00002028 p = subprocess.Popen([sys.executable, fd_status],
2029 stdout=subprocess.PIPE, close_fds=False)
2030 output, ignored = p.communicate()
2031 remaining_fds = set(map(int, output.split(b',')))
2032
2033 self.assertEqual(remaining_fds & open_fds, open_fds,
2034 "Some fds were closed")
2035
2036 p = subprocess.Popen([sys.executable, fd_status],
2037 stdout=subprocess.PIPE, close_fds=True)
2038 output, ignored = p.communicate()
2039 remaining_fds = set(map(int, output.split(b',')))
2040
2041 self.assertFalse(remaining_fds & open_fds,
2042 "Some fds were left open")
2043 self.assertIn(1, remaining_fds, "Subprocess failed")
2044
Gregory P. Smith8facece2012-01-21 14:01:08 -08002045 # Keep some of the fd's we opened open in the subprocess.
2046 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
2047 fds_to_keep = set(open_fds.pop() for _ in range(8))
2048 p = subprocess.Popen([sys.executable, fd_status],
2049 stdout=subprocess.PIPE, close_fds=True,
2050 pass_fds=())
2051 output, ignored = p.communicate()
2052 remaining_fds = set(map(int, output.split(b',')))
2053
2054 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
2055 "Some fds not in pass_fds were left open")
2056 self.assertIn(1, remaining_fds, "Subprocess failed")
2057
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002058
Gregory P. Smithd04f6992014-06-01 15:27:28 -07002059 @unittest.skipIf(sys.platform.startswith("freebsd") and
2060 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
2061 "Requires fdescfs mounted on /dev/fd on FreeBSD.")
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002062 def test_close_fds_when_max_fd_is_lowered(self):
2063 """Confirm that issue21618 is fixed (may fail under valgrind)."""
2064 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2065
Gregory P. Smith634aa682014-06-15 17:51:04 -07002066 # This launches the meat of the test in a child process to
2067 # avoid messing with the larger unittest processes maximum
2068 # number of file descriptors.
2069 # This process launches:
2070 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
2071 # a bunch of high open fds above the new lower rlimit.
2072 # Those are reported via stdout before launching a new
2073 # process with close_fds=False to run the actual test:
2074 # +--> The TEST: This one launches a fd_status.py
2075 # subprocess with close_fds=True so we can find out if
2076 # any of the fds above the lowered rlimit are still open.
2077 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
2078 '''
2079 import os, resource, subprocess, sys, textwrap
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002080 open_fds = set()
2081 # Add a bunch more fds to pass down.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002082 for _ in range(40):
Serhiy Storchaka85c30332015-02-15 13:58:23 +02002083 fd = os.open(os.devnull, os.O_RDONLY)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002084 open_fds.add(fd)
2085
2086 # Leave a two pairs of low ones available for use by the
2087 # internal child error pipe and the stdout pipe.
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002088 # We also leave 10 more open as some Python buildbots run into
2089 # "too many open files" errors during the test if we do not.
2090 for fd in sorted(open_fds)[:14]:
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002091 os.close(fd)
2092 open_fds.remove(fd)
2093
2094 for fd in open_fds:
Gregory P. Smith634aa682014-06-15 17:51:04 -07002095 #self.addCleanup(os.close, fd)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002096 os.set_inheritable(fd, True)
2097
2098 max_fd_open = max(open_fds)
2099
Gregory P. Smith634aa682014-06-15 17:51:04 -07002100 # Communicate the open_fds to the parent unittest.TestCase process.
2101 print(','.join(map(str, sorted(open_fds))))
2102 sys.stdout.flush()
2103
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002104 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
2105 try:
Gregory P. Smith8fed4de2014-06-01 15:15:44 -07002106 # 29 is lower than the highest fds we are leaving open.
2107 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002108 # Launch a new Python interpreter with our low fd rlim_cur that
2109 # inherits open fds above that limit. It then uses subprocess
2110 # with close_fds=True to get a report of open fds in the child.
2111 # An explicit list of fds to check is passed to fd_status.py as
2112 # letting fd_status rely on its default logic would miss the
2113 # fds above rlim_cur as it normally only checks up to that limit.
Gregory P. Smith634aa682014-06-15 17:51:04 -07002114 subprocess.Popen(
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002115 [sys.executable, '-c',
2116 textwrap.dedent("""
2117 import subprocess, sys
Gregory P. Smith634aa682014-06-15 17:51:04 -07002118 subprocess.Popen([sys.executable, %r] +
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002119 [str(x) for x in range({max_fd})],
Gregory P. Smithffd529c2014-06-01 13:46:54 -07002120 close_fds=True).wait()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002121 """.format(max_fd=max_fd_open+1))],
2122 close_fds=False).wait()
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002123 finally:
2124 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
Gregory P. Smith634aa682014-06-15 17:51:04 -07002125 ''' % fd_status)], stdout=subprocess.PIPE)
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002126
2127 output, unused_stderr = p.communicate()
Gregory P. Smith634aa682014-06-15 17:51:04 -07002128 output_lines = output.splitlines()
2129 self.assertEqual(len(output_lines), 2,
Gregory P. Smith9204e092014-06-15 20:16:01 -07002130 msg="expected exactly two lines of output:\n%r" % output)
Gregory P. Smith634aa682014-06-15 17:51:04 -07002131 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
2132 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002133
Gregory P. Smith634aa682014-06-15 17:51:04 -07002134 self.assertFalse(remaining_fds & opened_fds,
Gregory P. Smithd4dcb702014-06-01 13:18:28 -07002135 msg="Some fds were left open.")
2136
2137
Victor Stinner88701e22011-06-01 13:13:04 +02002138 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
2139 # descriptor of a pipe closed in the parent process is valid in the
2140 # child process according to fstat(), but the mode of the file
2141 # descriptor is invalid, and read or write raise an error.
2142 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002143 def test_pass_fds(self):
2144 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2145
2146 open_fds = set()
2147
2148 for x in range(5):
2149 fds = os.pipe()
2150 self.addCleanup(os.close, fds[0])
2151 self.addCleanup(os.close, fds[1])
Victor Stinnerdaf45552013-08-28 00:53:59 +02002152 os.set_inheritable(fds[0], True)
2153 os.set_inheritable(fds[1], True)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00002154 open_fds.update(fds)
2155
2156 for fd in open_fds:
2157 p = subprocess.Popen([sys.executable, fd_status],
2158 stdout=subprocess.PIPE, close_fds=True,
2159 pass_fds=(fd, ))
2160 output, ignored = p.communicate()
2161
2162 remaining_fds = set(map(int, output.split(b',')))
2163 to_be_closed = open_fds - {fd}
2164
2165 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
2166 self.assertFalse(remaining_fds & to_be_closed,
2167 "fd to be closed passed")
2168
2169 # pass_fds overrides close_fds with a warning.
2170 with self.assertWarns(RuntimeWarning) as context:
2171 self.assertFalse(subprocess.call(
2172 [sys.executable, "-c", "import sys; sys.exit(0)"],
2173 close_fds=False, pass_fds=(fd, )))
2174 self.assertIn('overriding close_fds', str(context.warning))
2175
Victor Stinnerdaf45552013-08-28 00:53:59 +02002176 def test_pass_fds_inheritable(self):
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002177 script = support.findfile("fd_status.py", subdir="subprocessdata")
Victor Stinnerdaf45552013-08-28 00:53:59 +02002178
2179 inheritable, non_inheritable = os.pipe()
2180 self.addCleanup(os.close, inheritable)
2181 self.addCleanup(os.close, non_inheritable)
2182 os.set_inheritable(inheritable, True)
2183 os.set_inheritable(non_inheritable, False)
2184 pass_fds = (inheritable, non_inheritable)
2185 args = [sys.executable, script]
2186 args += list(map(str, pass_fds))
2187
2188 p = subprocess.Popen(args,
2189 stdout=subprocess.PIPE, close_fds=True,
2190 pass_fds=pass_fds)
2191 output, ignored = p.communicate()
2192 fds = set(map(int, output.split(b',')))
2193
2194 # the inheritable file descriptor must be inherited, so its inheritable
2195 # flag must be set in the child process after fork() and before exec()
Victor Stinnerf6fa22e2013-09-01 10:22:41 +02002196 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
Victor Stinnerdaf45552013-08-28 00:53:59 +02002197
2198 # inheritable flag must not be changed in the parent process
2199 self.assertEqual(os.get_inheritable(inheritable), True)
2200 self.assertEqual(os.get_inheritable(non_inheritable), False)
2201
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002202 def test_stdout_stdin_are_single_inout_fd(self):
2203 with io.open(os.devnull, "r+") as inout:
2204 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2205 stdout=inout, stdin=inout)
2206 p.wait()
2207
2208 def test_stdout_stderr_are_single_inout_fd(self):
2209 with io.open(os.devnull, "r+") as inout:
2210 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2211 stdout=inout, stderr=inout)
2212 p.wait()
2213
2214 def test_stderr_stdin_are_single_inout_fd(self):
2215 with io.open(os.devnull, "r+") as inout:
2216 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
2217 stderr=inout, stdin=inout)
2218 p.wait()
2219
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002220 def test_wait_when_sigchild_ignored(self):
2221 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
2222 sigchild_ignore = support.findfile("sigchild_ignore.py",
2223 subdir="subprocessdata")
2224 p = subprocess.Popen([sys.executable, sigchild_ignore],
2225 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2226 stdout, stderr = p.communicate()
2227 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00002228 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002229 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00002230
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002231 def test_select_unbuffered(self):
2232 # Issue #11459: bufsize=0 should really set the pipes as
2233 # unbuffered (and therefore let select() work properly).
2234 select = support.import_module("select")
2235 p = subprocess.Popen([sys.executable, "-c",
2236 'import sys;'
2237 'sys.stdout.write("apple")'],
2238 stdout=subprocess.PIPE,
2239 bufsize=0)
2240 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02002241 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01002242 try:
2243 self.assertEqual(f.read(4), b"appl")
2244 self.assertIn(f, select.select([f], [], [], 0.0)[0])
2245 finally:
2246 p.wait()
2247
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002248 def test_zombie_fast_process_del(self):
2249 # Issue #12650: on Unix, if Popen.__del__() was called before the
2250 # process exited, it wouldn't be added to subprocess._active, and would
2251 # remain a zombie.
2252 # spawn a Popen, and delete its reference before it exits
2253 p = subprocess.Popen([sys.executable, "-c",
2254 'import sys, time;'
2255 'time.sleep(0.2)'],
2256 stdout=subprocess.PIPE,
2257 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002258 self.addCleanup(p.stdout.close)
2259 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002260 ident = id(p)
2261 pid = p.pid
2262 del p
2263 # check that p is in the active processes list
2264 self.assertIn(ident, [id(o) for o in subprocess._active])
2265
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002266 def test_leak_fast_process_del_killed(self):
2267 # Issue #12650: on Unix, if Popen.__del__() was called before the
2268 # process exited, and the process got killed by a signal, it would never
2269 # be removed from subprocess._active, which triggered a FD and memory
2270 # leak.
2271 # spawn a Popen, delete its reference and kill it
2272 p = subprocess.Popen([sys.executable, "-c",
2273 'import time;'
2274 'time.sleep(3)'],
2275 stdout=subprocess.PIPE,
2276 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02002277 self.addCleanup(p.stdout.close)
2278 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002279 ident = id(p)
2280 pid = p.pid
2281 del p
2282 os.kill(pid, signal.SIGKILL)
2283 # check that p is in the active processes list
2284 self.assertIn(ident, [id(o) for o in subprocess._active])
2285
2286 # let some time for the process to exit, and create a new Popen: this
2287 # should trigger the wait() of p
2288 time.sleep(0.2)
Andrew Svetlov3438fa42012-12-17 23:35:18 +02002289 with self.assertRaises(OSError) as c:
Charles-François Natali134a8ba2011-08-18 18:49:39 +02002290 with subprocess.Popen(['nonexisting_i_hope'],
2291 stdout=subprocess.PIPE,
2292 stderr=subprocess.PIPE) as proc:
2293 pass
2294 # p should have been wait()ed on, and removed from the _active list
2295 self.assertRaises(OSError, os.waitpid, pid, 0)
2296 self.assertNotIn(ident, [id(o) for o in subprocess._active])
2297
Charles-François Natali249cdc32013-08-25 18:24:45 +02002298 def test_close_fds_after_preexec(self):
2299 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2300
2301 # this FD is used as dup2() target by preexec_fn, and should be closed
2302 # in the child process
2303 fd = os.dup(1)
2304 self.addCleanup(os.close, fd)
2305
2306 p = subprocess.Popen([sys.executable, fd_status],
2307 stdout=subprocess.PIPE, close_fds=True,
2308 preexec_fn=lambda: os.dup2(1, fd))
2309 output, ignored = p.communicate()
2310
2311 remaining_fds = set(map(int, output.split(b',')))
2312
2313 self.assertNotIn(fd, remaining_fds)
2314
Victor Stinner8f437aa2014-10-05 17:25:19 +02002315 @support.cpython_only
2316 def test_fork_exec(self):
2317 # Issue #22290: fork_exec() must not crash on memory allocation failure
2318 # or other errors
2319 import _posixsubprocess
2320 gc_enabled = gc.isenabled()
2321 try:
2322 # Use a preexec function and enable the garbage collector
2323 # to force fork_exec() to re-enable the garbage collector
2324 # on error.
2325 func = lambda: None
2326 gc.enable()
2327
2328 executable_list = "exec" # error: must be a sequence
2329
2330 for args, exe_list, cwd, env_list in (
2331 (123, [b"exe"], None, [b"env"]),
2332 ([b"arg"], 123, None, [b"env"]),
2333 ([b"arg"], [b"exe"], 123, [b"env"]),
2334 ([b"arg"], [b"exe"], None, 123),
2335 ):
2336 with self.assertRaises(TypeError):
2337 _posixsubprocess.fork_exec(
2338 args, exe_list,
2339 True, [], cwd, env_list,
2340 -1, -1, -1, -1,
2341 1, 2, 3, 4,
2342 True, True, func)
2343 finally:
2344 if not gc_enabled:
2345 gc.disable()
2346
2347
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002348
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002349@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00002350class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002351
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002352 def test_startupinfo(self):
2353 # startupinfo argument
2354 # We uses hardcoded constants, because we do not want to
2355 # depend on win32all.
2356 STARTF_USESHOWWINDOW = 1
2357 SW_MAXIMIZE = 3
2358 startupinfo = subprocess.STARTUPINFO()
2359 startupinfo.dwFlags = STARTF_USESHOWWINDOW
2360 startupinfo.wShowWindow = SW_MAXIMIZE
2361 # Since Python is a console process, it won't be affected
2362 # by wShowWindow, but the argument should be silently
2363 # ignored
2364 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002365 startupinfo=startupinfo)
2366
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002367 def test_creationflags(self):
2368 # creationflags argument
2369 CREATE_NEW_CONSOLE = 16
2370 sys.stderr.write(" a DOS box should flash briefly ...\n")
2371 subprocess.call(sys.executable +
2372 ' -c "import time; time.sleep(0.25)"',
2373 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002374
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002375 def test_invalid_args(self):
2376 # invalid arguments should raise ValueError
2377 self.assertRaises(ValueError, subprocess.call,
2378 [sys.executable, "-c",
2379 "import sys; sys.exit(47)"],
2380 preexec_fn=lambda: 1)
2381 self.assertRaises(ValueError, subprocess.call,
2382 [sys.executable, "-c",
2383 "import sys; sys.exit(47)"],
2384 stdout=subprocess.PIPE,
2385 close_fds=True)
2386
2387 def test_close_fds(self):
2388 # close file descriptors
2389 rc = subprocess.call([sys.executable, "-c",
2390 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002391 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002392 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002393
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002394 def test_shell_sequence(self):
2395 # Run command through the shell (sequence)
2396 newenv = os.environ.copy()
2397 newenv["FRUIT"] = "physalis"
2398 p = subprocess.Popen(["set"], shell=1,
2399 stdout=subprocess.PIPE,
2400 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00002401 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002402 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00002403
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002404 def test_shell_string(self):
2405 # Run command through the shell (string)
2406 newenv = os.environ.copy()
2407 newenv["FRUIT"] = "physalis"
2408 p = subprocess.Popen("set", shell=1,
2409 stdout=subprocess.PIPE,
2410 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00002411 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002412 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002413
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002414 def test_call_string(self):
2415 # call() function with string argument on Windows
2416 rc = subprocess.call(sys.executable +
2417 ' -c "import sys; sys.exit(47)"')
2418 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002419
Florent Xicluna4886d242010-03-08 13:27:26 +00002420 def _kill_process(self, method, *args):
2421 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00002422 p = subprocess.Popen([sys.executable, "-c", """if 1:
2423 import sys, time
2424 sys.stdout.write('x\\n')
2425 sys.stdout.flush()
2426 time.sleep(30)
2427 """],
2428 stdin=subprocess.PIPE,
2429 stdout=subprocess.PIPE,
2430 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00002431 self.addCleanup(p.stdout.close)
2432 self.addCleanup(p.stderr.close)
2433 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00002434 # Wait for the interpreter to be completely initialized before
2435 # sending any signal.
2436 p.stdout.read(1)
2437 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00002438 _, stderr = p.communicate()
2439 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00002440 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00002441 self.assertNotEqual(returncode, 0)
2442
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002443 def _kill_dead_process(self, method, *args):
2444 p = subprocess.Popen([sys.executable, "-c", """if 1:
2445 import sys, time
2446 sys.stdout.write('x\\n')
2447 sys.stdout.flush()
2448 sys.exit(42)
2449 """],
2450 stdin=subprocess.PIPE,
2451 stdout=subprocess.PIPE,
2452 stderr=subprocess.PIPE)
2453 self.addCleanup(p.stdout.close)
2454 self.addCleanup(p.stderr.close)
2455 self.addCleanup(p.stdin.close)
2456 # Wait for the interpreter to be completely initialized before
2457 # sending any signal.
2458 p.stdout.read(1)
2459 # The process should end after this
2460 time.sleep(1)
2461 # This shouldn't raise even though the child is now dead
2462 getattr(p, method)(*args)
2463 _, stderr = p.communicate()
2464 self.assertStderrEqual(stderr, b'')
2465 rc = p.wait()
2466 self.assertEqual(rc, 42)
2467
Florent Xicluna4886d242010-03-08 13:27:26 +00002468 def test_send_signal(self):
2469 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00002470
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002471 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002472 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00002473
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002474 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002475 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00002476
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002477 def test_send_signal_dead(self):
2478 self._kill_dead_process('send_signal', signal.SIGTERM)
2479
2480 def test_kill_dead(self):
2481 self._kill_dead_process('kill')
2482
2483 def test_terminate_dead(self):
2484 self._kill_dead_process('terminate')
2485
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002486class CommandTests(unittest.TestCase):
2487 def test_getoutput(self):
2488 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
2489 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
2490 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00002491
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002492 # we use mkdtemp in the next line to create an empty directory
2493 # under our exclusive control; from that, we can invent a pathname
2494 # that we _know_ won't exist. This is guaranteed to fail.
2495 dir = None
2496 try:
2497 dir = tempfile.mkdtemp()
2498 name = os.path.join(dir, "foo")
Tim Goldene0041752013-11-03 12:53:17 +00002499 status, output = subprocess.getstatusoutput(
2500 ("type " if mswindows else "cat ") + name)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002501 self.assertNotEqual(status, 0)
2502 finally:
2503 if dir is not None:
2504 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00002505
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002506
Charles-François Natali3a4586a2013-11-08 19:56:59 +01002507@unittest.skipUnless(hasattr(selectors, 'PollSelector'),
2508 "Test needs selectors.PollSelector")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002509class ProcessTestCaseNoPoll(ProcessTestCase):
2510 def setUp(self):
Charles-François Natali3a4586a2013-11-08 19:56:59 +01002511 self.orig_selector = subprocess._PopenSelector
2512 subprocess._PopenSelector = selectors.SelectSelector
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002513 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002514
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002515 def tearDown(self):
Charles-François Natali3a4586a2013-11-08 19:56:59 +01002516 subprocess._PopenSelector = self.orig_selector
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002517 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002518
Gregory P. Smithace55862015-04-07 15:57:54 -07002519 def test__all__(self):
2520 """Ensure that __all__ is populated properly."""
Gregory P. Smithcb6fdf22015-04-07 16:11:33 -07002521 intentionally_excluded = set(("list2cmdline",))
Gregory P. Smithace55862015-04-07 15:57:54 -07002522 exported = set(subprocess.__all__)
2523 possible_exports = set()
2524 import types
2525 for name, value in subprocess.__dict__.items():
2526 if name.startswith('_'):
2527 continue
2528 if isinstance(value, (types.ModuleType,)):
2529 continue
2530 possible_exports.add(name)
2531 self.assertEqual(exported, possible_exports - intentionally_excluded)
2532
2533
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002534
Tim Golden126c2962010-08-11 14:20:40 +00002535@unittest.skipUnless(mswindows, "Windows-specific tests")
2536class CommandsWithSpaces (BaseTestCase):
2537
2538 def setUp(self):
2539 super().setUp()
2540 f, fname = mkstemp(".py", "te st")
2541 self.fname = fname.lower ()
2542 os.write(f, b"import sys;"
2543 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
2544 )
2545 os.close(f)
2546
2547 def tearDown(self):
2548 os.remove(self.fname)
2549 super().tearDown()
2550
2551 def with_spaces(self, *args, **kwargs):
2552 kwargs['stdout'] = subprocess.PIPE
2553 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00002554 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00002555 self.assertEqual(
2556 p.stdout.read ().decode("mbcs"),
2557 "2 [%r, 'ab cd']" % self.fname
2558 )
2559
2560 def test_shell_string_with_spaces(self):
2561 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002562 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2563 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002564
2565 def test_shell_sequence_with_spaces(self):
2566 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002567 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002568
2569 def test_noshell_string_with_spaces(self):
2570 # call() function with string argument with spaces on Windows
2571 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2572 "ab cd"))
2573
2574 def test_noshell_sequence_with_spaces(self):
2575 # call() function with sequence argument with spaces on Windows
2576 self.with_spaces([sys.executable, self.fname, "ab cd"])
2577
Brian Curtin79cdb662010-12-03 02:46:02 +00002578
Georg Brandla86b2622012-02-20 21:34:57 +01002579class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00002580
2581 def test_pipe(self):
2582 with subprocess.Popen([sys.executable, "-c",
2583 "import sys;"
2584 "sys.stdout.write('stdout');"
2585 "sys.stderr.write('stderr');"],
2586 stdout=subprocess.PIPE,
2587 stderr=subprocess.PIPE) as proc:
2588 self.assertEqual(proc.stdout.read(), b"stdout")
2589 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2590
2591 self.assertTrue(proc.stdout.closed)
2592 self.assertTrue(proc.stderr.closed)
2593
2594 def test_returncode(self):
2595 with subprocess.Popen([sys.executable, "-c",
2596 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002597 pass
2598 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002599 self.assertEqual(proc.returncode, 100)
2600
2601 def test_communicate_stdin(self):
2602 with subprocess.Popen([sys.executable, "-c",
2603 "import sys;"
2604 "sys.exit(sys.stdin.read() == 'context')"],
2605 stdin=subprocess.PIPE) as proc:
2606 proc.communicate(b"context")
2607 self.assertEqual(proc.returncode, 1)
2608
2609 def test_invalid_args(self):
Andrew Svetlovb1726972012-12-26 23:34:54 +02002610 with self.assertRaises(FileNotFoundError) as c:
Brian Curtin79cdb662010-12-03 02:46:02 +00002611 with subprocess.Popen(['nonexisting_i_hope'],
2612 stdout=subprocess.PIPE,
2613 stderr=subprocess.PIPE) as proc:
2614 pass
2615
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002616 def test_broken_pipe_cleanup(self):
2617 """Broken pipe error should not prevent wait() (Issue 21619)"""
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002618 proc = subprocess.Popen([sys.executable, '-c', 'pass'],
Victor Stinner20f4bd42015-03-05 02:38:41 +01002619 stdin=subprocess.PIPE,
Victor Stinner20f4bd42015-03-05 02:38:41 +01002620 bufsize=support.PIPE_MAX_SIZE*2)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002621 proc = proc.__enter__()
2622 # Prepare to send enough data to overflow any OS pipe buffering and
2623 # guarantee a broken pipe error. Data is held in BufferedWriter
2624 # buffer until closed.
2625 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002626 self.assertIsNone(proc.returncode)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002627 # EPIPE expected under POSIX; EINVAL under Windows
Serhiy Storchakacf265fd2015-02-28 13:27:54 +02002628 self.assertRaises(OSError, proc.__exit__, None, None, None)
Serhiy Storchakaf87afb02015-03-08 09:16:40 +02002629 self.assertEqual(proc.returncode, 0)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002630 self.assertTrue(proc.stdin.closed)
Serhiy Storchakaab900c22015-02-28 12:43:08 +02002631
Brian Curtin79cdb662010-12-03 02:46:02 +00002632
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002633def test_main():
2634 unit_tests = (ProcessTestCase,
2635 POSIXProcessTestCase,
2636 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002637 CommandTests,
2638 ProcessTestCaseNoPoll,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002639 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02002640 ContextManagerTests,
Gregory P. Smith6e730002015-04-14 16:14:25 -07002641 RunFuncTestCase,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02002642 )
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002643
2644 support.run_unittest(*unit_tests)
2645 support.reap_children()
2646
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002647if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002648 unittest.main()