blob: 3dbef13caefe941259866465e0497b3827b237e7 [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. Smith112bb3a2011-03-15 14:55:17 -04007import io
Andrew Svetlov82860712012-08-19 22:13:41 +03008import locale
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00009import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +000010import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000011import tempfile
12import time
Tim Peters3761e8d2004-10-13 04:07:12 +000013import re
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
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030019import textwrap
Benjamin Peterson964561b2011-12-10 12:31:42 -050020
21try:
22 import resource
23except ImportError:
24 resource = None
25
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000026mswindows = (sys.platform == "win32")
27
28#
29# Depends on the following external programs: Python
30#
31
32if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000033 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
34 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000035else:
36 SETBINARY = ''
37
Florent Xiclunab1e94e82010-02-27 22:12:37 +000038
39try:
40 mkstemp = tempfile.mkstemp
41except AttributeError:
42 # tempfile.mkstemp is not available
43 def mkstemp():
44 """Replacement for mkstemp, calling mktemp."""
45 fname = tempfile.mktemp()
46 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
47
Tim Peters3761e8d2004-10-13 04:07:12 +000048
Florent Xiclunac049d872010-03-27 22:47:23 +000049class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000050 def setUp(self):
51 # Try to minimize the number of children we have so this test
52 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000053 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000054
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000055 def tearDown(self):
56 for inst in subprocess._active:
57 inst.wait()
58 subprocess._cleanup()
59 self.assertFalse(subprocess._active, "subprocess._active not empty")
60
Florent Xiclunab1e94e82010-02-27 22:12:37 +000061 def assertStderrEqual(self, stderr, expected, msg=None):
62 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
63 # shutdown time. That frustrates tests trying to check stderr produced
64 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000065 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040066 # strip_python_stderr also strips whitespace, so we do too.
67 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000068 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000069
Florent Xiclunac049d872010-03-27 22:47:23 +000070
71class ProcessTestCase(BaseTestCase):
72
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000073 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000074 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000075 rc = subprocess.call([sys.executable, "-c",
76 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000077 self.assertEqual(rc, 47)
78
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040079 def test_call_timeout(self):
80 # call() function with timeout argument; we want to test that the child
81 # process gets killed when the timeout expires. If the child isn't
82 # killed, this call will deadlock since subprocess.call waits for the
83 # child.
84 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
85 [sys.executable, "-c", "while True: pass"],
86 timeout=0.1)
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
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400130 def test_check_output_timeout(self):
131 # check_output() function with timeout arg
132 with self.assertRaises(subprocess.TimeoutExpired) as c:
133 output = subprocess.check_output(
134 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200135 "import sys, time\n"
136 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400137 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200138 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400139 # Some heavily loaded buildbots (sparc Debian 3.x) require
140 # this much time to start and print.
141 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400142 self.fail("Expected TimeoutExpired.")
143 self.assertEqual(c.exception.output, b'BDFL')
144
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000145 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000146 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000147 newenv = os.environ.copy()
148 newenv["FRUIT"] = "banana"
149 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000150 'import sys, os;'
151 'sys.exit(os.getenv("FRUIT")=="banana")'],
152 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000153 self.assertEqual(rc, 1)
154
Victor Stinner87b9bc32011-06-01 00:57:47 +0200155 def test_invalid_args(self):
156 # Popen() called with invalid arguments should raise TypeError
157 # but Popen.__del__ should not complain (issue #12085)
158 with support.captured_stderr() as s:
159 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
160 argcount = subprocess.Popen.__init__.__code__.co_argcount
161 too_many_args = [0] * (argcount + 1)
162 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
163 self.assertEqual(s.getvalue(), '')
164
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000165 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000166 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000167 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000168 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000169 self.addCleanup(p.stdout.close)
170 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000171 p.wait()
172 self.assertEqual(p.stdin, None)
173
174 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000175 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000176 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000177 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000178 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000179 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000180 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000181 self.addCleanup(p.stdin.close)
182 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000183 p.wait()
184 self.assertEqual(p.stdout, None)
185
186 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000187 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000188 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000189 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000190 self.addCleanup(p.stdout.close)
191 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000192 p.wait()
193 self.assertEqual(p.stderr, None)
194
Chris Jerdonek776cb192012-10-08 15:56:43 -0700195 def _assert_python(self, pre_args, **kwargs):
196 # We include sys.exit() to prevent the test runner from hanging
197 # whenever python is found.
198 args = pre_args + ["import sys; sys.exit(47)"]
199 p = subprocess.Popen(args, **kwargs)
200 p.wait()
201 self.assertEqual(47, p.returncode)
202
203 def test_executable(self):
204 # Check that the executable argument works.
205 self._assert_python(["doesnotexist", "-c"], executable=sys.executable)
206
207 def test_executable_takes_precedence(self):
208 # Check that the executable argument takes precedence over args[0].
209 #
210 # Verify first that the call succeeds without the executable arg.
211 pre_args = [sys.executable, "-c"]
212 self._assert_python(pre_args)
213 self.assertRaises(FileNotFoundError, self._assert_python, pre_args,
214 executable="doesnotexist")
215
216 @unittest.skipIf(mswindows, "executable argument replaces shell")
217 def test_executable_replaces_shell(self):
218 # Check that the executable argument replaces the default shell
219 # when shell=True.
220 self._assert_python([], executable=sys.executable, shell=True)
221
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700222 # For use in the test_cwd* tests below.
223 def _normalize_cwd(self, cwd):
224 # Normalize an expected cwd (for Tru64 support).
225 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
226 # strings. See bug #1063571.
227 original_cwd = os.getcwd()
228 os.chdir(cwd)
229 cwd = os.getcwd()
230 os.chdir(original_cwd)
231 return cwd
232
233 # For use in the test_cwd* tests below.
234 def _split_python_path(self):
235 # Return normalized (python_dir, python_base).
236 python_path = os.path.realpath(sys.executable)
237 return os.path.split(python_path)
238
239 # For use in the test_cwd* tests below.
240 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
241 # Invoke Python via Popen, and assert that (1) the call succeeds,
242 # and that (2) the current working directory of the child process
243 # matches *expected_cwd*.
244 p = subprocess.Popen([python_arg, "-c",
245 "import os, sys; "
246 "sys.stdout.write(os.getcwd()); "
247 "sys.exit(47)"],
248 stdout=subprocess.PIPE,
249 **kwargs)
250 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000251 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700252 self.assertEqual(47, p.returncode)
253 normcase = os.path.normcase
254 self.assertEqual(normcase(expected_cwd),
255 normcase(p.stdout.read().decode("utf-8")))
256
257 def test_cwd(self):
258 # Check that cwd changes the cwd for the child process.
259 temp_dir = tempfile.gettempdir()
260 temp_dir = self._normalize_cwd(temp_dir)
261 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
262
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700263 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700264 def test_cwd_with_relative_arg(self):
265 # Check that Popen looks for args[0] relative to cwd if args[0]
266 # is relative.
267 python_dir, python_base = self._split_python_path()
268 rel_python = os.path.join(os.curdir, python_base)
269 with support.temp_cwd() as wrong_dir:
270 # Before calling with the correct cwd, confirm that the call fails
271 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700272 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700273 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700274 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700275 [rel_python], cwd=wrong_dir)
276 python_dir = self._normalize_cwd(python_dir)
277 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
278
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700279 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700280 def test_cwd_with_relative_executable(self):
281 # Check that Popen looks for executable relative to cwd if executable
282 # is relative (and that executable takes precedence over args[0]).
283 python_dir, python_base = self._split_python_path()
284 rel_python = os.path.join(os.curdir, python_base)
285 doesntexist = "somethingyoudonthave"
286 with support.temp_cwd() as wrong_dir:
287 # Before calling with the correct cwd, confirm that the call fails
288 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700289 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700290 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700291 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700292 [doesntexist], executable=rel_python,
293 cwd=wrong_dir)
294 python_dir = self._normalize_cwd(python_dir)
295 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
296 cwd=python_dir)
297
298 def test_cwd_with_absolute_arg(self):
299 # Check that Popen can find the executable when the cwd is wrong
300 # if args[0] is an absolute path.
301 python_dir, python_base = self._split_python_path()
302 abs_python = os.path.join(python_dir, python_base)
303 rel_python = os.path.join(os.curdir, python_base)
304 with script_helper.temp_dir() as wrong_dir:
305 # Before calling with an absolute path, confirm that using a
306 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700307 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700308 [rel_python], cwd=wrong_dir)
309 wrong_dir = self._normalize_cwd(wrong_dir)
310 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
311
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100312 @unittest.skipIf(sys.base_prefix != sys.prefix,
313 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000314 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700315 python_dir, python_base = self._split_python_path()
316 python_dir = self._normalize_cwd(python_dir)
317 self._assert_cwd(python_dir, "somethingyoudonthave",
318 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000319
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100320 @unittest.skipIf(sys.base_prefix != sys.prefix,
321 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000322 @unittest.skipIf(sysconfig.is_python_build(),
323 "need an installed Python. See #7774")
324 def test_executable_without_cwd(self):
325 # For a normal installation, it should work without 'cwd'
326 # argument. For test runs in the build directory, see #7774.
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700327 self._assert_cwd('', "somethingyoudonthave", executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000328
329 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000330 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000331 p = subprocess.Popen([sys.executable, "-c",
332 'import sys; sys.exit(sys.stdin.read() == "pear")'],
333 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000334 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000335 p.stdin.close()
336 p.wait()
337 self.assertEqual(p.returncode, 1)
338
339 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000340 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000341 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000342 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000343 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000344 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000345 os.lseek(d, 0, 0)
346 p = subprocess.Popen([sys.executable, "-c",
347 'import sys; sys.exit(sys.stdin.read() == "pear")'],
348 stdin=d)
349 p.wait()
350 self.assertEqual(p.returncode, 1)
351
352 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000353 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000354 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000355 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000356 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000357 tf.seek(0)
358 p = subprocess.Popen([sys.executable, "-c",
359 'import sys; sys.exit(sys.stdin.read() == "pear")'],
360 stdin=tf)
361 p.wait()
362 self.assertEqual(p.returncode, 1)
363
364 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000365 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000366 p = subprocess.Popen([sys.executable, "-c",
367 'import sys; sys.stdout.write("orange")'],
368 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000369 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000370 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000371
372 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000373 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000374 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000375 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000376 d = tf.fileno()
377 p = subprocess.Popen([sys.executable, "-c",
378 'import sys; sys.stdout.write("orange")'],
379 stdout=d)
380 p.wait()
381 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000382 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000383
384 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000385 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000386 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000387 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000388 p = subprocess.Popen([sys.executable, "-c",
389 'import sys; sys.stdout.write("orange")'],
390 stdout=tf)
391 p.wait()
392 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000393 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000394
395 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000396 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000397 p = subprocess.Popen([sys.executable, "-c",
398 'import sys; sys.stderr.write("strawberry")'],
399 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000400 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000401 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000402
403 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000404 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000405 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000406 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000407 d = tf.fileno()
408 p = subprocess.Popen([sys.executable, "-c",
409 'import sys; sys.stderr.write("strawberry")'],
410 stderr=d)
411 p.wait()
412 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000413 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000414
415 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000416 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000417 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000418 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000419 p = subprocess.Popen([sys.executable, "-c",
420 'import sys; sys.stderr.write("strawberry")'],
421 stderr=tf)
422 p.wait()
423 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000424 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000425
426 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000427 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000428 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000429 'import sys;'
430 'sys.stdout.write("apple");'
431 'sys.stdout.flush();'
432 'sys.stderr.write("orange")'],
433 stdout=subprocess.PIPE,
434 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000435 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000436 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000437
438 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000439 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000440 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000441 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000442 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000443 'import sys;'
444 'sys.stdout.write("apple");'
445 'sys.stdout.flush();'
446 'sys.stderr.write("orange")'],
447 stdout=tf,
448 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000449 p.wait()
450 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000451 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000452
Thomas Wouters89f507f2006-12-13 04:49:30 +0000453 def test_stdout_filedes_of_stdout(self):
454 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000455 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000456 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000457 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000458
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200459 def test_stdout_devnull(self):
460 p = subprocess.Popen([sys.executable, "-c",
461 'for i in range(10240):'
462 'print("x" * 1024)'],
463 stdout=subprocess.DEVNULL)
464 p.wait()
465 self.assertEqual(p.stdout, None)
466
467 def test_stderr_devnull(self):
468 p = subprocess.Popen([sys.executable, "-c",
469 'import sys\n'
470 'for i in range(10240):'
471 'sys.stderr.write("x" * 1024)'],
472 stderr=subprocess.DEVNULL)
473 p.wait()
474 self.assertEqual(p.stderr, None)
475
476 def test_stdin_devnull(self):
477 p = subprocess.Popen([sys.executable, "-c",
478 'import sys;'
479 'sys.stdin.read(1)'],
480 stdin=subprocess.DEVNULL)
481 p.wait()
482 self.assertEqual(p.stdin, None)
483
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000484 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000485 newenv = os.environ.copy()
486 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200487 with subprocess.Popen([sys.executable, "-c",
488 'import sys,os;'
489 'sys.stdout.write(os.getenv("FRUIT"))'],
490 stdout=subprocess.PIPE,
491 env=newenv) as p:
492 stdout, stderr = p.communicate()
493 self.assertEqual(stdout, b"orange")
494
Victor Stinner62d51182011-06-23 01:02:25 +0200495 # Windows requires at least the SYSTEMROOT environment variable to start
496 # Python
497 @unittest.skipIf(sys.platform == 'win32',
498 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200499 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200500 'the python library cannot be loaded '
501 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200502 def test_empty_env(self):
503 with subprocess.Popen([sys.executable, "-c",
504 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200505 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200506 stdout=subprocess.PIPE,
507 env={}) as p:
508 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200509 self.assertIn(stdout.strip(),
510 (b"[]",
511 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
512 # environment
513 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000514
Peter Astrandcbac93c2005-03-03 20:24:28 +0000515 def test_communicate_stdin(self):
516 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000517 'import sys;'
518 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000519 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000520 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000521 self.assertEqual(p.returncode, 1)
522
523 def test_communicate_stdout(self):
524 p = subprocess.Popen([sys.executable, "-c",
525 'import sys; sys.stdout.write("pineapple")'],
526 stdout=subprocess.PIPE)
527 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000528 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000529 self.assertEqual(stderr, None)
530
531 def test_communicate_stderr(self):
532 p = subprocess.Popen([sys.executable, "-c",
533 'import sys; sys.stderr.write("pineapple")'],
534 stderr=subprocess.PIPE)
535 (stdout, stderr) = p.communicate()
536 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000537 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000538
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000539 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000540 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000541 'import sys,os;'
542 'sys.stderr.write("pineapple");'
543 'sys.stdout.write(sys.stdin.read())'],
544 stdin=subprocess.PIPE,
545 stdout=subprocess.PIPE,
546 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000547 self.addCleanup(p.stdout.close)
548 self.addCleanup(p.stderr.close)
549 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000550 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000551 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000552 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000553
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400554 def test_communicate_timeout(self):
555 p = subprocess.Popen([sys.executable, "-c",
556 'import sys,os,time;'
557 'sys.stderr.write("pineapple\\n");'
558 'time.sleep(1);'
559 'sys.stderr.write("pear\\n");'
560 'sys.stdout.write(sys.stdin.read())'],
561 universal_newlines=True,
562 stdin=subprocess.PIPE,
563 stdout=subprocess.PIPE,
564 stderr=subprocess.PIPE)
565 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
566 timeout=0.3)
567 # Make sure we can keep waiting for it, and that we get the whole output
568 # after it completes.
569 (stdout, stderr) = p.communicate()
570 self.assertEqual(stdout, "banana")
571 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
572
573 def test_communicate_timeout_large_ouput(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200574 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400575 p = subprocess.Popen([sys.executable, "-c",
576 'import sys,os,time;'
577 'sys.stdout.write("a" * (64 * 1024));'
578 'time.sleep(0.2);'
579 'sys.stdout.write("a" * (64 * 1024));'
580 'time.sleep(0.2);'
581 'sys.stdout.write("a" * (64 * 1024));'
582 'time.sleep(0.2);'
583 'sys.stdout.write("a" * (64 * 1024));'],
584 stdout=subprocess.PIPE)
585 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
586 (stdout, _) = p.communicate()
587 self.assertEqual(len(stdout), 4 * 64 * 1024)
588
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000589 # Test for the fd leak reported in http://bugs.python.org/issue2791.
590 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000591 for stdin_pipe in (False, True):
592 for stdout_pipe in (False, True):
593 for stderr_pipe in (False, True):
594 options = {}
595 if stdin_pipe:
596 options['stdin'] = subprocess.PIPE
597 if stdout_pipe:
598 options['stdout'] = subprocess.PIPE
599 if stderr_pipe:
600 options['stderr'] = subprocess.PIPE
601 if not options:
602 continue
603 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
604 p.communicate()
605 if p.stdin is not None:
606 self.assertTrue(p.stdin.closed)
607 if p.stdout is not None:
608 self.assertTrue(p.stdout.closed)
609 if p.stderr is not None:
610 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000611
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000612 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000613 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000614 p = subprocess.Popen([sys.executable, "-c",
615 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000616 (stdout, stderr) = p.communicate()
617 self.assertEqual(stdout, None)
618 self.assertEqual(stderr, None)
619
620 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000621 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000622 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000623 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000624 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000625 os.close(x)
626 os.close(y)
627 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000628 'import sys,os;'
629 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200630 'sys.stderr.write("x" * %d);'
631 'sys.stdout.write(sys.stdin.read())' %
632 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000633 stdin=subprocess.PIPE,
634 stdout=subprocess.PIPE,
635 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000636 self.addCleanup(p.stdout.close)
637 self.addCleanup(p.stderr.close)
638 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200639 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000640 (stdout, stderr) = p.communicate(string_to_write)
641 self.assertEqual(stdout, string_to_write)
642
643 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000644 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000645 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000646 'import sys,os;'
647 'sys.stdout.write(sys.stdin.read())'],
648 stdin=subprocess.PIPE,
649 stdout=subprocess.PIPE,
650 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000651 self.addCleanup(p.stdout.close)
652 self.addCleanup(p.stderr.close)
653 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000654 p.stdin.write(b"banana")
655 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000656 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000657 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000658
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000659 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000660 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000661 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200662 'buf = sys.stdout.buffer;'
663 'buf.write(sys.stdin.readline().encode());'
664 'buf.flush();'
665 'buf.write(b"line2\\n");'
666 'buf.flush();'
667 'buf.write(sys.stdin.read().encode());'
668 'buf.flush();'
669 'buf.write(b"line4\\n");'
670 'buf.flush();'
671 'buf.write(b"line5\\r\\n");'
672 'buf.flush();'
673 'buf.write(b"line6\\r");'
674 'buf.flush();'
675 'buf.write(b"\\nline7");'
676 'buf.flush();'
677 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200678 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000679 stdout=subprocess.PIPE,
680 universal_newlines=1)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200681 p.stdin.write("line1\n")
682 self.assertEqual(p.stdout.readline(), "line1\n")
683 p.stdin.write("line3\n")
684 p.stdin.close()
Brian Curtin3c6a9512010-11-05 03:58:52 +0000685 self.addCleanup(p.stdout.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200686 self.assertEqual(p.stdout.readline(),
687 "line2\n")
688 self.assertEqual(p.stdout.read(6),
689 "line3\n")
690 self.assertEqual(p.stdout.read(),
691 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000692
693 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000694 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000695 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000696 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200697 'buf = sys.stdout.buffer;'
698 'buf.write(b"line2\\n");'
699 'buf.flush();'
700 'buf.write(b"line4\\n");'
701 'buf.flush();'
702 'buf.write(b"line5\\r\\n");'
703 'buf.flush();'
704 'buf.write(b"line6\\r");'
705 'buf.flush();'
706 'buf.write(b"\\nline7");'
707 'buf.flush();'
708 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200709 stderr=subprocess.PIPE,
710 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000711 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000712 self.addCleanup(p.stdout.close)
713 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000714 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200715 self.assertEqual(stdout,
716 "line2\nline4\nline5\nline6\nline7\nline8")
717
718 def test_universal_newlines_communicate_stdin(self):
719 # universal newlines through communicate(), with only stdin
720 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300721 'import sys,os;' + SETBINARY + textwrap.dedent('''
722 s = sys.stdin.readline()
723 assert s == "line1\\n", repr(s)
724 s = sys.stdin.read()
725 assert s == "line3\\n", repr(s)
726 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200727 stdin=subprocess.PIPE,
728 universal_newlines=1)
729 (stdout, stderr) = p.communicate("line1\nline3\n")
730 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000731
Andrew Svetlovf3765072012-08-14 18:35:17 +0300732 def test_universal_newlines_communicate_input_none(self):
733 # Test communicate(input=None) with universal newlines.
734 #
735 # We set stdout to PIPE because, as of this writing, a different
736 # code path is tested when the number of pipes is zero or one.
737 p = subprocess.Popen([sys.executable, "-c", "pass"],
738 stdin=subprocess.PIPE,
739 stdout=subprocess.PIPE,
740 universal_newlines=True)
741 p.communicate()
742 self.assertEqual(p.returncode, 0)
743
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300744 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300745 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300746 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300747 'import sys,os;' + SETBINARY + textwrap.dedent('''
748 s = sys.stdin.buffer.readline()
749 sys.stdout.buffer.write(s)
750 sys.stdout.buffer.write(b"line2\\r")
751 sys.stderr.buffer.write(b"eline2\\n")
752 s = sys.stdin.buffer.read()
753 sys.stdout.buffer.write(s)
754 sys.stdout.buffer.write(b"line4\\n")
755 sys.stdout.buffer.write(b"line5\\r\\n")
756 sys.stderr.buffer.write(b"eline6\\r")
757 sys.stderr.buffer.write(b"eline7\\r\\nz")
758 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300759 stdin=subprocess.PIPE,
760 stderr=subprocess.PIPE,
761 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300762 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300763 self.addCleanup(p.stdout.close)
764 self.addCleanup(p.stderr.close)
765 (stdout, stderr) = p.communicate("line1\nline3\n")
766 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300767 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300768 # Python debug build push something like "[42442 refs]\n"
769 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300770 # Don't use assertStderrEqual because it strips CR and LF from output.
771 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300772
Andrew Svetlov82860712012-08-19 22:13:41 +0300773 def test_universal_newlines_communicate_encodings(self):
774 # Check that universal newlines mode works for various encodings,
775 # in particular for encodings in the UTF-16 and UTF-32 families.
776 # See issue #15595.
777 #
778 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
779 # without, and UTF-16 and UTF-32.
780 for encoding in ['utf-16', 'utf-32-be']:
781 old_getpreferredencoding = locale.getpreferredencoding
782 # Indirectly via io.TextIOWrapper, Popen() defaults to
783 # locale.getpreferredencoding(False) and earlier in Python 3.2 to
784 # locale.getpreferredencoding().
785 def getpreferredencoding(do_setlocale=True):
786 return encoding
787 code = ("import sys; "
788 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
789 encoding)
790 args = [sys.executable, '-c', code]
791 try:
792 locale.getpreferredencoding = getpreferredencoding
793 # We set stdin to be non-None because, as of this writing,
794 # a different code path is used when the number of pipes is
795 # zero or one.
796 popen = subprocess.Popen(args, universal_newlines=True,
797 stdin=subprocess.PIPE,
798 stdout=subprocess.PIPE)
799 stdout, stderr = popen.communicate(input='')
800 finally:
801 locale.getpreferredencoding = old_getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300802 self.assertEqual(stdout, '1\n2\n3\n4')
803
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000804 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000805 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000806 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000807 max_handles = 1026 # too much for most UNIX systems
808 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000809 max_handles = 2050 # too much for (at least some) Windows setups
810 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400811 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000812 try:
813 for i in range(max_handles):
814 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400815 tmpfile = os.path.join(tmpdir, support.TESTFN)
816 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000817 except OSError as e:
818 if e.errno != errno.EMFILE:
819 raise
820 break
821 else:
822 self.skipTest("failed to reach the file descriptor limit "
823 "(tried %d)" % max_handles)
824 # Close a couple of them (should be enough for a subprocess)
825 for i in range(10):
826 os.close(handles.pop())
827 # Loop creating some subprocesses. If one of them leaks some fds,
828 # the next loop iteration will fail by reaching the max fd limit.
829 for i in range(15):
830 p = subprocess.Popen([sys.executable, "-c",
831 "import sys;"
832 "sys.stdout.write(sys.stdin.read())"],
833 stdin=subprocess.PIPE,
834 stdout=subprocess.PIPE,
835 stderr=subprocess.PIPE)
836 data = p.communicate(b"lime")[0]
837 self.assertEqual(data, b"lime")
838 finally:
839 for h in handles:
840 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400841 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000842
843 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000844 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
845 '"a b c" d e')
846 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
847 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000848 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
849 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000850 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
851 'a\\\\\\b "de fg" h')
852 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
853 'a\\\\\\"b c d')
854 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
855 '"a\\\\b c" d e')
856 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
857 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000858 self.assertEqual(subprocess.list2cmdline(['ab', '']),
859 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000860
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000861 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200862 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +0200863 "import os; os.read(0, 1)"],
864 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200865 self.addCleanup(p.stdin.close)
866 self.assertIsNone(p.poll())
867 os.write(p.stdin.fileno(), b'A')
868 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000869 # Subsequent invocations should just return the returncode
870 self.assertEqual(p.poll(), 0)
871
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000872 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200873 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000874 self.assertEqual(p.wait(), 0)
875 # Subsequent invocations should just return the returncode
876 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000877
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400878 def test_wait_timeout(self):
879 p = subprocess.Popen([sys.executable,
Reid Kleckner93479cc2011-03-14 19:32:41 -0400880 "-c", "import time; time.sleep(0.1)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -0400881 with self.assertRaises(subprocess.TimeoutExpired) as c:
882 p.wait(timeout=0.01)
883 self.assertIn("0.01", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -0400884 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
885 # time to start.
886 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400887
Peter Astrand738131d2004-11-30 21:04:45 +0000888 def test_invalid_bufsize(self):
889 # an invalid type of the bufsize argument should raise
890 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000891 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000892 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000893
Guido van Rossum46a05a72007-06-07 21:56:45 +0000894 def test_bufsize_is_none(self):
895 # bufsize=None should be the same as bufsize=0.
896 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
897 self.assertEqual(p.wait(), 0)
898 # Again with keyword arg
899 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
900 self.assertEqual(p.wait(), 0)
901
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000902 def test_leaking_fds_on_error(self):
903 # see bug #5179: Popen leaks file descriptors to PIPEs if
904 # the child fails to execute; this will eventually exhaust
905 # the maximum number of open fds. 1024 seems a very common
906 # value for that limit, but Windows has 2048, so we loop
907 # 1024 times (each call leaked two fds).
908 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000909 # Windows raises IOError. Others raise OSError.
910 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000911 subprocess.Popen(['nonexisting_i_hope'],
912 stdout=subprocess.PIPE,
913 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400914 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400915 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000916 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000917
Victor Stinnerb3693582010-05-21 20:13:12 +0000918 def test_issue8780(self):
919 # Ensure that stdout is inherited from the parent
920 # if stdout=PIPE is not used
921 code = ';'.join((
922 'import subprocess, sys',
923 'retcode = subprocess.call('
924 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
925 'assert retcode == 0'))
926 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000927 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000928
Tim Goldenaf5ac392010-08-06 13:03:56 +0000929 def test_handles_closed_on_exception(self):
930 # If CreateProcess exits with an error, ensure the
931 # duplicate output handles are released
932 ifhandle, ifname = mkstemp()
933 ofhandle, ofname = mkstemp()
934 efhandle, efname = mkstemp()
935 try:
936 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
937 stderr=efhandle)
938 except OSError:
939 os.close(ifhandle)
940 os.remove(ifname)
941 os.close(ofhandle)
942 os.remove(ofname)
943 os.close(efhandle)
944 os.remove(efname)
945 self.assertFalse(os.path.exists(ifname))
946 self.assertFalse(os.path.exists(ofname))
947 self.assertFalse(os.path.exists(efname))
948
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200949 def test_communicate_epipe(self):
950 # Issue 10963: communicate() should hide EPIPE
951 p = subprocess.Popen([sys.executable, "-c", 'pass'],
952 stdin=subprocess.PIPE,
953 stdout=subprocess.PIPE,
954 stderr=subprocess.PIPE)
955 self.addCleanup(p.stdout.close)
956 self.addCleanup(p.stderr.close)
957 self.addCleanup(p.stdin.close)
958 p.communicate(b"x" * 2**20)
959
960 def test_communicate_epipe_only_stdin(self):
961 # Issue 10963: communicate() should hide EPIPE
962 p = subprocess.Popen([sys.executable, "-c", 'pass'],
963 stdin=subprocess.PIPE)
964 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200965 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200966 p.communicate(b"x" * 2**20)
967
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200968 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
969 "Requires signal.SIGUSR1")
970 @unittest.skipUnless(hasattr(os, 'kill'),
971 "Requires os.kill")
972 @unittest.skipUnless(hasattr(os, 'getppid'),
973 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200974 def test_communicate_eintr(self):
975 # Issue #12493: communicate() should handle EINTR
976 def handler(signum, frame):
977 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200978 old_handler = signal.signal(signal.SIGUSR1, handler)
979 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200980
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200981 args = [sys.executable, "-c",
982 'import os, signal;'
983 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200984 for stream in ('stdout', 'stderr'):
985 kw = {stream: subprocess.PIPE}
986 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200987 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200988 process.communicate()
989
Tim Peterse718f612004-10-12 21:51:32 +0000990
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000991# context manager
992class _SuppressCoreFiles(object):
993 """Try to prevent core files from being created."""
994 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000995
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000996 def __enter__(self):
997 """Try to save previous ulimit, then set it to (0, 0)."""
Benjamin Peterson964561b2011-12-10 12:31:42 -0500998 if resource is not None:
999 try:
1000 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
1001 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
1002 except (ValueError, resource.error):
1003 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001004
Ronald Oussoren102d11a2010-07-23 09:50:05 +00001005 if sys.platform == 'darwin':
1006 # Check if the 'Crash Reporter' on OSX was configured
1007 # in 'Developer' mode and warn that it will get triggered
1008 # when it is.
1009 #
1010 # This assumes that this context manager is used in tests
1011 # that might trigger the next manager.
1012 value = subprocess.Popen(['/usr/bin/defaults', 'read',
1013 'com.apple.CrashReporter', 'DialogType'],
1014 stdout=subprocess.PIPE).communicate()[0]
1015 if value.strip() == b'developer':
1016 print("this tests triggers the Crash Reporter, "
1017 "that is intentional", end='')
1018 sys.stdout.flush()
1019
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001020 def __exit__(self, *args):
1021 """Return core file behavior to default."""
1022 if self.old_limit is None:
1023 return
Benjamin Peterson964561b2011-12-10 12:31:42 -05001024 if resource is not None:
1025 try:
1026 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
1027 except (ValueError, resource.error):
1028 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001029
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001030
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001031@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001032class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001033
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001034 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001035 nonexistent_dir = "/_this/pa.th/does/not/exist"
1036 try:
1037 os.chdir(nonexistent_dir)
1038 except OSError as e:
1039 # This avoids hard coding the errno value or the OS perror()
1040 # string and instead capture the exception that we want to see
1041 # below for comparison.
1042 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +00001043 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001044 else:
1045 self.fail("chdir to nonexistant directory %s succeeded." %
1046 nonexistent_dir)
1047
1048 # Error in the child re-raised in the parent.
1049 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001050 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001051 cwd=nonexistent_dir)
1052 except OSError as e:
1053 # Test that the child process chdir failure actually makes
1054 # it up to the parent process as the correct exception.
1055 self.assertEqual(desired_exception.errno, e.errno)
1056 self.assertEqual(desired_exception.strerror, e.strerror)
1057 else:
1058 self.fail("Expected OSError: %s" % desired_exception)
1059
1060 def test_restore_signals(self):
1061 # Code coverage for both values of restore_signals to make sure it
1062 # at least does not blow up.
1063 # A test for behavior would be complex. Contributions welcome.
1064 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1065 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1066
1067 def test_start_new_session(self):
1068 # For code coverage of calling setsid(). We don't care if we get an
1069 # EPERM error from it depending on the test execution environment, that
1070 # still indicates that it was called.
1071 try:
1072 output = subprocess.check_output(
1073 [sys.executable, "-c",
1074 "import os; print(os.getpgid(os.getpid()))"],
1075 start_new_session=True)
1076 except OSError as e:
1077 if e.errno != errno.EPERM:
1078 raise
1079 else:
1080 parent_pgid = os.getpgid(os.getpid())
1081 child_pgid = int(output)
1082 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001083
1084 def test_run_abort(self):
1085 # returncode handles signal termination
1086 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001087 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001088 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001089 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001090 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001091
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001092 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001093 # DISCLAIMER: Setting environment variables is *not* a good use
1094 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001095 p = subprocess.Popen([sys.executable, "-c",
1096 'import sys,os;'
1097 'sys.stdout.write(os.getenv("FRUIT"))'],
1098 stdout=subprocess.PIPE,
1099 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +00001100 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001101 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001102
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001103 def test_preexec_exception(self):
1104 def raise_it():
1105 raise ValueError("What if two swallows carried a coconut?")
1106 try:
1107 p = subprocess.Popen([sys.executable, "-c", ""],
1108 preexec_fn=raise_it)
1109 except RuntimeError as e:
1110 self.assertTrue(
1111 subprocess._posixsubprocess,
1112 "Expected a ValueError from the preexec_fn")
1113 except ValueError as e:
1114 self.assertIn("coconut", e.args[0])
1115 else:
1116 self.fail("Exception raised by preexec_fn did not make it "
1117 "to the parent process.")
1118
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001119 def test_preexec_gc_module_failure(self):
1120 # This tests the code that disables garbage collection if the child
1121 # process will execute any Python.
1122 def raise_runtime_error():
1123 raise RuntimeError("this shouldn't escape")
1124 enabled = gc.isenabled()
1125 orig_gc_disable = gc.disable
1126 orig_gc_isenabled = gc.isenabled
1127 try:
1128 gc.disable()
1129 self.assertFalse(gc.isenabled())
1130 subprocess.call([sys.executable, '-c', ''],
1131 preexec_fn=lambda: None)
1132 self.assertFalse(gc.isenabled(),
1133 "Popen enabled gc when it shouldn't.")
1134
1135 gc.enable()
1136 self.assertTrue(gc.isenabled())
1137 subprocess.call([sys.executable, '-c', ''],
1138 preexec_fn=lambda: None)
1139 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1140
1141 gc.disable = raise_runtime_error
1142 self.assertRaises(RuntimeError, subprocess.Popen,
1143 [sys.executable, '-c', ''],
1144 preexec_fn=lambda: None)
1145
1146 del gc.isenabled # force an AttributeError
1147 self.assertRaises(AttributeError, subprocess.Popen,
1148 [sys.executable, '-c', ''],
1149 preexec_fn=lambda: None)
1150 finally:
1151 gc.disable = orig_gc_disable
1152 gc.isenabled = orig_gc_isenabled
1153 if not enabled:
1154 gc.disable()
1155
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001156 def test_args_string(self):
1157 # args is a string
1158 fd, fname = mkstemp()
1159 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001160 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001161 fobj.write("#!/bin/sh\n")
1162 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1163 sys.executable)
1164 os.chmod(fname, 0o700)
1165 p = subprocess.Popen(fname)
1166 p.wait()
1167 os.remove(fname)
1168 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001169
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001170 def test_invalid_args(self):
1171 # invalid arguments should raise ValueError
1172 self.assertRaises(ValueError, subprocess.call,
1173 [sys.executable, "-c",
1174 "import sys; sys.exit(47)"],
1175 startupinfo=47)
1176 self.assertRaises(ValueError, subprocess.call,
1177 [sys.executable, "-c",
1178 "import sys; sys.exit(47)"],
1179 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001180
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001181 def test_shell_sequence(self):
1182 # Run command through the shell (sequence)
1183 newenv = os.environ.copy()
1184 newenv["FRUIT"] = "apple"
1185 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1186 stdout=subprocess.PIPE,
1187 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001188 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001189 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001190
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001191 def test_shell_string(self):
1192 # Run command through the shell (string)
1193 newenv = os.environ.copy()
1194 newenv["FRUIT"] = "apple"
1195 p = subprocess.Popen("echo $FRUIT", shell=1,
1196 stdout=subprocess.PIPE,
1197 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001198 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001199 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001200
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001201 def test_call_string(self):
1202 # call() function with string argument on UNIX
1203 fd, fname = mkstemp()
1204 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001205 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001206 fobj.write("#!/bin/sh\n")
1207 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1208 sys.executable)
1209 os.chmod(fname, 0o700)
1210 rc = subprocess.call(fname)
1211 os.remove(fname)
1212 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001213
Stefan Krah9542cc62010-07-19 14:20:53 +00001214 def test_specific_shell(self):
1215 # Issue #9265: Incorrect name passed as arg[0].
1216 shells = []
1217 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1218 for name in ['bash', 'ksh']:
1219 sh = os.path.join(prefix, name)
1220 if os.path.isfile(sh):
1221 shells.append(sh)
1222 if not shells: # Will probably work for any shell but csh.
1223 self.skipTest("bash or ksh required for this test")
1224 sh = '/bin/sh'
1225 if os.path.isfile(sh) and not os.path.islink(sh):
1226 # Test will fail if /bin/sh is a symlink to csh.
1227 shells.append(sh)
1228 for sh in shells:
1229 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1230 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001231 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001232 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1233
Florent Xicluna4886d242010-03-08 13:27:26 +00001234 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001235 # Do not inherit file handles from the parent.
1236 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001237 p = subprocess.Popen([sys.executable, "-c", """if 1:
1238 import sys, time
1239 sys.stdout.write('x\\n')
1240 sys.stdout.flush()
1241 time.sleep(30)
1242 """],
1243 close_fds=True,
1244 stdin=subprocess.PIPE,
1245 stdout=subprocess.PIPE,
1246 stderr=subprocess.PIPE)
1247 # Wait for the interpreter to be completely initialized before
1248 # sending any signal.
1249 p.stdout.read(1)
1250 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001251 return p
1252
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001253 def _kill_dead_process(self, method, *args):
1254 # Do not inherit file handles from the parent.
1255 # It should fix failures on some platforms.
1256 p = subprocess.Popen([sys.executable, "-c", """if 1:
1257 import sys, time
1258 sys.stdout.write('x\\n')
1259 sys.stdout.flush()
1260 """],
1261 close_fds=True,
1262 stdin=subprocess.PIPE,
1263 stdout=subprocess.PIPE,
1264 stderr=subprocess.PIPE)
1265 # Wait for the interpreter to be completely initialized before
1266 # sending any signal.
1267 p.stdout.read(1)
1268 # The process should end after this
1269 time.sleep(1)
1270 # This shouldn't raise even though the child is now dead
1271 getattr(p, method)(*args)
1272 p.communicate()
1273
Florent Xicluna4886d242010-03-08 13:27:26 +00001274 def test_send_signal(self):
1275 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001276 _, stderr = p.communicate()
1277 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001278 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001279
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001280 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001281 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001282 _, stderr = p.communicate()
1283 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001284 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001285
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001286 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001287 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001288 _, stderr = p.communicate()
1289 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001290 self.assertEqual(p.wait(), -signal.SIGTERM)
1291
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001292 def test_send_signal_dead(self):
1293 # Sending a signal to a dead process
1294 self._kill_dead_process('send_signal', signal.SIGINT)
1295
1296 def test_kill_dead(self):
1297 # Killing a dead process
1298 self._kill_dead_process('kill')
1299
1300 def test_terminate_dead(self):
1301 # Terminating a dead process
1302 self._kill_dead_process('terminate')
1303
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001304 def check_close_std_fds(self, fds):
1305 # Issue #9905: test that subprocess pipes still work properly with
1306 # some standard fds closed
1307 stdin = 0
1308 newfds = []
1309 for a in fds:
1310 b = os.dup(a)
1311 newfds.append(b)
1312 if a == 0:
1313 stdin = b
1314 try:
1315 for fd in fds:
1316 os.close(fd)
1317 out, err = subprocess.Popen([sys.executable, "-c",
1318 'import sys;'
1319 'sys.stdout.write("apple");'
1320 'sys.stdout.flush();'
1321 'sys.stderr.write("orange")'],
1322 stdin=stdin,
1323 stdout=subprocess.PIPE,
1324 stderr=subprocess.PIPE).communicate()
1325 err = support.strip_python_stderr(err)
1326 self.assertEqual((out, err), (b'apple', b'orange'))
1327 finally:
1328 for b, a in zip(newfds, fds):
1329 os.dup2(b, a)
1330 for b in newfds:
1331 os.close(b)
1332
1333 def test_close_fd_0(self):
1334 self.check_close_std_fds([0])
1335
1336 def test_close_fd_1(self):
1337 self.check_close_std_fds([1])
1338
1339 def test_close_fd_2(self):
1340 self.check_close_std_fds([2])
1341
1342 def test_close_fds_0_1(self):
1343 self.check_close_std_fds([0, 1])
1344
1345 def test_close_fds_0_2(self):
1346 self.check_close_std_fds([0, 2])
1347
1348 def test_close_fds_1_2(self):
1349 self.check_close_std_fds([1, 2])
1350
1351 def test_close_fds_0_1_2(self):
1352 # Issue #10806: test that subprocess pipes still work properly with
1353 # all standard fds closed.
1354 self.check_close_std_fds([0, 1, 2])
1355
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001356 def test_remapping_std_fds(self):
1357 # open up some temporary files
1358 temps = [mkstemp() for i in range(3)]
1359 try:
1360 temp_fds = [fd for fd, fname in temps]
1361
1362 # unlink the files -- we won't need to reopen them
1363 for fd, fname in temps:
1364 os.unlink(fname)
1365
1366 # write some data to what will become stdin, and rewind
1367 os.write(temp_fds[1], b"STDIN")
1368 os.lseek(temp_fds[1], 0, 0)
1369
1370 # move the standard file descriptors out of the way
1371 saved_fds = [os.dup(fd) for fd in range(3)]
1372 try:
1373 # duplicate the file objects over the standard fd's
1374 for fd, temp_fd in enumerate(temp_fds):
1375 os.dup2(temp_fd, fd)
1376
1377 # now use those files in the "wrong" order, so that subprocess
1378 # has to rearrange them in the child
1379 p = subprocess.Popen([sys.executable, "-c",
1380 'import sys; got = sys.stdin.read();'
1381 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1382 stdin=temp_fds[1],
1383 stdout=temp_fds[2],
1384 stderr=temp_fds[0])
1385 p.wait()
1386 finally:
1387 # restore the original fd's underneath sys.stdin, etc.
1388 for std, saved in enumerate(saved_fds):
1389 os.dup2(saved, std)
1390 os.close(saved)
1391
1392 for fd in temp_fds:
1393 os.lseek(fd, 0, 0)
1394
1395 out = os.read(temp_fds[2], 1024)
1396 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1397 self.assertEqual(out, b"got STDIN")
1398 self.assertEqual(err, b"err")
1399
1400 finally:
1401 for fd in temp_fds:
1402 os.close(fd)
1403
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001404 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1405 # open up some temporary files
1406 temps = [mkstemp() for i in range(3)]
1407 temp_fds = [fd for fd, fname in temps]
1408 try:
1409 # unlink the files -- we won't need to reopen them
1410 for fd, fname in temps:
1411 os.unlink(fname)
1412
1413 # save a copy of the standard file descriptors
1414 saved_fds = [os.dup(fd) for fd in range(3)]
1415 try:
1416 # duplicate the temp files over the standard fd's 0, 1, 2
1417 for fd, temp_fd in enumerate(temp_fds):
1418 os.dup2(temp_fd, fd)
1419
1420 # write some data to what will become stdin, and rewind
1421 os.write(stdin_no, b"STDIN")
1422 os.lseek(stdin_no, 0, 0)
1423
1424 # now use those files in the given order, so that subprocess
1425 # has to rearrange them in the child
1426 p = subprocess.Popen([sys.executable, "-c",
1427 'import sys; got = sys.stdin.read();'
1428 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1429 stdin=stdin_no,
1430 stdout=stdout_no,
1431 stderr=stderr_no)
1432 p.wait()
1433
1434 for fd in temp_fds:
1435 os.lseek(fd, 0, 0)
1436
1437 out = os.read(stdout_no, 1024)
1438 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1439 finally:
1440 for std, saved in enumerate(saved_fds):
1441 os.dup2(saved, std)
1442 os.close(saved)
1443
1444 self.assertEqual(out, b"got STDIN")
1445 self.assertEqual(err, b"err")
1446
1447 finally:
1448 for fd in temp_fds:
1449 os.close(fd)
1450
1451 # When duping fds, if there arises a situation where one of the fds is
1452 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1453 # This tests all combinations of this.
1454 def test_swap_fds(self):
1455 self.check_swap_fds(0, 1, 2)
1456 self.check_swap_fds(0, 2, 1)
1457 self.check_swap_fds(1, 0, 2)
1458 self.check_swap_fds(1, 2, 0)
1459 self.check_swap_fds(2, 0, 1)
1460 self.check_swap_fds(2, 1, 0)
1461
Victor Stinner13bb71c2010-04-23 21:41:56 +00001462 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001463 def prepare():
1464 raise ValueError("surrogate:\uDCff")
1465
1466 try:
1467 subprocess.call(
1468 [sys.executable, "-c", "pass"],
1469 preexec_fn=prepare)
1470 except ValueError as err:
1471 # Pure Python implementations keeps the message
1472 self.assertIsNone(subprocess._posixsubprocess)
1473 self.assertEqual(str(err), "surrogate:\uDCff")
1474 except RuntimeError as err:
1475 # _posixsubprocess uses a default message
1476 self.assertIsNotNone(subprocess._posixsubprocess)
1477 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1478 else:
1479 self.fail("Expected ValueError or RuntimeError")
1480
Victor Stinner13bb71c2010-04-23 21:41:56 +00001481 def test_undecodable_env(self):
1482 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001483 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001484 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001485 env = os.environ.copy()
1486 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001487 # Use C locale to get ascii for the locale encoding to force
1488 # surrogate-escaping of \xFF in the child process; otherwise it can
1489 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001490 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001491 stdout = subprocess.check_output(
1492 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001493 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001494 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001495 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001496
1497 # test bytes
1498 key = key.encode("ascii", "surrogateescape")
1499 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001500 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001501 env = os.environ.copy()
1502 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001503 stdout = subprocess.check_output(
1504 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001505 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001506 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001507 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001508
Victor Stinnerb745a742010-05-18 17:17:23 +00001509 def test_bytes_program(self):
1510 abs_program = os.fsencode(sys.executable)
1511 path, program = os.path.split(sys.executable)
1512 program = os.fsencode(program)
1513
1514 # absolute bytes path
1515 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001516 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001517
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001518 # absolute bytes path as a string
1519 cmd = b"'" + abs_program + b"' -c pass"
1520 exitcode = subprocess.call(cmd, shell=True)
1521 self.assertEqual(exitcode, 0)
1522
Victor Stinnerb745a742010-05-18 17:17:23 +00001523 # bytes program, unicode PATH
1524 env = os.environ.copy()
1525 env["PATH"] = path
1526 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001527 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001528
1529 # bytes program, bytes PATH
1530 envb = os.environb.copy()
1531 envb[b"PATH"] = os.fsencode(path)
1532 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001533 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001534
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001535 def test_pipe_cloexec(self):
1536 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1537 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1538
1539 p1 = subprocess.Popen([sys.executable, sleeper],
1540 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1541 stderr=subprocess.PIPE, close_fds=False)
1542
1543 self.addCleanup(p1.communicate, b'')
1544
1545 p2 = subprocess.Popen([sys.executable, fd_status],
1546 stdout=subprocess.PIPE, close_fds=False)
1547
1548 output, error = p2.communicate()
1549 result_fds = set(map(int, output.split(b',')))
1550 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1551 p1.stderr.fileno()])
1552
1553 self.assertFalse(result_fds & unwanted_fds,
1554 "Expected no fds from %r to be open in child, "
1555 "found %r" %
1556 (unwanted_fds, result_fds & unwanted_fds))
1557
1558 def test_pipe_cloexec_real_tools(self):
1559 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1560 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1561
1562 subdata = b'zxcvbn'
1563 data = subdata * 4 + b'\n'
1564
1565 p1 = subprocess.Popen([sys.executable, qcat],
1566 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1567 close_fds=False)
1568
1569 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1570 stdin=p1.stdout, stdout=subprocess.PIPE,
1571 close_fds=False)
1572
1573 self.addCleanup(p1.wait)
1574 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001575 def kill_p1():
1576 try:
1577 p1.terminate()
1578 except ProcessLookupError:
1579 pass
1580 def kill_p2():
1581 try:
1582 p2.terminate()
1583 except ProcessLookupError:
1584 pass
1585 self.addCleanup(kill_p1)
1586 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001587
1588 p1.stdin.write(data)
1589 p1.stdin.close()
1590
1591 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1592
1593 self.assertTrue(readfiles, "The child hung")
1594 self.assertEqual(p2.stdout.read(), data)
1595
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001596 p1.stdout.close()
1597 p2.stdout.close()
1598
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001599 def test_close_fds(self):
1600 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1601
1602 fds = os.pipe()
1603 self.addCleanup(os.close, fds[0])
1604 self.addCleanup(os.close, fds[1])
1605
1606 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001607 # add a bunch more fds
1608 for _ in range(9):
1609 fd = os.open("/dev/null", os.O_RDONLY)
1610 self.addCleanup(os.close, fd)
1611 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001612
1613 p = subprocess.Popen([sys.executable, fd_status],
1614 stdout=subprocess.PIPE, close_fds=False)
1615 output, ignored = p.communicate()
1616 remaining_fds = set(map(int, output.split(b',')))
1617
1618 self.assertEqual(remaining_fds & open_fds, open_fds,
1619 "Some fds were closed")
1620
1621 p = subprocess.Popen([sys.executable, fd_status],
1622 stdout=subprocess.PIPE, close_fds=True)
1623 output, ignored = p.communicate()
1624 remaining_fds = set(map(int, output.split(b',')))
1625
1626 self.assertFalse(remaining_fds & open_fds,
1627 "Some fds were left open")
1628 self.assertIn(1, remaining_fds, "Subprocess failed")
1629
Gregory P. Smith8facece2012-01-21 14:01:08 -08001630 # Keep some of the fd's we opened open in the subprocess.
1631 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1632 fds_to_keep = set(open_fds.pop() for _ in range(8))
1633 p = subprocess.Popen([sys.executable, fd_status],
1634 stdout=subprocess.PIPE, close_fds=True,
1635 pass_fds=())
1636 output, ignored = p.communicate()
1637 remaining_fds = set(map(int, output.split(b',')))
1638
1639 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1640 "Some fds not in pass_fds were left open")
1641 self.assertIn(1, remaining_fds, "Subprocess failed")
1642
Victor Stinner88701e22011-06-01 13:13:04 +02001643 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1644 # descriptor of a pipe closed in the parent process is valid in the
1645 # child process according to fstat(), but the mode of the file
1646 # descriptor is invalid, and read or write raise an error.
1647 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001648 def test_pass_fds(self):
1649 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1650
1651 open_fds = set()
1652
1653 for x in range(5):
1654 fds = os.pipe()
1655 self.addCleanup(os.close, fds[0])
1656 self.addCleanup(os.close, fds[1])
1657 open_fds.update(fds)
1658
1659 for fd in open_fds:
1660 p = subprocess.Popen([sys.executable, fd_status],
1661 stdout=subprocess.PIPE, close_fds=True,
1662 pass_fds=(fd, ))
1663 output, ignored = p.communicate()
1664
1665 remaining_fds = set(map(int, output.split(b',')))
1666 to_be_closed = open_fds - {fd}
1667
1668 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1669 self.assertFalse(remaining_fds & to_be_closed,
1670 "fd to be closed passed")
1671
1672 # pass_fds overrides close_fds with a warning.
1673 with self.assertWarns(RuntimeWarning) as context:
1674 self.assertFalse(subprocess.call(
1675 [sys.executable, "-c", "import sys; sys.exit(0)"],
1676 close_fds=False, pass_fds=(fd, )))
1677 self.assertIn('overriding close_fds', str(context.warning))
1678
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001679 def test_stdout_stdin_are_single_inout_fd(self):
1680 with io.open(os.devnull, "r+") as inout:
1681 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1682 stdout=inout, stdin=inout)
1683 p.wait()
1684
1685 def test_stdout_stderr_are_single_inout_fd(self):
1686 with io.open(os.devnull, "r+") as inout:
1687 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1688 stdout=inout, stderr=inout)
1689 p.wait()
1690
1691 def test_stderr_stdin_are_single_inout_fd(self):
1692 with io.open(os.devnull, "r+") as inout:
1693 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1694 stderr=inout, stdin=inout)
1695 p.wait()
1696
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001697 def test_wait_when_sigchild_ignored(self):
1698 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1699 sigchild_ignore = support.findfile("sigchild_ignore.py",
1700 subdir="subprocessdata")
1701 p = subprocess.Popen([sys.executable, sigchild_ignore],
1702 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1703 stdout, stderr = p.communicate()
1704 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001705 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001706 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001707
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001708 def test_select_unbuffered(self):
1709 # Issue #11459: bufsize=0 should really set the pipes as
1710 # unbuffered (and therefore let select() work properly).
1711 select = support.import_module("select")
1712 p = subprocess.Popen([sys.executable, "-c",
1713 'import sys;'
1714 'sys.stdout.write("apple")'],
1715 stdout=subprocess.PIPE,
1716 bufsize=0)
1717 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001718 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001719 try:
1720 self.assertEqual(f.read(4), b"appl")
1721 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1722 finally:
1723 p.wait()
1724
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001725 def test_zombie_fast_process_del(self):
1726 # Issue #12650: on Unix, if Popen.__del__() was called before the
1727 # process exited, it wouldn't be added to subprocess._active, and would
1728 # remain a zombie.
1729 # spawn a Popen, and delete its reference before it exits
1730 p = subprocess.Popen([sys.executable, "-c",
1731 'import sys, time;'
1732 'time.sleep(0.2)'],
1733 stdout=subprocess.PIPE,
1734 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001735 self.addCleanup(p.stdout.close)
1736 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001737 ident = id(p)
1738 pid = p.pid
1739 del p
1740 # check that p is in the active processes list
1741 self.assertIn(ident, [id(o) for o in subprocess._active])
1742
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001743 def test_leak_fast_process_del_killed(self):
1744 # Issue #12650: on Unix, if Popen.__del__() was called before the
1745 # process exited, and the process got killed by a signal, it would never
1746 # be removed from subprocess._active, which triggered a FD and memory
1747 # leak.
1748 # spawn a Popen, delete its reference and kill it
1749 p = subprocess.Popen([sys.executable, "-c",
1750 'import time;'
1751 'time.sleep(3)'],
1752 stdout=subprocess.PIPE,
1753 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001754 self.addCleanup(p.stdout.close)
1755 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001756 ident = id(p)
1757 pid = p.pid
1758 del p
1759 os.kill(pid, signal.SIGKILL)
1760 # check that p is in the active processes list
1761 self.assertIn(ident, [id(o) for o in subprocess._active])
1762
1763 # let some time for the process to exit, and create a new Popen: this
1764 # should trigger the wait() of p
1765 time.sleep(0.2)
1766 with self.assertRaises(EnvironmentError) as c:
1767 with subprocess.Popen(['nonexisting_i_hope'],
1768 stdout=subprocess.PIPE,
1769 stderr=subprocess.PIPE) as proc:
1770 pass
1771 # p should have been wait()ed on, and removed from the _active list
1772 self.assertRaises(OSError, os.waitpid, pid, 0)
1773 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1774
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001775
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001776@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001777class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001778
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001779 def test_startupinfo(self):
1780 # startupinfo argument
1781 # We uses hardcoded constants, because we do not want to
1782 # depend on win32all.
1783 STARTF_USESHOWWINDOW = 1
1784 SW_MAXIMIZE = 3
1785 startupinfo = subprocess.STARTUPINFO()
1786 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1787 startupinfo.wShowWindow = SW_MAXIMIZE
1788 # Since Python is a console process, it won't be affected
1789 # by wShowWindow, but the argument should be silently
1790 # ignored
1791 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001792 startupinfo=startupinfo)
1793
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001794 def test_creationflags(self):
1795 # creationflags argument
1796 CREATE_NEW_CONSOLE = 16
1797 sys.stderr.write(" a DOS box should flash briefly ...\n")
1798 subprocess.call(sys.executable +
1799 ' -c "import time; time.sleep(0.25)"',
1800 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001801
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001802 def test_invalid_args(self):
1803 # invalid arguments should raise ValueError
1804 self.assertRaises(ValueError, subprocess.call,
1805 [sys.executable, "-c",
1806 "import sys; sys.exit(47)"],
1807 preexec_fn=lambda: 1)
1808 self.assertRaises(ValueError, subprocess.call,
1809 [sys.executable, "-c",
1810 "import sys; sys.exit(47)"],
1811 stdout=subprocess.PIPE,
1812 close_fds=True)
1813
1814 def test_close_fds(self):
1815 # close file descriptors
1816 rc = subprocess.call([sys.executable, "-c",
1817 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001818 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001819 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001820
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001821 def test_shell_sequence(self):
1822 # Run command through the shell (sequence)
1823 newenv = os.environ.copy()
1824 newenv["FRUIT"] = "physalis"
1825 p = subprocess.Popen(["set"], shell=1,
1826 stdout=subprocess.PIPE,
1827 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001828 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001829 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001830
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001831 def test_shell_string(self):
1832 # Run command through the shell (string)
1833 newenv = os.environ.copy()
1834 newenv["FRUIT"] = "physalis"
1835 p = subprocess.Popen("set", shell=1,
1836 stdout=subprocess.PIPE,
1837 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001838 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001839 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001840
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001841 def test_call_string(self):
1842 # call() function with string argument on Windows
1843 rc = subprocess.call(sys.executable +
1844 ' -c "import sys; sys.exit(47)"')
1845 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001846
Florent Xicluna4886d242010-03-08 13:27:26 +00001847 def _kill_process(self, method, *args):
1848 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001849 p = subprocess.Popen([sys.executable, "-c", """if 1:
1850 import sys, time
1851 sys.stdout.write('x\\n')
1852 sys.stdout.flush()
1853 time.sleep(30)
1854 """],
1855 stdin=subprocess.PIPE,
1856 stdout=subprocess.PIPE,
1857 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001858 self.addCleanup(p.stdout.close)
1859 self.addCleanup(p.stderr.close)
1860 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001861 # Wait for the interpreter to be completely initialized before
1862 # sending any signal.
1863 p.stdout.read(1)
1864 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001865 _, stderr = p.communicate()
1866 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001867 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001868 self.assertNotEqual(returncode, 0)
1869
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001870 def _kill_dead_process(self, method, *args):
1871 p = subprocess.Popen([sys.executable, "-c", """if 1:
1872 import sys, time
1873 sys.stdout.write('x\\n')
1874 sys.stdout.flush()
1875 sys.exit(42)
1876 """],
1877 stdin=subprocess.PIPE,
1878 stdout=subprocess.PIPE,
1879 stderr=subprocess.PIPE)
1880 self.addCleanup(p.stdout.close)
1881 self.addCleanup(p.stderr.close)
1882 self.addCleanup(p.stdin.close)
1883 # Wait for the interpreter to be completely initialized before
1884 # sending any signal.
1885 p.stdout.read(1)
1886 # The process should end after this
1887 time.sleep(1)
1888 # This shouldn't raise even though the child is now dead
1889 getattr(p, method)(*args)
1890 _, stderr = p.communicate()
1891 self.assertStderrEqual(stderr, b'')
1892 rc = p.wait()
1893 self.assertEqual(rc, 42)
1894
Florent Xicluna4886d242010-03-08 13:27:26 +00001895 def test_send_signal(self):
1896 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001897
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001898 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001899 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001900
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001901 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001902 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001903
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001904 def test_send_signal_dead(self):
1905 self._kill_dead_process('send_signal', signal.SIGTERM)
1906
1907 def test_kill_dead(self):
1908 self._kill_dead_process('kill')
1909
1910 def test_terminate_dead(self):
1911 self._kill_dead_process('terminate')
1912
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001913
Brett Cannona23810f2008-05-26 19:04:21 +00001914# The module says:
1915# "NB This only works (and is only relevant) for UNIX."
1916#
1917# Actually, getoutput should work on any platform with an os.popen, but
1918# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001919@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001920class CommandTests(unittest.TestCase):
1921 def test_getoutput(self):
1922 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1923 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1924 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001925
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001926 # we use mkdtemp in the next line to create an empty directory
1927 # under our exclusive control; from that, we can invent a pathname
1928 # that we _know_ won't exist. This is guaranteed to fail.
1929 dir = None
1930 try:
1931 dir = tempfile.mkdtemp()
1932 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001933
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001934 status, output = subprocess.getstatusoutput('cat ' + name)
1935 self.assertNotEqual(status, 0)
1936 finally:
1937 if dir is not None:
1938 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001939
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001940
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001941@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1942 "poll system call not supported")
1943class ProcessTestCaseNoPoll(ProcessTestCase):
1944 def setUp(self):
1945 subprocess._has_poll = False
1946 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001947
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001948 def tearDown(self):
1949 subprocess._has_poll = True
1950 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001951
1952
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001953class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001954 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001955 def test_eintr_retry_call(self):
1956 record_calls = []
1957 def fake_os_func(*args):
1958 record_calls.append(args)
1959 if len(record_calls) == 2:
1960 raise OSError(errno.EINTR, "fake interrupted system call")
1961 return tuple(reversed(args))
1962
1963 self.assertEqual((999, 256),
1964 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1965 self.assertEqual([(256, 999)], record_calls)
1966 # This time there will be an EINTR so it will loop once.
1967 self.assertEqual((666,),
1968 subprocess._eintr_retry_call(fake_os_func, 666))
1969 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1970
1971
Tim Golden126c2962010-08-11 14:20:40 +00001972@unittest.skipUnless(mswindows, "Windows-specific tests")
1973class CommandsWithSpaces (BaseTestCase):
1974
1975 def setUp(self):
1976 super().setUp()
1977 f, fname = mkstemp(".py", "te st")
1978 self.fname = fname.lower ()
1979 os.write(f, b"import sys;"
1980 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1981 )
1982 os.close(f)
1983
1984 def tearDown(self):
1985 os.remove(self.fname)
1986 super().tearDown()
1987
1988 def with_spaces(self, *args, **kwargs):
1989 kwargs['stdout'] = subprocess.PIPE
1990 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001991 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001992 self.assertEqual(
1993 p.stdout.read ().decode("mbcs"),
1994 "2 [%r, 'ab cd']" % self.fname
1995 )
1996
1997 def test_shell_string_with_spaces(self):
1998 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001999 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2000 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002001
2002 def test_shell_sequence_with_spaces(self):
2003 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002004 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002005
2006 def test_noshell_string_with_spaces(self):
2007 # call() function with string argument with spaces on Windows
2008 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2009 "ab cd"))
2010
2011 def test_noshell_sequence_with_spaces(self):
2012 # call() function with sequence argument with spaces on Windows
2013 self.with_spaces([sys.executable, self.fname, "ab cd"])
2014
Brian Curtin79cdb662010-12-03 02:46:02 +00002015
Georg Brandla86b2622012-02-20 21:34:57 +01002016class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00002017
2018 def test_pipe(self):
2019 with subprocess.Popen([sys.executable, "-c",
2020 "import sys;"
2021 "sys.stdout.write('stdout');"
2022 "sys.stderr.write('stderr');"],
2023 stdout=subprocess.PIPE,
2024 stderr=subprocess.PIPE) as proc:
2025 self.assertEqual(proc.stdout.read(), b"stdout")
2026 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2027
2028 self.assertTrue(proc.stdout.closed)
2029 self.assertTrue(proc.stderr.closed)
2030
2031 def test_returncode(self):
2032 with subprocess.Popen([sys.executable, "-c",
2033 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002034 pass
2035 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002036 self.assertEqual(proc.returncode, 100)
2037
2038 def test_communicate_stdin(self):
2039 with subprocess.Popen([sys.executable, "-c",
2040 "import sys;"
2041 "sys.exit(sys.stdin.read() == 'context')"],
2042 stdin=subprocess.PIPE) as proc:
2043 proc.communicate(b"context")
2044 self.assertEqual(proc.returncode, 1)
2045
2046 def test_invalid_args(self):
2047 with self.assertRaises(EnvironmentError) as c:
2048 with subprocess.Popen(['nonexisting_i_hope'],
2049 stdout=subprocess.PIPE,
2050 stderr=subprocess.PIPE) as proc:
2051 pass
2052
2053 if c.exception.errno != errno.ENOENT: # ignore "no such file"
2054 raise c.exception
2055
2056
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002057def test_main():
2058 unit_tests = (ProcessTestCase,
2059 POSIXProcessTestCase,
2060 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002061 CommandTests,
2062 ProcessTestCaseNoPoll,
2063 HelperFunctionTests,
2064 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02002065 ContextManagerTests,
2066 )
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002067
2068 support.run_unittest(*unit_tests)
2069 support.reap_children()
2070
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002071if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002072 unittest.main()