blob: b1e9027999f4589088681ebd024283cb19f037b6 [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
Chris Jerdonekec3ea942012-09-30 00:10:28 -07002from test 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. Smithe14e9c22011-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
Ezio Melotti184bdfb2010-02-18 09:37:05 +000014import sysconfig
Gregory P. Smithd23047b2010-12-04 09:10:44 +000015import warnings
Gregory P. Smith51ee2702010-12-13 07:59:39 +000016import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040017import shutil
Benjamin Petersonb870aa12011-12-10 12:44:25 -050018import gc
Benjamin Peterson964561b2011-12-10 12:31:42 -050019
20try:
21 import resource
22except ImportError:
23 resource = None
24
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000025mswindows = (sys.platform == "win32")
26
27#
28# Depends on the following external programs: Python
29#
30
31if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000032 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
33 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000034else:
35 SETBINARY = ''
36
Florent Xiclunab1e94e82010-02-27 22:12:37 +000037
38try:
39 mkstemp = tempfile.mkstemp
40except AttributeError:
41 # tempfile.mkstemp is not available
42 def mkstemp():
43 """Replacement for mkstemp, calling mktemp."""
44 fname = tempfile.mktemp()
45 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
46
Tim Peters3761e8d2004-10-13 04:07:12 +000047
Florent Xiclunac049d872010-03-27 22:47:23 +000048class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000049 def setUp(self):
50 # Try to minimize the number of children we have so this test
51 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000052 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000053
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000054 def tearDown(self):
55 for inst in subprocess._active:
56 inst.wait()
57 subprocess._cleanup()
58 self.assertFalse(subprocess._active, "subprocess._active not empty")
59
Florent Xiclunab1e94e82010-02-27 22:12:37 +000060 def assertStderrEqual(self, stderr, expected, msg=None):
61 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
62 # shutdown time. That frustrates tests trying to check stderr produced
63 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000064 actual = support.strip_python_stderr(stderr)
Florent Xiclunab1e94e82010-02-27 22:12:37 +000065 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000066
Florent Xiclunac049d872010-03-27 22:47:23 +000067
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080068class PopenTestException(Exception):
69 pass
70
71
72class PopenExecuteChildRaises(subprocess.Popen):
73 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
74 _execute_child fails.
75 """
76 def _execute_child(self, *args, **kwargs):
77 raise PopenTestException("Forced Exception for Test")
78
79
Florent Xiclunac049d872010-03-27 22:47:23 +000080class ProcessTestCase(BaseTestCase):
81
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000082 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000083 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000084 rc = subprocess.call([sys.executable, "-c",
85 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000086 self.assertEqual(rc, 47)
87
Peter Astrand454f7672005-01-01 09:36:35 +000088 def test_check_call_zero(self):
89 # check_call() function with zero return code
90 rc = subprocess.check_call([sys.executable, "-c",
91 "import sys; sys.exit(0)"])
92 self.assertEqual(rc, 0)
93
94 def test_check_call_nonzero(self):
95 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000096 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +000097 subprocess.check_call([sys.executable, "-c",
98 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000099 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000100
Georg Brandlf9734072008-12-07 15:30:06 +0000101 def test_check_output(self):
102 # check_output() function with zero return code
103 output = subprocess.check_output(
104 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000105 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000106
107 def test_check_output_nonzero(self):
108 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000109 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000110 subprocess.check_output(
111 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000112 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000113
114 def test_check_output_stderr(self):
115 # check_output() function stderr redirected to stdout
116 output = subprocess.check_output(
117 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
118 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000119 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000120
121 def test_check_output_stdout_arg(self):
122 # check_output() function stderr redirected to stdout
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000123 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000124 output = subprocess.check_output(
125 [sys.executable, "-c", "print('will not be run')"],
126 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000127 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000128 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000129
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000130 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000131 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000132 newenv = os.environ.copy()
133 newenv["FRUIT"] = "banana"
134 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000135 'import sys, os;'
136 'sys.exit(os.getenv("FRUIT")=="banana")'],
137 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000138 self.assertEqual(rc, 1)
139
Victor Stinner87b9bc32011-06-01 00:57:47 +0200140 def test_invalid_args(self):
141 # Popen() called with invalid arguments should raise TypeError
142 # but Popen.__del__ should not complain (issue #12085)
143 with support.captured_stderr() as s:
144 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
145 argcount = subprocess.Popen.__init__.__code__.co_argcount
146 too_many_args = [0] * (argcount + 1)
147 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
148 self.assertEqual(s.getvalue(), '')
149
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000150 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000151 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000152 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000153 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000154 self.addCleanup(p.stdout.close)
155 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000156 p.wait()
157 self.assertEqual(p.stdin, None)
158
159 def test_stdout_none(self):
Ezio Melotti42a541b2013-03-11 05:53:34 +0200160 # .stdout is None when not redirected, and the child's stdout will
161 # be inherited from the parent. In order to test this we run a
162 # subprocess in a subprocess:
163 # this_test
164 # \-- subprocess created by this test (parent)
165 # \-- subprocess created by the parent subprocess (child)
166 # The parent doesn't specify stdout, so the child will use the
167 # parent's stdout. This test checks that the message printed by the
168 # child goes to the parent stdout. The parent also checks that the
169 # child's stdout is None. See #11963.
170 code = ('import sys; from subprocess import Popen, PIPE;'
171 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
172 ' stdin=PIPE, stderr=PIPE);'
173 'p.wait(); assert p.stdout is None;')
174 p = subprocess.Popen([sys.executable, "-c", code],
175 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
176 self.addCleanup(p.stdout.close)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000177 self.addCleanup(p.stderr.close)
Ezio Melotti42a541b2013-03-11 05:53:34 +0200178 out, err = p.communicate()
179 self.assertEqual(p.returncode, 0, err)
180 self.assertEqual(out.rstrip(), b'test_stdout_none')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000181
182 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000183 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000184 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000185 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000186 self.addCleanup(p.stdout.close)
187 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000188 p.wait()
189 self.assertEqual(p.stderr, None)
190
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700191 # For use in the test_cwd* tests below.
192 def _normalize_cwd(self, cwd):
193 # Normalize an expected cwd (for Tru64 support).
194 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
195 # strings. See bug #1063571.
196 original_cwd = os.getcwd()
197 os.chdir(cwd)
198 cwd = os.getcwd()
199 os.chdir(original_cwd)
200 return cwd
201
202 # For use in the test_cwd* tests below.
203 def _split_python_path(self):
204 # Return normalized (python_dir, python_base).
205 python_path = os.path.realpath(sys.executable)
206 return os.path.split(python_path)
207
208 # For use in the test_cwd* tests below.
209 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
210 # Invoke Python via Popen, and assert that (1) the call succeeds,
211 # and that (2) the current working directory of the child process
212 # matches *expected_cwd*.
213 p = subprocess.Popen([python_arg, "-c",
214 "import os, sys; "
215 "sys.stdout.write(os.getcwd()); "
216 "sys.exit(47)"],
217 stdout=subprocess.PIPE,
218 **kwargs)
219 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000220 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700221 self.assertEqual(47, p.returncode)
222 normcase = os.path.normcase
223 self.assertEqual(normcase(expected_cwd),
224 normcase(p.stdout.read().decode("utf-8")))
225
226 def test_cwd(self):
227 # Check that cwd changes the cwd for the child process.
228 temp_dir = tempfile.gettempdir()
229 temp_dir = self._normalize_cwd(temp_dir)
230 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
231
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700232 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700233 def test_cwd_with_relative_arg(self):
234 # Check that Popen looks for args[0] relative to cwd if args[0]
235 # is relative.
236 python_dir, python_base = self._split_python_path()
237 rel_python = os.path.join(os.curdir, python_base)
238 with support.temp_cwd() as wrong_dir:
239 # Before calling with the correct cwd, confirm that the call fails
240 # without cwd and with the wrong cwd.
241 self.assertRaises(OSError, subprocess.Popen,
242 [rel_python])
243 self.assertRaises(OSError, subprocess.Popen,
244 [rel_python], cwd=wrong_dir)
245 python_dir = self._normalize_cwd(python_dir)
246 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
247
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700248 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700249 def test_cwd_with_relative_executable(self):
250 # Check that Popen looks for executable relative to cwd if executable
251 # is relative (and that executable takes precedence over args[0]).
252 python_dir, python_base = self._split_python_path()
253 rel_python = os.path.join(os.curdir, python_base)
254 doesntexist = "somethingyoudonthave"
255 with support.temp_cwd() as wrong_dir:
256 # Before calling with the correct cwd, confirm that the call fails
257 # without cwd and with the wrong cwd.
258 self.assertRaises(OSError, subprocess.Popen,
259 [doesntexist], executable=rel_python)
260 self.assertRaises(OSError, subprocess.Popen,
261 [doesntexist], executable=rel_python,
262 cwd=wrong_dir)
263 python_dir = self._normalize_cwd(python_dir)
264 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
265 cwd=python_dir)
266
267 def test_cwd_with_absolute_arg(self):
268 # Check that Popen can find the executable when the cwd is wrong
269 # if args[0] is an absolute path.
270 python_dir, python_base = self._split_python_path()
271 abs_python = os.path.join(python_dir, python_base)
272 rel_python = os.path.join(os.curdir, python_base)
273 with script_helper.temp_dir() as wrong_dir:
274 # Before calling with an absolute path, confirm that using a
275 # relative path fails.
276 self.assertRaises(OSError, subprocess.Popen,
277 [rel_python], cwd=wrong_dir)
278 wrong_dir = self._normalize_cwd(wrong_dir)
279 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
280
281 def test_executable_with_cwd(self):
282 python_dir, python_base = self._split_python_path()
283 python_dir = self._normalize_cwd(python_dir)
284 self._assert_cwd(python_dir, "somethingyoudonthave",
285 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000286
287 @unittest.skipIf(sysconfig.is_python_build(),
288 "need an installed Python. See #7774")
289 def test_executable_without_cwd(self):
290 # For a normal installation, it should work without 'cwd'
291 # argument. For test runs in the build directory, see #7774.
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700292 self._assert_cwd('', "somethingyoudonthave", executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000293
294 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000295 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000296 p = subprocess.Popen([sys.executable, "-c",
297 'import sys; sys.exit(sys.stdin.read() == "pear")'],
298 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000299 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000300 p.stdin.close()
301 p.wait()
302 self.assertEqual(p.returncode, 1)
303
304 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000305 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000306 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000307 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000308 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000309 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000310 os.lseek(d, 0, 0)
311 p = subprocess.Popen([sys.executable, "-c",
312 'import sys; sys.exit(sys.stdin.read() == "pear")'],
313 stdin=d)
314 p.wait()
315 self.assertEqual(p.returncode, 1)
316
317 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000318 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000319 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000320 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000321 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000322 tf.seek(0)
323 p = subprocess.Popen([sys.executable, "-c",
324 'import sys; sys.exit(sys.stdin.read() == "pear")'],
325 stdin=tf)
326 p.wait()
327 self.assertEqual(p.returncode, 1)
328
329 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000330 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000331 p = subprocess.Popen([sys.executable, "-c",
332 'import sys; sys.stdout.write("orange")'],
333 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000334 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000335 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000336
337 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000338 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000339 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000340 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000341 d = tf.fileno()
342 p = subprocess.Popen([sys.executable, "-c",
343 'import sys; sys.stdout.write("orange")'],
344 stdout=d)
345 p.wait()
346 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000347 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000348
349 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000350 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000351 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000352 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000353 p = subprocess.Popen([sys.executable, "-c",
354 'import sys; sys.stdout.write("orange")'],
355 stdout=tf)
356 p.wait()
357 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000358 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000359
360 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000361 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000362 p = subprocess.Popen([sys.executable, "-c",
363 'import sys; sys.stderr.write("strawberry")'],
364 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000365 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000366 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000367
368 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000369 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000370 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000371 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000372 d = tf.fileno()
373 p = subprocess.Popen([sys.executable, "-c",
374 'import sys; sys.stderr.write("strawberry")'],
375 stderr=d)
376 p.wait()
377 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000378 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000379
380 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000381 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000382 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000383 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000384 p = subprocess.Popen([sys.executable, "-c",
385 'import sys; sys.stderr.write("strawberry")'],
386 stderr=tf)
387 p.wait()
388 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000389 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000390
391 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000392 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000393 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000394 'import sys;'
395 'sys.stdout.write("apple");'
396 'sys.stdout.flush();'
397 'sys.stderr.write("orange")'],
398 stdout=subprocess.PIPE,
399 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000400 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000401 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000402
403 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000404 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000405 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000406 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000407 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000408 'import sys;'
409 'sys.stdout.write("apple");'
410 'sys.stdout.flush();'
411 'sys.stderr.write("orange")'],
412 stdout=tf,
413 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000414 p.wait()
415 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000416 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000417
Thomas Wouters89f507f2006-12-13 04:49:30 +0000418 def test_stdout_filedes_of_stdout(self):
419 # stdout is set to 1 (#1531862).
Ezio Melotti42a541b2013-03-11 05:53:34 +0200420 # To avoid printing the text on stdout, we do something similar to
421 # test_stdout_none (see above). The parent subprocess calls the child
422 # subprocess passing stdout=1, and this test uses stdout=PIPE in
423 # order to capture and check the output of the parent. See #11963.
424 code = ('import sys, subprocess; '
425 'rc = subprocess.call([sys.executable, "-c", '
426 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
427 'b\'test with stdout=1\'))"], stdout=1); '
428 'assert rc == 18')
429 p = subprocess.Popen([sys.executable, "-c", code],
430 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
431 self.addCleanup(p.stdout.close)
432 self.addCleanup(p.stderr.close)
433 out, err = p.communicate()
434 self.assertEqual(p.returncode, 0, err)
435 self.assertEqual(out.rstrip(), b'test with stdout=1')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000436
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000437 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000438 newenv = os.environ.copy()
439 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200440 with subprocess.Popen([sys.executable, "-c",
441 'import sys,os;'
442 'sys.stdout.write(os.getenv("FRUIT"))'],
443 stdout=subprocess.PIPE,
444 env=newenv) as p:
445 stdout, stderr = p.communicate()
446 self.assertEqual(stdout, b"orange")
447
Victor Stinner62d51182011-06-23 01:02:25 +0200448 # Windows requires at least the SYSTEMROOT environment variable to start
449 # Python
450 @unittest.skipIf(sys.platform == 'win32',
451 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200452 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200453 'the python library cannot be loaded '
454 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200455 def test_empty_env(self):
456 with subprocess.Popen([sys.executable, "-c",
457 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200458 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200459 stdout=subprocess.PIPE,
460 env={}) as p:
461 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200462 self.assertIn(stdout.strip(),
463 (b"[]",
464 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
465 # environment
466 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000467
Peter Astrandcbac93c2005-03-03 20:24:28 +0000468 def test_communicate_stdin(self):
469 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000470 'import sys;'
471 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000472 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000473 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000474 self.assertEqual(p.returncode, 1)
475
476 def test_communicate_stdout(self):
477 p = subprocess.Popen([sys.executable, "-c",
478 'import sys; sys.stdout.write("pineapple")'],
479 stdout=subprocess.PIPE)
480 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000481 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000482 self.assertEqual(stderr, None)
483
484 def test_communicate_stderr(self):
485 p = subprocess.Popen([sys.executable, "-c",
486 'import sys; sys.stderr.write("pineapple")'],
487 stderr=subprocess.PIPE)
488 (stdout, stderr) = p.communicate()
489 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000490 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000491
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000492 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000493 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000494 'import sys,os;'
495 'sys.stderr.write("pineapple");'
496 'sys.stdout.write(sys.stdin.read())'],
497 stdin=subprocess.PIPE,
498 stdout=subprocess.PIPE,
499 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000500 self.addCleanup(p.stdout.close)
501 self.addCleanup(p.stderr.close)
502 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000503 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000504 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000505 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000506
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000507 # Test for the fd leak reported in http://bugs.python.org/issue2791.
508 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000509 for stdin_pipe in (False, True):
510 for stdout_pipe in (False, True):
511 for stderr_pipe in (False, True):
512 options = {}
513 if stdin_pipe:
514 options['stdin'] = subprocess.PIPE
515 if stdout_pipe:
516 options['stdout'] = subprocess.PIPE
517 if stderr_pipe:
518 options['stderr'] = subprocess.PIPE
519 if not options:
520 continue
521 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
522 p.communicate()
523 if p.stdin is not None:
524 self.assertTrue(p.stdin.closed)
525 if p.stdout is not None:
526 self.assertTrue(p.stdout.closed)
527 if p.stderr is not None:
528 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000529
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000530 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000531 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000532 p = subprocess.Popen([sys.executable, "-c",
533 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000534 (stdout, stderr) = p.communicate()
535 self.assertEqual(stdout, None)
536 self.assertEqual(stderr, None)
537
538 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000539 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000540 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000541 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000542 x, y = os.pipe()
543 if mswindows:
544 pipe_buf = 512
545 else:
546 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
547 os.close(x)
548 os.close(y)
549 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000550 'import sys,os;'
551 'sys.stdout.write(sys.stdin.read(47));'
552 'sys.stderr.write("xyz"*%d);'
553 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
554 stdin=subprocess.PIPE,
555 stdout=subprocess.PIPE,
556 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000557 self.addCleanup(p.stdout.close)
558 self.addCleanup(p.stderr.close)
559 self.addCleanup(p.stdin.close)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000560 string_to_write = b"abc"*pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000561 (stdout, stderr) = p.communicate(string_to_write)
562 self.assertEqual(stdout, string_to_write)
563
564 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000565 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000566 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000567 'import sys,os;'
568 'sys.stdout.write(sys.stdin.read())'],
569 stdin=subprocess.PIPE,
570 stdout=subprocess.PIPE,
571 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000572 self.addCleanup(p.stdout.close)
573 self.addCleanup(p.stderr.close)
574 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000575 p.stdin.write(b"banana")
576 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000577 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000578 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000579
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000580 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000581 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000582 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200583 'buf = sys.stdout.buffer;'
584 'buf.write(sys.stdin.readline().encode());'
585 'buf.flush();'
586 'buf.write(b"line2\\n");'
587 'buf.flush();'
588 'buf.write(sys.stdin.read().encode());'
589 'buf.flush();'
590 'buf.write(b"line4\\n");'
591 'buf.flush();'
592 'buf.write(b"line5\\r\\n");'
593 'buf.flush();'
594 'buf.write(b"line6\\r");'
595 'buf.flush();'
596 'buf.write(b"\\nline7");'
597 'buf.flush();'
598 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200599 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000600 stdout=subprocess.PIPE,
601 universal_newlines=1)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200602 p.stdin.write("line1\n")
603 self.assertEqual(p.stdout.readline(), "line1\n")
604 p.stdin.write("line3\n")
605 p.stdin.close()
Brian Curtin3c6a9512010-11-05 03:58:52 +0000606 self.addCleanup(p.stdout.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200607 self.assertEqual(p.stdout.readline(),
608 "line2\n")
609 self.assertEqual(p.stdout.read(6),
610 "line3\n")
611 self.assertEqual(p.stdout.read(),
612 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000613
614 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000615 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000616 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000617 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200618 'buf = sys.stdout.buffer;'
619 'buf.write(b"line2\\n");'
620 'buf.flush();'
621 'buf.write(b"line4\\n");'
622 'buf.flush();'
623 'buf.write(b"line5\\r\\n");'
624 'buf.flush();'
625 'buf.write(b"line6\\r");'
626 'buf.flush();'
627 'buf.write(b"\\nline7");'
628 'buf.flush();'
629 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200630 stderr=subprocess.PIPE,
631 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000632 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000633 self.addCleanup(p.stdout.close)
634 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000635 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200636 self.assertEqual(stdout,
637 "line2\nline4\nline5\nline6\nline7\nline8")
638
639 def test_universal_newlines_communicate_stdin(self):
640 # universal newlines through communicate(), with only stdin
641 p = subprocess.Popen([sys.executable, "-c",
642 'import sys,os;' + SETBINARY + '''\nif True:
643 s = sys.stdin.readline()
644 assert s == "line1\\n", repr(s)
645 s = sys.stdin.read()
646 assert s == "line3\\n", repr(s)
647 '''],
648 stdin=subprocess.PIPE,
649 universal_newlines=1)
650 (stdout, stderr) = p.communicate("line1\nline3\n")
651 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000652
Andrew Svetlovf3765072012-08-14 18:35:17 +0300653 def test_universal_newlines_communicate_input_none(self):
654 # Test communicate(input=None) with universal newlines.
655 #
656 # We set stdout to PIPE because, as of this writing, a different
657 # code path is tested when the number of pipes is zero or one.
658 p = subprocess.Popen([sys.executable, "-c", "pass"],
659 stdin=subprocess.PIPE,
660 stdout=subprocess.PIPE,
661 universal_newlines=True)
662 p.communicate()
663 self.assertEqual(p.returncode, 0)
664
Serhiy Storchakab3f194d2013-02-04 16:47:39 +0200665 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
666 # universal newlines through communicate(), with stdin, stdout, stderr
667 p = subprocess.Popen([sys.executable, "-c",
668 'import sys,os;' + SETBINARY + '''\nif True:
669 s = sys.stdin.buffer.readline()
670 sys.stdout.buffer.write(s)
671 sys.stdout.buffer.write(b"line2\\r")
672 sys.stderr.buffer.write(b"eline2\\n")
673 s = sys.stdin.buffer.read()
674 sys.stdout.buffer.write(s)
675 sys.stdout.buffer.write(b"line4\\n")
676 sys.stdout.buffer.write(b"line5\\r\\n")
677 sys.stderr.buffer.write(b"eline6\\r")
678 sys.stderr.buffer.write(b"eline7\\r\\nz")
679 '''],
680 stdin=subprocess.PIPE,
681 stderr=subprocess.PIPE,
682 stdout=subprocess.PIPE,
683 universal_newlines=True)
684 self.addCleanup(p.stdout.close)
685 self.addCleanup(p.stderr.close)
686 (stdout, stderr) = p.communicate("line1\nline3\n")
687 self.assertEqual(p.returncode, 0)
688 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
689 # Python debug build push something like "[42442 refs]\n"
690 # to stderr at exit of subprocess.
691 # Don't use assertStderrEqual because it strips CR and LF from output.
692 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
693
Andrew Svetlov82860712012-08-19 22:13:41 +0300694 def test_universal_newlines_communicate_encodings(self):
695 # Check that universal newlines mode works for various encodings,
696 # in particular for encodings in the UTF-16 and UTF-32 families.
697 # See issue #15595.
698 #
699 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
700 # without, and UTF-16 and UTF-32.
701 for encoding in ['utf-16', 'utf-32-be']:
702 old_getpreferredencoding = locale.getpreferredencoding
703 # Indirectly via io.TextIOWrapper, Popen() defaults to
704 # locale.getpreferredencoding(False) and earlier in Python 3.2 to
705 # locale.getpreferredencoding().
706 def getpreferredencoding(do_setlocale=True):
707 return encoding
708 code = ("import sys; "
709 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
710 encoding)
711 args = [sys.executable, '-c', code]
712 try:
713 locale.getpreferredencoding = getpreferredencoding
714 # We set stdin to be non-None because, as of this writing,
715 # a different code path is used when the number of pipes is
716 # zero or one.
717 popen = subprocess.Popen(args, universal_newlines=True,
718 stdin=subprocess.PIPE,
719 stdout=subprocess.PIPE)
720 stdout, stderr = popen.communicate(input='')
721 finally:
722 locale.getpreferredencoding = old_getpreferredencoding
723
724 self.assertEqual(stdout, '1\n2\n3\n4')
725
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000726 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000727 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000728 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000729 max_handles = 1026 # too much for most UNIX systems
730 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000731 max_handles = 2050 # too much for (at least some) Windows setups
732 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400733 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000734 try:
735 for i in range(max_handles):
736 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400737 tmpfile = os.path.join(tmpdir, support.TESTFN)
738 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000739 except OSError as e:
740 if e.errno != errno.EMFILE:
741 raise
742 break
743 else:
744 self.skipTest("failed to reach the file descriptor limit "
745 "(tried %d)" % max_handles)
746 # Close a couple of them (should be enough for a subprocess)
747 for i in range(10):
748 os.close(handles.pop())
749 # Loop creating some subprocesses. If one of them leaks some fds,
750 # the next loop iteration will fail by reaching the max fd limit.
751 for i in range(15):
752 p = subprocess.Popen([sys.executable, "-c",
753 "import sys;"
754 "sys.stdout.write(sys.stdin.read())"],
755 stdin=subprocess.PIPE,
756 stdout=subprocess.PIPE,
757 stderr=subprocess.PIPE)
758 data = p.communicate(b"lime")[0]
759 self.assertEqual(data, b"lime")
760 finally:
761 for h in handles:
762 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400763 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000764
765 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000766 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
767 '"a b c" d e')
768 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
769 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000770 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
771 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000772 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
773 'a\\\\\\b "de fg" h')
774 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
775 'a\\\\\\"b c d')
776 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
777 '"a\\\\b c" d e')
778 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
779 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000780 self.assertEqual(subprocess.list2cmdline(['ab', '']),
781 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000782
783
784 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000785 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000786 "-c", "import time; time.sleep(1)"])
787 count = 0
788 while p.poll() is None:
789 time.sleep(0.1)
790 count += 1
791 # We expect that the poll loop probably went around about 10 times,
792 # but, based on system scheduling we can't control, it's possible
793 # poll() never returned None. It "should be" very rare that it
794 # didn't go around at least twice.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000795 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000796 # Subsequent invocations should just return the returncode
797 self.assertEqual(p.poll(), 0)
798
799
800 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000801 p = subprocess.Popen([sys.executable,
802 "-c", "import time; time.sleep(2)"])
803 self.assertEqual(p.wait(), 0)
804 # Subsequent invocations should just return the returncode
805 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000806
Peter Astrand738131d2004-11-30 21:04:45 +0000807
808 def test_invalid_bufsize(self):
809 # an invalid type of the bufsize argument should raise
810 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000811 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000812 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000813
Guido van Rossum46a05a72007-06-07 21:56:45 +0000814 def test_bufsize_is_none(self):
815 # bufsize=None should be the same as bufsize=0.
816 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
817 self.assertEqual(p.wait(), 0)
818 # Again with keyword arg
819 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
820 self.assertEqual(p.wait(), 0)
821
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000822 def test_leaking_fds_on_error(self):
823 # see bug #5179: Popen leaks file descriptors to PIPEs if
824 # the child fails to execute; this will eventually exhaust
825 # the maximum number of open fds. 1024 seems a very common
826 # value for that limit, but Windows has 2048, so we loop
827 # 1024 times (each call leaked two fds).
828 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000829 # Windows raises IOError. Others raise OSError.
830 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000831 subprocess.Popen(['nonexisting_i_hope'],
832 stdout=subprocess.PIPE,
833 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400834 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400835 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000836 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000837
Victor Stinnerb3693582010-05-21 20:13:12 +0000838 def test_issue8780(self):
839 # Ensure that stdout is inherited from the parent
840 # if stdout=PIPE is not used
841 code = ';'.join((
842 'import subprocess, sys',
843 'retcode = subprocess.call('
844 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
845 'assert retcode == 0'))
846 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000847 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000848
Tim Goldenaf5ac392010-08-06 13:03:56 +0000849 def test_handles_closed_on_exception(self):
850 # If CreateProcess exits with an error, ensure the
851 # duplicate output handles are released
852 ifhandle, ifname = mkstemp()
853 ofhandle, ofname = mkstemp()
854 efhandle, efname = mkstemp()
855 try:
856 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
857 stderr=efhandle)
858 except OSError:
859 os.close(ifhandle)
860 os.remove(ifname)
861 os.close(ofhandle)
862 os.remove(ofname)
863 os.close(efhandle)
864 os.remove(efname)
865 self.assertFalse(os.path.exists(ifname))
866 self.assertFalse(os.path.exists(ofname))
867 self.assertFalse(os.path.exists(efname))
868
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200869 def test_communicate_epipe(self):
870 # Issue 10963: communicate() should hide EPIPE
871 p = subprocess.Popen([sys.executable, "-c", 'pass'],
872 stdin=subprocess.PIPE,
873 stdout=subprocess.PIPE,
874 stderr=subprocess.PIPE)
875 self.addCleanup(p.stdout.close)
876 self.addCleanup(p.stderr.close)
877 self.addCleanup(p.stdin.close)
878 p.communicate(b"x" * 2**20)
879
880 def test_communicate_epipe_only_stdin(self):
881 # Issue 10963: communicate() should hide EPIPE
882 p = subprocess.Popen([sys.executable, "-c", 'pass'],
883 stdin=subprocess.PIPE)
884 self.addCleanup(p.stdin.close)
885 time.sleep(2)
886 p.communicate(b"x" * 2**20)
887
Victor Stinner1848db82011-07-05 14:49:46 +0200888 @unittest.skipUnless(hasattr(signal, 'SIGALRM'),
889 "Requires signal.SIGALRM")
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200890 def test_communicate_eintr(self):
891 # Issue #12493: communicate() should handle EINTR
892 def handler(signum, frame):
893 pass
894 old_handler = signal.signal(signal.SIGALRM, handler)
895 self.addCleanup(signal.signal, signal.SIGALRM, old_handler)
896
897 # the process is running for 2 seconds
898 args = [sys.executable, "-c", 'import time; time.sleep(2)']
899 for stream in ('stdout', 'stderr'):
900 kw = {stream: subprocess.PIPE}
901 with subprocess.Popen(args, **kw) as process:
902 signal.alarm(1)
903 # communicate() will be interrupted by SIGALRM
904 process.communicate()
905
Tim Peterse718f612004-10-12 21:51:32 +0000906
Gregory P. Smith3d8e7762012-11-10 22:32:22 -0800907 # This test is Linux-ish specific for simplicity to at least have
908 # some coverage. It is not a platform specific bug.
909 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
910 "Linux specific")
911 def test_failed_child_execute_fd_leak(self):
912 """Test for the fork() failure fd leak reported in issue16327."""
913 fd_directory = '/proc/%d/fd' % os.getpid()
914 fds_before_popen = os.listdir(fd_directory)
915 with self.assertRaises(PopenTestException):
916 PopenExecuteChildRaises(
917 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
918 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
919
920 # NOTE: This test doesn't verify that the real _execute_child
921 # does not close the file descriptors itself on the way out
922 # during an exception. Code inspection has confirmed that.
923
924 fds_after_exception = os.listdir(fd_directory)
925 self.assertEqual(fds_before_popen, fds_after_exception)
926
927
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000928# context manager
929class _SuppressCoreFiles(object):
930 """Try to prevent core files from being created."""
931 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000932
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000933 def __enter__(self):
934 """Try to save previous ulimit, then set it to (0, 0)."""
Benjamin Peterson964561b2011-12-10 12:31:42 -0500935 if resource is not None:
936 try:
937 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
938 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
939 except (ValueError, resource.error):
940 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000941
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000942 if sys.platform == 'darwin':
943 # Check if the 'Crash Reporter' on OSX was configured
944 # in 'Developer' mode and warn that it will get triggered
945 # when it is.
946 #
947 # This assumes that this context manager is used in tests
948 # that might trigger the next manager.
949 value = subprocess.Popen(['/usr/bin/defaults', 'read',
950 'com.apple.CrashReporter', 'DialogType'],
951 stdout=subprocess.PIPE).communicate()[0]
952 if value.strip() == b'developer':
953 print("this tests triggers the Crash Reporter, "
954 "that is intentional", end='')
955 sys.stdout.flush()
956
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000957 def __exit__(self, *args):
958 """Return core file behavior to default."""
959 if self.old_limit is None:
960 return
Benjamin Peterson964561b2011-12-10 12:31:42 -0500961 if resource is not None:
962 try:
963 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
964 except (ValueError, resource.error):
965 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000966
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000967
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000968@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000969class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000970
Gregory P. Smith5591b022012-10-10 03:34:47 -0700971 def setUp(self):
972 super().setUp()
973 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
974
975 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000976 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -0700977 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000978 except OSError as e:
979 # This avoids hard coding the errno value or the OS perror()
980 # string and instead capture the exception that we want to see
981 # below for comparison.
982 desired_exception = e
Gregory P. Smith5591b022012-10-10 03:34:47 -0700983 desired_exception.strerror += ': ' + repr(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000984 else:
985 self.fail("chdir to nonexistant directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -0700986 self._nonexistent_dir)
987 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000988
Gregory P. Smith5591b022012-10-10 03:34:47 -0700989 def test_exception_cwd(self):
990 """Test error in the child raised in the parent for a bad cwd."""
991 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000992 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000993 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -0700994 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000995 except OSError as e:
996 # Test that the child process chdir failure actually makes
997 # it up to the parent process as the correct exception.
998 self.assertEqual(desired_exception.errno, e.errno)
999 self.assertEqual(desired_exception.strerror, e.strerror)
1000 else:
1001 self.fail("Expected OSError: %s" % desired_exception)
1002
Gregory P. Smith5591b022012-10-10 03:34:47 -07001003 def test_exception_bad_executable(self):
1004 """Test error in the child raised in the parent for a bad executable."""
1005 desired_exception = self._get_chdir_exception()
1006 try:
1007 p = subprocess.Popen([sys.executable, "-c", ""],
1008 executable=self._nonexistent_dir)
1009 except OSError as e:
1010 # Test that the child process exec failure actually makes
1011 # it up to the parent process as the correct exception.
1012 self.assertEqual(desired_exception.errno, e.errno)
1013 self.assertEqual(desired_exception.strerror, e.strerror)
1014 else:
1015 self.fail("Expected OSError: %s" % desired_exception)
1016
1017 def test_exception_bad_args_0(self):
1018 """Test error in the child raised in the parent for a bad args[0]."""
1019 desired_exception = self._get_chdir_exception()
1020 try:
1021 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1022 except OSError as e:
1023 # Test that the child process exec failure actually makes
1024 # it up to the parent process as the correct exception.
1025 self.assertEqual(desired_exception.errno, e.errno)
1026 self.assertEqual(desired_exception.strerror, e.strerror)
1027 else:
1028 self.fail("Expected OSError: %s" % desired_exception)
1029
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001030 def test_restore_signals(self):
1031 # Code coverage for both values of restore_signals to make sure it
1032 # at least does not blow up.
1033 # A test for behavior would be complex. Contributions welcome.
1034 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1035 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1036
1037 def test_start_new_session(self):
1038 # For code coverage of calling setsid(). We don't care if we get an
1039 # EPERM error from it depending on the test execution environment, that
1040 # still indicates that it was called.
1041 try:
1042 output = subprocess.check_output(
1043 [sys.executable, "-c",
1044 "import os; print(os.getpgid(os.getpid()))"],
1045 start_new_session=True)
1046 except OSError as e:
1047 if e.errno != errno.EPERM:
1048 raise
1049 else:
1050 parent_pgid = os.getpgid(os.getpid())
1051 child_pgid = int(output)
1052 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001053
1054 def test_run_abort(self):
1055 # returncode handles signal termination
1056 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001057 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001058 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001059 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001060 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001061
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001062 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001063 # DISCLAIMER: Setting environment variables is *not* a good use
1064 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001065 p = subprocess.Popen([sys.executable, "-c",
1066 'import sys,os;'
1067 'sys.stdout.write(os.getenv("FRUIT"))'],
1068 stdout=subprocess.PIPE,
1069 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +00001070 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001071 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001072
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001073 def test_preexec_exception(self):
1074 def raise_it():
1075 raise ValueError("What if two swallows carried a coconut?")
1076 try:
1077 p = subprocess.Popen([sys.executable, "-c", ""],
1078 preexec_fn=raise_it)
1079 except RuntimeError as e:
1080 self.assertTrue(
1081 subprocess._posixsubprocess,
1082 "Expected a ValueError from the preexec_fn")
1083 except ValueError as e:
1084 self.assertIn("coconut", e.args[0])
1085 else:
1086 self.fail("Exception raised by preexec_fn did not make it "
1087 "to the parent process.")
1088
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001089 class _TestExecuteChildPopen(subprocess.Popen):
1090 """Used to test behavior at the end of _execute_child."""
1091 def __init__(self, testcase, *args, **kwargs):
1092 self._testcase = testcase
1093 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001094
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001095 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001096 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001097 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001098 finally:
1099 # Open a bunch of file descriptors and verify that
1100 # none of them are the same as the ones the Popen
1101 # instance is using for stdin/stdout/stderr.
1102 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1103 for _ in range(8)]
1104 try:
1105 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001106 self._testcase.assertNotIn(
1107 fd, (self.stdin.fileno(), self.stdout.fileno(),
1108 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001109 msg="At least one fd was closed early.")
1110 finally:
1111 map(os.close, devzero_fds)
1112
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001113 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1114 def test_preexec_errpipe_does_not_double_close_pipes(self):
1115 """Issue16140: Don't double close pipes on preexec error."""
1116
1117 def raise_it():
1118 raise RuntimeError("force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001119
1120 with self.assertRaises(RuntimeError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001121 self._TestExecuteChildPopen(
1122 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001123 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1124 stderr=subprocess.PIPE, preexec_fn=raise_it)
1125
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001126 def test_preexec_gc_module_failure(self):
1127 # This tests the code that disables garbage collection if the child
1128 # process will execute any Python.
1129 def raise_runtime_error():
1130 raise RuntimeError("this shouldn't escape")
1131 enabled = gc.isenabled()
1132 orig_gc_disable = gc.disable
1133 orig_gc_isenabled = gc.isenabled
1134 try:
1135 gc.disable()
1136 self.assertFalse(gc.isenabled())
1137 subprocess.call([sys.executable, '-c', ''],
1138 preexec_fn=lambda: None)
1139 self.assertFalse(gc.isenabled(),
1140 "Popen enabled gc when it shouldn't.")
1141
1142 gc.enable()
1143 self.assertTrue(gc.isenabled())
1144 subprocess.call([sys.executable, '-c', ''],
1145 preexec_fn=lambda: None)
1146 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1147
1148 gc.disable = raise_runtime_error
1149 self.assertRaises(RuntimeError, subprocess.Popen,
1150 [sys.executable, '-c', ''],
1151 preexec_fn=lambda: None)
1152
1153 del gc.isenabled # force an AttributeError
1154 self.assertRaises(AttributeError, subprocess.Popen,
1155 [sys.executable, '-c', ''],
1156 preexec_fn=lambda: None)
1157 finally:
1158 gc.disable = orig_gc_disable
1159 gc.isenabled = orig_gc_isenabled
1160 if not enabled:
1161 gc.disable()
1162
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001163 def test_args_string(self):
1164 # args is a string
1165 fd, fname = mkstemp()
1166 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001167 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001168 fobj.write("#!/bin/sh\n")
1169 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1170 sys.executable)
1171 os.chmod(fname, 0o700)
1172 p = subprocess.Popen(fname)
1173 p.wait()
1174 os.remove(fname)
1175 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001176
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001177 def test_invalid_args(self):
1178 # invalid arguments should raise ValueError
1179 self.assertRaises(ValueError, subprocess.call,
1180 [sys.executable, "-c",
1181 "import sys; sys.exit(47)"],
1182 startupinfo=47)
1183 self.assertRaises(ValueError, subprocess.call,
1184 [sys.executable, "-c",
1185 "import sys; sys.exit(47)"],
1186 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001187
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001188 def test_shell_sequence(self):
1189 # Run command through the shell (sequence)
1190 newenv = os.environ.copy()
1191 newenv["FRUIT"] = "apple"
1192 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1193 stdout=subprocess.PIPE,
1194 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001195 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001196 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001197
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001198 def test_shell_string(self):
1199 # Run command through the shell (string)
1200 newenv = os.environ.copy()
1201 newenv["FRUIT"] = "apple"
1202 p = subprocess.Popen("echo $FRUIT", shell=1,
1203 stdout=subprocess.PIPE,
1204 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001205 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001206 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001207
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001208 def test_call_string(self):
1209 # call() function with string argument on UNIX
1210 fd, fname = mkstemp()
1211 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001212 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001213 fobj.write("#!/bin/sh\n")
1214 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1215 sys.executable)
1216 os.chmod(fname, 0o700)
1217 rc = subprocess.call(fname)
1218 os.remove(fname)
1219 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001220
Stefan Krah9542cc62010-07-19 14:20:53 +00001221 def test_specific_shell(self):
1222 # Issue #9265: Incorrect name passed as arg[0].
1223 shells = []
1224 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1225 for name in ['bash', 'ksh']:
1226 sh = os.path.join(prefix, name)
1227 if os.path.isfile(sh):
1228 shells.append(sh)
1229 if not shells: # Will probably work for any shell but csh.
1230 self.skipTest("bash or ksh required for this test")
1231 sh = '/bin/sh'
1232 if os.path.isfile(sh) and not os.path.islink(sh):
1233 # Test will fail if /bin/sh is a symlink to csh.
1234 shells.append(sh)
1235 for sh in shells:
1236 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1237 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001238 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001239 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1240
Florent Xicluna4886d242010-03-08 13:27:26 +00001241 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001242 # Do not inherit file handles from the parent.
1243 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001244 p = subprocess.Popen([sys.executable, "-c", """if 1:
1245 import sys, time
1246 sys.stdout.write('x\\n')
1247 sys.stdout.flush()
1248 time.sleep(30)
1249 """],
1250 close_fds=True,
1251 stdin=subprocess.PIPE,
1252 stdout=subprocess.PIPE,
1253 stderr=subprocess.PIPE)
1254 # Wait for the interpreter to be completely initialized before
1255 # sending any signal.
1256 p.stdout.read(1)
1257 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001258 return p
1259
Charles-François Natali53221e32013-01-12 16:52:20 +01001260 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
1261 "Due to known OS bug (issue #16762)")
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001262 def _kill_dead_process(self, method, *args):
1263 # Do not inherit file handles from the parent.
1264 # It should fix failures on some platforms.
1265 p = subprocess.Popen([sys.executable, "-c", """if 1:
1266 import sys, time
1267 sys.stdout.write('x\\n')
1268 sys.stdout.flush()
1269 """],
1270 close_fds=True,
1271 stdin=subprocess.PIPE,
1272 stdout=subprocess.PIPE,
1273 stderr=subprocess.PIPE)
1274 # Wait for the interpreter to be completely initialized before
1275 # sending any signal.
1276 p.stdout.read(1)
1277 # The process should end after this
1278 time.sleep(1)
1279 # This shouldn't raise even though the child is now dead
1280 getattr(p, method)(*args)
1281 p.communicate()
1282
Florent Xicluna4886d242010-03-08 13:27:26 +00001283 def test_send_signal(self):
1284 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001285 _, stderr = p.communicate()
1286 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001287 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001288
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001289 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001290 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001291 _, stderr = p.communicate()
1292 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001293 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001294
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001295 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001296 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001297 _, stderr = p.communicate()
1298 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001299 self.assertEqual(p.wait(), -signal.SIGTERM)
1300
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001301 def test_send_signal_dead(self):
1302 # Sending a signal to a dead process
1303 self._kill_dead_process('send_signal', signal.SIGINT)
1304
1305 def test_kill_dead(self):
1306 # Killing a dead process
1307 self._kill_dead_process('kill')
1308
1309 def test_terminate_dead(self):
1310 # Terminating a dead process
1311 self._kill_dead_process('terminate')
1312
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001313 def check_close_std_fds(self, fds):
1314 # Issue #9905: test that subprocess pipes still work properly with
1315 # some standard fds closed
1316 stdin = 0
1317 newfds = []
1318 for a in fds:
1319 b = os.dup(a)
1320 newfds.append(b)
1321 if a == 0:
1322 stdin = b
1323 try:
1324 for fd in fds:
1325 os.close(fd)
1326 out, err = subprocess.Popen([sys.executable, "-c",
1327 'import sys;'
1328 'sys.stdout.write("apple");'
1329 'sys.stdout.flush();'
1330 'sys.stderr.write("orange")'],
1331 stdin=stdin,
1332 stdout=subprocess.PIPE,
1333 stderr=subprocess.PIPE).communicate()
1334 err = support.strip_python_stderr(err)
1335 self.assertEqual((out, err), (b'apple', b'orange'))
1336 finally:
1337 for b, a in zip(newfds, fds):
1338 os.dup2(b, a)
1339 for b in newfds:
1340 os.close(b)
1341
1342 def test_close_fd_0(self):
1343 self.check_close_std_fds([0])
1344
1345 def test_close_fd_1(self):
1346 self.check_close_std_fds([1])
1347
1348 def test_close_fd_2(self):
1349 self.check_close_std_fds([2])
1350
1351 def test_close_fds_0_1(self):
1352 self.check_close_std_fds([0, 1])
1353
1354 def test_close_fds_0_2(self):
1355 self.check_close_std_fds([0, 2])
1356
1357 def test_close_fds_1_2(self):
1358 self.check_close_std_fds([1, 2])
1359
1360 def test_close_fds_0_1_2(self):
1361 # Issue #10806: test that subprocess pipes still work properly with
1362 # all standard fds closed.
1363 self.check_close_std_fds([0, 1, 2])
1364
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001365 def test_remapping_std_fds(self):
1366 # open up some temporary files
1367 temps = [mkstemp() for i in range(3)]
1368 try:
1369 temp_fds = [fd for fd, fname in temps]
1370
1371 # unlink the files -- we won't need to reopen them
1372 for fd, fname in temps:
1373 os.unlink(fname)
1374
1375 # write some data to what will become stdin, and rewind
1376 os.write(temp_fds[1], b"STDIN")
1377 os.lseek(temp_fds[1], 0, 0)
1378
1379 # move the standard file descriptors out of the way
1380 saved_fds = [os.dup(fd) for fd in range(3)]
1381 try:
1382 # duplicate the file objects over the standard fd's
1383 for fd, temp_fd in enumerate(temp_fds):
1384 os.dup2(temp_fd, fd)
1385
1386 # now use those files in the "wrong" order, so that subprocess
1387 # has to rearrange them in the child
1388 p = subprocess.Popen([sys.executable, "-c",
1389 'import sys; got = sys.stdin.read();'
1390 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1391 stdin=temp_fds[1],
1392 stdout=temp_fds[2],
1393 stderr=temp_fds[0])
1394 p.wait()
1395 finally:
1396 # restore the original fd's underneath sys.stdin, etc.
1397 for std, saved in enumerate(saved_fds):
1398 os.dup2(saved, std)
1399 os.close(saved)
1400
1401 for fd in temp_fds:
1402 os.lseek(fd, 0, 0)
1403
1404 out = os.read(temp_fds[2], 1024)
1405 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1406 self.assertEqual(out, b"got STDIN")
1407 self.assertEqual(err, b"err")
1408
1409 finally:
1410 for fd in temp_fds:
1411 os.close(fd)
1412
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001413 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1414 # open up some temporary files
1415 temps = [mkstemp() for i in range(3)]
1416 temp_fds = [fd for fd, fname in temps]
1417 try:
1418 # unlink the files -- we won't need to reopen them
1419 for fd, fname in temps:
1420 os.unlink(fname)
1421
1422 # save a copy of the standard file descriptors
1423 saved_fds = [os.dup(fd) for fd in range(3)]
1424 try:
1425 # duplicate the temp files over the standard fd's 0, 1, 2
1426 for fd, temp_fd in enumerate(temp_fds):
1427 os.dup2(temp_fd, fd)
1428
1429 # write some data to what will become stdin, and rewind
1430 os.write(stdin_no, b"STDIN")
1431 os.lseek(stdin_no, 0, 0)
1432
1433 # now use those files in the given order, so that subprocess
1434 # has to rearrange them in the child
1435 p = subprocess.Popen([sys.executable, "-c",
1436 'import sys; got = sys.stdin.read();'
1437 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1438 stdin=stdin_no,
1439 stdout=stdout_no,
1440 stderr=stderr_no)
1441 p.wait()
1442
1443 for fd in temp_fds:
1444 os.lseek(fd, 0, 0)
1445
1446 out = os.read(stdout_no, 1024)
1447 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1448 finally:
1449 for std, saved in enumerate(saved_fds):
1450 os.dup2(saved, std)
1451 os.close(saved)
1452
1453 self.assertEqual(out, b"got STDIN")
1454 self.assertEqual(err, b"err")
1455
1456 finally:
1457 for fd in temp_fds:
1458 os.close(fd)
1459
1460 # When duping fds, if there arises a situation where one of the fds is
1461 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1462 # This tests all combinations of this.
1463 def test_swap_fds(self):
1464 self.check_swap_fds(0, 1, 2)
1465 self.check_swap_fds(0, 2, 1)
1466 self.check_swap_fds(1, 0, 2)
1467 self.check_swap_fds(1, 2, 0)
1468 self.check_swap_fds(2, 0, 1)
1469 self.check_swap_fds(2, 1, 0)
1470
Victor Stinner13bb71c2010-04-23 21:41:56 +00001471 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001472 def prepare():
1473 raise ValueError("surrogate:\uDCff")
1474
1475 try:
1476 subprocess.call(
1477 [sys.executable, "-c", "pass"],
1478 preexec_fn=prepare)
1479 except ValueError as err:
1480 # Pure Python implementations keeps the message
1481 self.assertIsNone(subprocess._posixsubprocess)
1482 self.assertEqual(str(err), "surrogate:\uDCff")
1483 except RuntimeError as err:
1484 # _posixsubprocess uses a default message
1485 self.assertIsNotNone(subprocess._posixsubprocess)
1486 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1487 else:
1488 self.fail("Expected ValueError or RuntimeError")
1489
Victor Stinner13bb71c2010-04-23 21:41:56 +00001490 def test_undecodable_env(self):
1491 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001492 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001493 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001494 env = os.environ.copy()
1495 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001496 # Use C locale to get ascii for the locale encoding to force
1497 # surrogate-escaping of \xFF in the child process; otherwise it can
1498 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001499 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001500 stdout = subprocess.check_output(
1501 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001502 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001503 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001504 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001505
1506 # test bytes
1507 key = key.encode("ascii", "surrogateescape")
1508 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001509 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001510 env = os.environ.copy()
1511 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001512 stdout = subprocess.check_output(
1513 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001514 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001515 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001516 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001517
Victor Stinnerb745a742010-05-18 17:17:23 +00001518 def test_bytes_program(self):
1519 abs_program = os.fsencode(sys.executable)
1520 path, program = os.path.split(sys.executable)
1521 program = os.fsencode(program)
1522
1523 # absolute bytes path
1524 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001525 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001526
1527 # bytes program, unicode PATH
1528 env = os.environ.copy()
1529 env["PATH"] = path
1530 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001531 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001532
1533 # bytes program, bytes PATH
1534 envb = os.environb.copy()
1535 envb[b"PATH"] = os.fsencode(path)
1536 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001537 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001538
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001539 def test_pipe_cloexec(self):
1540 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1541 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1542
1543 p1 = subprocess.Popen([sys.executable, sleeper],
1544 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1545 stderr=subprocess.PIPE, close_fds=False)
1546
1547 self.addCleanup(p1.communicate, b'')
1548
1549 p2 = subprocess.Popen([sys.executable, fd_status],
1550 stdout=subprocess.PIPE, close_fds=False)
1551
1552 output, error = p2.communicate()
1553 result_fds = set(map(int, output.split(b',')))
1554 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1555 p1.stderr.fileno()])
1556
1557 self.assertFalse(result_fds & unwanted_fds,
1558 "Expected no fds from %r to be open in child, "
1559 "found %r" %
1560 (unwanted_fds, result_fds & unwanted_fds))
1561
1562 def test_pipe_cloexec_real_tools(self):
1563 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1564 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1565
1566 subdata = b'zxcvbn'
1567 data = subdata * 4 + b'\n'
1568
1569 p1 = subprocess.Popen([sys.executable, qcat],
1570 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1571 close_fds=False)
1572
1573 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1574 stdin=p1.stdout, stdout=subprocess.PIPE,
1575 close_fds=False)
1576
1577 self.addCleanup(p1.wait)
1578 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001579 def kill_p1():
1580 try:
1581 p1.terminate()
1582 except ProcessLookupError:
1583 pass
1584 def kill_p2():
1585 try:
1586 p2.terminate()
1587 except ProcessLookupError:
1588 pass
1589 self.addCleanup(kill_p1)
1590 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001591
1592 p1.stdin.write(data)
1593 p1.stdin.close()
1594
1595 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1596
1597 self.assertTrue(readfiles, "The child hung")
1598 self.assertEqual(p2.stdout.read(), data)
1599
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001600 p1.stdout.close()
1601 p2.stdout.close()
1602
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001603 def test_close_fds(self):
1604 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1605
1606 fds = os.pipe()
1607 self.addCleanup(os.close, fds[0])
1608 self.addCleanup(os.close, fds[1])
1609
1610 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001611 # add a bunch more fds
1612 for _ in range(9):
1613 fd = os.open("/dev/null", os.O_RDONLY)
1614 self.addCleanup(os.close, fd)
1615 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001616
1617 p = subprocess.Popen([sys.executable, fd_status],
1618 stdout=subprocess.PIPE, close_fds=False)
1619 output, ignored = p.communicate()
1620 remaining_fds = set(map(int, output.split(b',')))
1621
1622 self.assertEqual(remaining_fds & open_fds, open_fds,
1623 "Some fds were closed")
1624
1625 p = subprocess.Popen([sys.executable, fd_status],
1626 stdout=subprocess.PIPE, close_fds=True)
1627 output, ignored = p.communicate()
1628 remaining_fds = set(map(int, output.split(b',')))
1629
1630 self.assertFalse(remaining_fds & open_fds,
1631 "Some fds were left open")
1632 self.assertIn(1, remaining_fds, "Subprocess failed")
1633
Gregory P. Smith8facece2012-01-21 14:01:08 -08001634 # Keep some of the fd's we opened open in the subprocess.
1635 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1636 fds_to_keep = set(open_fds.pop() for _ in range(8))
1637 p = subprocess.Popen([sys.executable, fd_status],
1638 stdout=subprocess.PIPE, close_fds=True,
1639 pass_fds=())
1640 output, ignored = p.communicate()
1641 remaining_fds = set(map(int, output.split(b',')))
1642
1643 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1644 "Some fds not in pass_fds were left open")
1645 self.assertIn(1, remaining_fds, "Subprocess failed")
1646
Victor Stinner88701e22011-06-01 13:13:04 +02001647 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1648 # descriptor of a pipe closed in the parent process is valid in the
1649 # child process according to fstat(), but the mode of the file
1650 # descriptor is invalid, and read or write raise an error.
1651 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001652 def test_pass_fds(self):
1653 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1654
1655 open_fds = set()
1656
1657 for x in range(5):
1658 fds = os.pipe()
1659 self.addCleanup(os.close, fds[0])
1660 self.addCleanup(os.close, fds[1])
1661 open_fds.update(fds)
1662
1663 for fd in open_fds:
1664 p = subprocess.Popen([sys.executable, fd_status],
1665 stdout=subprocess.PIPE, close_fds=True,
1666 pass_fds=(fd, ))
1667 output, ignored = p.communicate()
1668
1669 remaining_fds = set(map(int, output.split(b',')))
1670 to_be_closed = open_fds - {fd}
1671
1672 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1673 self.assertFalse(remaining_fds & to_be_closed,
1674 "fd to be closed passed")
1675
1676 # pass_fds overrides close_fds with a warning.
1677 with self.assertWarns(RuntimeWarning) as context:
1678 self.assertFalse(subprocess.call(
1679 [sys.executable, "-c", "import sys; sys.exit(0)"],
1680 close_fds=False, pass_fds=(fd, )))
1681 self.assertIn('overriding close_fds', str(context.warning))
1682
Gregory P. Smithe14e9c22011-03-15 14:55:17 -04001683 def test_stdout_stdin_are_single_inout_fd(self):
1684 with io.open(os.devnull, "r+") as inout:
1685 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1686 stdout=inout, stdin=inout)
1687 p.wait()
1688
1689 def test_stdout_stderr_are_single_inout_fd(self):
1690 with io.open(os.devnull, "r+") as inout:
1691 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1692 stdout=inout, stderr=inout)
1693 p.wait()
1694
1695 def test_stderr_stdin_are_single_inout_fd(self):
1696 with io.open(os.devnull, "r+") as inout:
1697 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1698 stderr=inout, stdin=inout)
1699 p.wait()
1700
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001701 def test_wait_when_sigchild_ignored(self):
1702 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1703 sigchild_ignore = support.findfile("sigchild_ignore.py",
1704 subdir="subprocessdata")
1705 p = subprocess.Popen([sys.executable, sigchild_ignore],
1706 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1707 stdout, stderr = p.communicate()
1708 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001709 " non-zero with this error:\n%s" %
1710 stderr.decode('utf8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001711
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001712 def test_select_unbuffered(self):
1713 # Issue #11459: bufsize=0 should really set the pipes as
1714 # unbuffered (and therefore let select() work properly).
1715 select = support.import_module("select")
1716 p = subprocess.Popen([sys.executable, "-c",
1717 'import sys;'
1718 'sys.stdout.write("apple")'],
1719 stdout=subprocess.PIPE,
1720 bufsize=0)
1721 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001722 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001723 try:
1724 self.assertEqual(f.read(4), b"appl")
1725 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1726 finally:
1727 p.wait()
1728
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001729 def test_zombie_fast_process_del(self):
1730 # Issue #12650: on Unix, if Popen.__del__() was called before the
1731 # process exited, it wouldn't be added to subprocess._active, and would
1732 # remain a zombie.
1733 # spawn a Popen, and delete its reference before it exits
1734 p = subprocess.Popen([sys.executable, "-c",
1735 'import sys, time;'
1736 'time.sleep(0.2)'],
1737 stdout=subprocess.PIPE,
1738 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001739 self.addCleanup(p.stdout.close)
1740 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001741 ident = id(p)
1742 pid = p.pid
1743 del p
1744 # check that p is in the active processes list
1745 self.assertIn(ident, [id(o) for o in subprocess._active])
1746
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001747 def test_leak_fast_process_del_killed(self):
1748 # Issue #12650: on Unix, if Popen.__del__() was called before the
1749 # process exited, and the process got killed by a signal, it would never
1750 # be removed from subprocess._active, which triggered a FD and memory
1751 # leak.
1752 # spawn a Popen, delete its reference and kill it
1753 p = subprocess.Popen([sys.executable, "-c",
1754 'import time;'
1755 'time.sleep(3)'],
1756 stdout=subprocess.PIPE,
1757 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001758 self.addCleanup(p.stdout.close)
1759 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001760 ident = id(p)
1761 pid = p.pid
1762 del p
1763 os.kill(pid, signal.SIGKILL)
1764 # check that p is in the active processes list
1765 self.assertIn(ident, [id(o) for o in subprocess._active])
1766
1767 # let some time for the process to exit, and create a new Popen: this
1768 # should trigger the wait() of p
1769 time.sleep(0.2)
1770 with self.assertRaises(EnvironmentError) as c:
1771 with subprocess.Popen(['nonexisting_i_hope'],
1772 stdout=subprocess.PIPE,
1773 stderr=subprocess.PIPE) as proc:
1774 pass
1775 # p should have been wait()ed on, and removed from the _active list
1776 self.assertRaises(OSError, os.waitpid, pid, 0)
1777 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1778
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001779
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001780@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001781class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001782
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001783 def test_startupinfo(self):
1784 # startupinfo argument
1785 # We uses hardcoded constants, because we do not want to
1786 # depend on win32all.
1787 STARTF_USESHOWWINDOW = 1
1788 SW_MAXIMIZE = 3
1789 startupinfo = subprocess.STARTUPINFO()
1790 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1791 startupinfo.wShowWindow = SW_MAXIMIZE
1792 # Since Python is a console process, it won't be affected
1793 # by wShowWindow, but the argument should be silently
1794 # ignored
1795 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001796 startupinfo=startupinfo)
1797
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001798 def test_creationflags(self):
1799 # creationflags argument
1800 CREATE_NEW_CONSOLE = 16
1801 sys.stderr.write(" a DOS box should flash briefly ...\n")
1802 subprocess.call(sys.executable +
1803 ' -c "import time; time.sleep(0.25)"',
1804 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001805
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001806 def test_invalid_args(self):
1807 # invalid arguments should raise ValueError
1808 self.assertRaises(ValueError, subprocess.call,
1809 [sys.executable, "-c",
1810 "import sys; sys.exit(47)"],
1811 preexec_fn=lambda: 1)
1812 self.assertRaises(ValueError, subprocess.call,
1813 [sys.executable, "-c",
1814 "import sys; sys.exit(47)"],
1815 stdout=subprocess.PIPE,
1816 close_fds=True)
1817
1818 def test_close_fds(self):
1819 # close file descriptors
1820 rc = subprocess.call([sys.executable, "-c",
1821 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001822 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001823 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001824
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001825 def test_shell_sequence(self):
1826 # Run command through the shell (sequence)
1827 newenv = os.environ.copy()
1828 newenv["FRUIT"] = "physalis"
1829 p = subprocess.Popen(["set"], shell=1,
1830 stdout=subprocess.PIPE,
1831 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001832 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001833 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001834
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001835 def test_shell_string(self):
1836 # Run command through the shell (string)
1837 newenv = os.environ.copy()
1838 newenv["FRUIT"] = "physalis"
1839 p = subprocess.Popen("set", shell=1,
1840 stdout=subprocess.PIPE,
1841 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001842 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001843 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001844
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001845 def test_call_string(self):
1846 # call() function with string argument on Windows
1847 rc = subprocess.call(sys.executable +
1848 ' -c "import sys; sys.exit(47)"')
1849 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001850
Florent Xicluna4886d242010-03-08 13:27:26 +00001851 def _kill_process(self, method, *args):
1852 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001853 p = subprocess.Popen([sys.executable, "-c", """if 1:
1854 import sys, time
1855 sys.stdout.write('x\\n')
1856 sys.stdout.flush()
1857 time.sleep(30)
1858 """],
1859 stdin=subprocess.PIPE,
1860 stdout=subprocess.PIPE,
1861 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001862 self.addCleanup(p.stdout.close)
1863 self.addCleanup(p.stderr.close)
1864 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001865 # Wait for the interpreter to be completely initialized before
1866 # sending any signal.
1867 p.stdout.read(1)
1868 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001869 _, stderr = p.communicate()
1870 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001871 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001872 self.assertNotEqual(returncode, 0)
1873
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001874 def _kill_dead_process(self, method, *args):
1875 p = subprocess.Popen([sys.executable, "-c", """if 1:
1876 import sys, time
1877 sys.stdout.write('x\\n')
1878 sys.stdout.flush()
1879 sys.exit(42)
1880 """],
1881 stdin=subprocess.PIPE,
1882 stdout=subprocess.PIPE,
1883 stderr=subprocess.PIPE)
1884 self.addCleanup(p.stdout.close)
1885 self.addCleanup(p.stderr.close)
1886 self.addCleanup(p.stdin.close)
1887 # Wait for the interpreter to be completely initialized before
1888 # sending any signal.
1889 p.stdout.read(1)
1890 # The process should end after this
1891 time.sleep(1)
1892 # This shouldn't raise even though the child is now dead
1893 getattr(p, method)(*args)
1894 _, stderr = p.communicate()
1895 self.assertStderrEqual(stderr, b'')
1896 rc = p.wait()
1897 self.assertEqual(rc, 42)
1898
Florent Xicluna4886d242010-03-08 13:27:26 +00001899 def test_send_signal(self):
1900 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001901
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001902 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001903 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001904
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001905 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001906 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001907
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001908 def test_send_signal_dead(self):
1909 self._kill_dead_process('send_signal', signal.SIGTERM)
1910
1911 def test_kill_dead(self):
1912 self._kill_dead_process('kill')
1913
1914 def test_terminate_dead(self):
1915 self._kill_dead_process('terminate')
1916
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001917
Brett Cannona23810f2008-05-26 19:04:21 +00001918# The module says:
1919# "NB This only works (and is only relevant) for UNIX."
1920#
1921# Actually, getoutput should work on any platform with an os.popen, but
1922# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001923@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001924class CommandTests(unittest.TestCase):
1925 def test_getoutput(self):
1926 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1927 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1928 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001929
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001930 # we use mkdtemp in the next line to create an empty directory
1931 # under our exclusive control; from that, we can invent a pathname
1932 # that we _know_ won't exist. This is guaranteed to fail.
1933 dir = None
1934 try:
1935 dir = tempfile.mkdtemp()
1936 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001937
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001938 status, output = subprocess.getstatusoutput('cat ' + name)
1939 self.assertNotEqual(status, 0)
1940 finally:
1941 if dir is not None:
1942 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001943
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001944
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001945@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1946 "poll system call not supported")
1947class ProcessTestCaseNoPoll(ProcessTestCase):
1948 def setUp(self):
1949 subprocess._has_poll = False
1950 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001951
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001952 def tearDown(self):
1953 subprocess._has_poll = True
1954 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001955
1956
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001957@unittest.skipUnless(getattr(subprocess, '_posixsubprocess', False),
1958 "_posixsubprocess extension module not found.")
1959class ProcessTestCasePOSIXPurePython(ProcessTestCase, POSIXProcessTestCase):
Gregory P. Smith7439e7b2011-05-28 09:06:02 -07001960 @classmethod
1961 def setUpClass(cls):
1962 global subprocess
1963 assert subprocess._posixsubprocess
1964 # Reimport subprocess while forcing _posixsubprocess to not exist.
1965 with support.check_warnings(('.*_posixsubprocess .* not being used.*',
1966 RuntimeWarning)):
1967 subprocess = support.import_fresh_module(
1968 'subprocess', blocked=['_posixsubprocess'])
1969 assert not subprocess._posixsubprocess
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001970
Gregory P. Smith7439e7b2011-05-28 09:06:02 -07001971 @classmethod
1972 def tearDownClass(cls):
1973 global subprocess
1974 # Reimport subprocess as it should be, restoring order to the universe.
1975 subprocess = support.import_fresh_module('subprocess')
1976 assert subprocess._posixsubprocess
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001977
1978
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001979class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001980 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001981 def test_eintr_retry_call(self):
1982 record_calls = []
1983 def fake_os_func(*args):
1984 record_calls.append(args)
1985 if len(record_calls) == 2:
1986 raise OSError(errno.EINTR, "fake interrupted system call")
1987 return tuple(reversed(args))
1988
1989 self.assertEqual((999, 256),
1990 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1991 self.assertEqual([(256, 999)], record_calls)
1992 # This time there will be an EINTR so it will loop once.
1993 self.assertEqual((666,),
1994 subprocess._eintr_retry_call(fake_os_func, 666))
1995 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1996
1997
Tim Golden126c2962010-08-11 14:20:40 +00001998@unittest.skipUnless(mswindows, "Windows-specific tests")
1999class CommandsWithSpaces (BaseTestCase):
2000
2001 def setUp(self):
2002 super().setUp()
2003 f, fname = mkstemp(".py", "te st")
2004 self.fname = fname.lower ()
2005 os.write(f, b"import sys;"
2006 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
2007 )
2008 os.close(f)
2009
2010 def tearDown(self):
2011 os.remove(self.fname)
2012 super().tearDown()
2013
2014 def with_spaces(self, *args, **kwargs):
2015 kwargs['stdout'] = subprocess.PIPE
2016 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00002017 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00002018 self.assertEqual(
2019 p.stdout.read ().decode("mbcs"),
2020 "2 [%r, 'ab cd']" % self.fname
2021 )
2022
2023 def test_shell_string_with_spaces(self):
2024 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002025 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2026 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002027
2028 def test_shell_sequence_with_spaces(self):
2029 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002030 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002031
2032 def test_noshell_string_with_spaces(self):
2033 # call() function with string argument with spaces on Windows
2034 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2035 "ab cd"))
2036
2037 def test_noshell_sequence_with_spaces(self):
2038 # call() function with sequence argument with spaces on Windows
2039 self.with_spaces([sys.executable, self.fname, "ab cd"])
2040
Brian Curtin79cdb662010-12-03 02:46:02 +00002041
Georg Brandla86b2622012-02-20 21:34:57 +01002042class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00002043
2044 def test_pipe(self):
2045 with subprocess.Popen([sys.executable, "-c",
2046 "import sys;"
2047 "sys.stdout.write('stdout');"
2048 "sys.stderr.write('stderr');"],
2049 stdout=subprocess.PIPE,
2050 stderr=subprocess.PIPE) as proc:
2051 self.assertEqual(proc.stdout.read(), b"stdout")
2052 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2053
2054 self.assertTrue(proc.stdout.closed)
2055 self.assertTrue(proc.stderr.closed)
2056
2057 def test_returncode(self):
2058 with subprocess.Popen([sys.executable, "-c",
2059 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smithc9557af2011-05-11 22:18:23 -07002060 pass
2061 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002062 self.assertEqual(proc.returncode, 100)
2063
2064 def test_communicate_stdin(self):
2065 with subprocess.Popen([sys.executable, "-c",
2066 "import sys;"
2067 "sys.exit(sys.stdin.read() == 'context')"],
2068 stdin=subprocess.PIPE) as proc:
2069 proc.communicate(b"context")
2070 self.assertEqual(proc.returncode, 1)
2071
2072 def test_invalid_args(self):
2073 with self.assertRaises(EnvironmentError) as c:
2074 with subprocess.Popen(['nonexisting_i_hope'],
2075 stdout=subprocess.PIPE,
2076 stderr=subprocess.PIPE) as proc:
2077 pass
2078
Andrew Svetlov57a12332012-12-26 23:31:45 +02002079 self.assertEqual(c.exception.errno, errno.ENOENT)
Brian Curtin79cdb662010-12-03 02:46:02 +00002080
2081
Gregory P. Smith961e0e82011-03-15 15:43:39 -04002082def test_main():
2083 unit_tests = (ProcessTestCase,
2084 POSIXProcessTestCase,
2085 Win32ProcessTestCase,
2086 ProcessTestCasePOSIXPurePython,
2087 CommandTests,
2088 ProcessTestCaseNoPoll,
2089 HelperFunctionTests,
2090 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02002091 ContextManagerTests,
2092 )
Gregory P. Smith961e0e82011-03-15 15:43:39 -04002093
2094 support.run_unittest(*unit_tests)
2095 support.reap_children()
2096
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002097if __name__ == "__main__":
Gregory P. Smithe14e9c22011-03-15 14:55:17 -04002098 unittest.main()