blob: 07e2b4b688d1625f3c7b131e1cc79ff98c92ae42 [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
Chris Jerdonek2d051b82012-10-08 17:53:46 -0700203 # TODO: make this test work on Linux.
204 # This may be failing on Linux because of issue #7774.
205 @unittest.skipIf(sys.platform not in ('win32', 'darwin'),
206 "possible bug using executable argument on Linux")
Chris Jerdonek776cb192012-10-08 15:56:43 -0700207 def test_executable(self):
208 # Check that the executable argument works.
209 self._assert_python(["doesnotexist", "-c"], executable=sys.executable)
210
211 def test_executable_takes_precedence(self):
212 # Check that the executable argument takes precedence over args[0].
213 #
214 # Verify first that the call succeeds without the executable arg.
215 pre_args = [sys.executable, "-c"]
216 self._assert_python(pre_args)
217 self.assertRaises(FileNotFoundError, self._assert_python, pre_args,
218 executable="doesnotexist")
219
220 @unittest.skipIf(mswindows, "executable argument replaces shell")
221 def test_executable_replaces_shell(self):
222 # Check that the executable argument replaces the default shell
223 # when shell=True.
224 self._assert_python([], executable=sys.executable, shell=True)
225
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700226 # For use in the test_cwd* tests below.
227 def _normalize_cwd(self, cwd):
228 # Normalize an expected cwd (for Tru64 support).
229 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
230 # strings. See bug #1063571.
231 original_cwd = os.getcwd()
232 os.chdir(cwd)
233 cwd = os.getcwd()
234 os.chdir(original_cwd)
235 return cwd
236
237 # For use in the test_cwd* tests below.
238 def _split_python_path(self):
239 # Return normalized (python_dir, python_base).
240 python_path = os.path.realpath(sys.executable)
241 return os.path.split(python_path)
242
243 # For use in the test_cwd* tests below.
244 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
245 # Invoke Python via Popen, and assert that (1) the call succeeds,
246 # and that (2) the current working directory of the child process
247 # matches *expected_cwd*.
248 p = subprocess.Popen([python_arg, "-c",
249 "import os, sys; "
250 "sys.stdout.write(os.getcwd()); "
251 "sys.exit(47)"],
252 stdout=subprocess.PIPE,
253 **kwargs)
254 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000255 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700256 self.assertEqual(47, p.returncode)
257 normcase = os.path.normcase
258 self.assertEqual(normcase(expected_cwd),
259 normcase(p.stdout.read().decode("utf-8")))
260
261 def test_cwd(self):
262 # Check that cwd changes the cwd for the child process.
263 temp_dir = tempfile.gettempdir()
264 temp_dir = self._normalize_cwd(temp_dir)
265 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
266
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700267 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700268 def test_cwd_with_relative_arg(self):
269 # Check that Popen looks for args[0] relative to cwd if args[0]
270 # is relative.
271 python_dir, python_base = self._split_python_path()
272 rel_python = os.path.join(os.curdir, python_base)
273 with support.temp_cwd() as wrong_dir:
274 # Before calling with the correct cwd, confirm that the call fails
275 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700276 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700277 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700278 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700279 [rel_python], cwd=wrong_dir)
280 python_dir = self._normalize_cwd(python_dir)
281 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
282
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700283 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700284 def test_cwd_with_relative_executable(self):
285 # Check that Popen looks for executable relative to cwd if executable
286 # is relative (and that executable takes precedence over args[0]).
287 python_dir, python_base = self._split_python_path()
288 rel_python = os.path.join(os.curdir, python_base)
289 doesntexist = "somethingyoudonthave"
290 with support.temp_cwd() as wrong_dir:
291 # Before calling with the correct cwd, confirm that the call fails
292 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700293 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700294 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700295 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700296 [doesntexist], executable=rel_python,
297 cwd=wrong_dir)
298 python_dir = self._normalize_cwd(python_dir)
299 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
300 cwd=python_dir)
301
302 def test_cwd_with_absolute_arg(self):
303 # Check that Popen can find the executable when the cwd is wrong
304 # if args[0] is an absolute path.
305 python_dir, python_base = self._split_python_path()
306 abs_python = os.path.join(python_dir, python_base)
307 rel_python = os.path.join(os.curdir, python_base)
308 with script_helper.temp_dir() as wrong_dir:
309 # Before calling with an absolute path, confirm that using a
310 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700311 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700312 [rel_python], cwd=wrong_dir)
313 wrong_dir = self._normalize_cwd(wrong_dir)
314 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
315
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100316 @unittest.skipIf(sys.base_prefix != sys.prefix,
317 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000318 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700319 python_dir, python_base = self._split_python_path()
320 python_dir = self._normalize_cwd(python_dir)
321 self._assert_cwd(python_dir, "somethingyoudonthave",
322 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000323
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100324 @unittest.skipIf(sys.base_prefix != sys.prefix,
325 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000326 @unittest.skipIf(sysconfig.is_python_build(),
327 "need an installed Python. See #7774")
328 def test_executable_without_cwd(self):
329 # For a normal installation, it should work without 'cwd'
330 # argument. For test runs in the build directory, see #7774.
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700331 self._assert_cwd('', "somethingyoudonthave", executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000332
333 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000334 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000335 p = subprocess.Popen([sys.executable, "-c",
336 'import sys; sys.exit(sys.stdin.read() == "pear")'],
337 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000338 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000339 p.stdin.close()
340 p.wait()
341 self.assertEqual(p.returncode, 1)
342
343 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000344 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000345 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000346 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000347 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000348 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000349 os.lseek(d, 0, 0)
350 p = subprocess.Popen([sys.executable, "-c",
351 'import sys; sys.exit(sys.stdin.read() == "pear")'],
352 stdin=d)
353 p.wait()
354 self.assertEqual(p.returncode, 1)
355
356 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000357 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000358 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000359 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000360 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000361 tf.seek(0)
362 p = subprocess.Popen([sys.executable, "-c",
363 'import sys; sys.exit(sys.stdin.read() == "pear")'],
364 stdin=tf)
365 p.wait()
366 self.assertEqual(p.returncode, 1)
367
368 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000369 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000370 p = subprocess.Popen([sys.executable, "-c",
371 'import sys; sys.stdout.write("orange")'],
372 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000373 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000374 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000375
376 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000377 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000378 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000379 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000380 d = tf.fileno()
381 p = subprocess.Popen([sys.executable, "-c",
382 'import sys; sys.stdout.write("orange")'],
383 stdout=d)
384 p.wait()
385 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000386 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000387
388 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000389 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000390 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000391 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000392 p = subprocess.Popen([sys.executable, "-c",
393 'import sys; sys.stdout.write("orange")'],
394 stdout=tf)
395 p.wait()
396 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000397 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000398
399 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000400 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000401 p = subprocess.Popen([sys.executable, "-c",
402 'import sys; sys.stderr.write("strawberry")'],
403 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000404 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000405 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000406
407 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000408 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000409 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000410 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000411 d = tf.fileno()
412 p = subprocess.Popen([sys.executable, "-c",
413 'import sys; sys.stderr.write("strawberry")'],
414 stderr=d)
415 p.wait()
416 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000417 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000418
419 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000420 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000421 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000422 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000423 p = subprocess.Popen([sys.executable, "-c",
424 'import sys; sys.stderr.write("strawberry")'],
425 stderr=tf)
426 p.wait()
427 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000428 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000429
430 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000431 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000432 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000433 'import sys;'
434 'sys.stdout.write("apple");'
435 'sys.stdout.flush();'
436 'sys.stderr.write("orange")'],
437 stdout=subprocess.PIPE,
438 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000439 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000440 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000441
442 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000443 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000444 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000445 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000446 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000447 'import sys;'
448 'sys.stdout.write("apple");'
449 'sys.stdout.flush();'
450 'sys.stderr.write("orange")'],
451 stdout=tf,
452 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000453 p.wait()
454 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000455 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000456
Thomas Wouters89f507f2006-12-13 04:49:30 +0000457 def test_stdout_filedes_of_stdout(self):
458 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000459 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000460 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000461 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000462
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200463 def test_stdout_devnull(self):
464 p = subprocess.Popen([sys.executable, "-c",
465 'for i in range(10240):'
466 'print("x" * 1024)'],
467 stdout=subprocess.DEVNULL)
468 p.wait()
469 self.assertEqual(p.stdout, None)
470
471 def test_stderr_devnull(self):
472 p = subprocess.Popen([sys.executable, "-c",
473 'import sys\n'
474 'for i in range(10240):'
475 'sys.stderr.write("x" * 1024)'],
476 stderr=subprocess.DEVNULL)
477 p.wait()
478 self.assertEqual(p.stderr, None)
479
480 def test_stdin_devnull(self):
481 p = subprocess.Popen([sys.executable, "-c",
482 'import sys;'
483 'sys.stdin.read(1)'],
484 stdin=subprocess.DEVNULL)
485 p.wait()
486 self.assertEqual(p.stdin, None)
487
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000488 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000489 newenv = os.environ.copy()
490 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200491 with subprocess.Popen([sys.executable, "-c",
492 'import sys,os;'
493 'sys.stdout.write(os.getenv("FRUIT"))'],
494 stdout=subprocess.PIPE,
495 env=newenv) as p:
496 stdout, stderr = p.communicate()
497 self.assertEqual(stdout, b"orange")
498
Victor Stinner62d51182011-06-23 01:02:25 +0200499 # Windows requires at least the SYSTEMROOT environment variable to start
500 # Python
501 @unittest.skipIf(sys.platform == 'win32',
502 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200503 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200504 'the python library cannot be loaded '
505 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200506 def test_empty_env(self):
507 with subprocess.Popen([sys.executable, "-c",
508 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200509 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200510 stdout=subprocess.PIPE,
511 env={}) as p:
512 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200513 self.assertIn(stdout.strip(),
514 (b"[]",
515 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
516 # environment
517 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000518
Peter Astrandcbac93c2005-03-03 20:24:28 +0000519 def test_communicate_stdin(self):
520 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000521 'import sys;'
522 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000523 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000524 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000525 self.assertEqual(p.returncode, 1)
526
527 def test_communicate_stdout(self):
528 p = subprocess.Popen([sys.executable, "-c",
529 'import sys; sys.stdout.write("pineapple")'],
530 stdout=subprocess.PIPE)
531 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000532 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000533 self.assertEqual(stderr, None)
534
535 def test_communicate_stderr(self):
536 p = subprocess.Popen([sys.executable, "-c",
537 'import sys; sys.stderr.write("pineapple")'],
538 stderr=subprocess.PIPE)
539 (stdout, stderr) = p.communicate()
540 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000541 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000542
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000543 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000544 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000545 'import sys,os;'
546 'sys.stderr.write("pineapple");'
547 'sys.stdout.write(sys.stdin.read())'],
548 stdin=subprocess.PIPE,
549 stdout=subprocess.PIPE,
550 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000551 self.addCleanup(p.stdout.close)
552 self.addCleanup(p.stderr.close)
553 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000554 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000555 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000556 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000557
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400558 def test_communicate_timeout(self):
559 p = subprocess.Popen([sys.executable, "-c",
560 'import sys,os,time;'
561 'sys.stderr.write("pineapple\\n");'
562 'time.sleep(1);'
563 'sys.stderr.write("pear\\n");'
564 'sys.stdout.write(sys.stdin.read())'],
565 universal_newlines=True,
566 stdin=subprocess.PIPE,
567 stdout=subprocess.PIPE,
568 stderr=subprocess.PIPE)
569 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
570 timeout=0.3)
571 # Make sure we can keep waiting for it, and that we get the whole output
572 # after it completes.
573 (stdout, stderr) = p.communicate()
574 self.assertEqual(stdout, "banana")
575 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
576
577 def test_communicate_timeout_large_ouput(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200578 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400579 p = subprocess.Popen([sys.executable, "-c",
580 'import sys,os,time;'
581 'sys.stdout.write("a" * (64 * 1024));'
582 'time.sleep(0.2);'
583 'sys.stdout.write("a" * (64 * 1024));'
584 'time.sleep(0.2);'
585 'sys.stdout.write("a" * (64 * 1024));'
586 'time.sleep(0.2);'
587 'sys.stdout.write("a" * (64 * 1024));'],
588 stdout=subprocess.PIPE)
589 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
590 (stdout, _) = p.communicate()
591 self.assertEqual(len(stdout), 4 * 64 * 1024)
592
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000593 # Test for the fd leak reported in http://bugs.python.org/issue2791.
594 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000595 for stdin_pipe in (False, True):
596 for stdout_pipe in (False, True):
597 for stderr_pipe in (False, True):
598 options = {}
599 if stdin_pipe:
600 options['stdin'] = subprocess.PIPE
601 if stdout_pipe:
602 options['stdout'] = subprocess.PIPE
603 if stderr_pipe:
604 options['stderr'] = subprocess.PIPE
605 if not options:
606 continue
607 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
608 p.communicate()
609 if p.stdin is not None:
610 self.assertTrue(p.stdin.closed)
611 if p.stdout is not None:
612 self.assertTrue(p.stdout.closed)
613 if p.stderr is not None:
614 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000615
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000616 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000617 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000618 p = subprocess.Popen([sys.executable, "-c",
619 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000620 (stdout, stderr) = p.communicate()
621 self.assertEqual(stdout, None)
622 self.assertEqual(stderr, None)
623
624 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000625 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000626 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000627 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000628 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000629 os.close(x)
630 os.close(y)
631 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000632 'import sys,os;'
633 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200634 'sys.stderr.write("x" * %d);'
635 'sys.stdout.write(sys.stdin.read())' %
636 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000637 stdin=subprocess.PIPE,
638 stdout=subprocess.PIPE,
639 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000640 self.addCleanup(p.stdout.close)
641 self.addCleanup(p.stderr.close)
642 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200643 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000644 (stdout, stderr) = p.communicate(string_to_write)
645 self.assertEqual(stdout, string_to_write)
646
647 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000648 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000649 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000650 'import sys,os;'
651 'sys.stdout.write(sys.stdin.read())'],
652 stdin=subprocess.PIPE,
653 stdout=subprocess.PIPE,
654 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000655 self.addCleanup(p.stdout.close)
656 self.addCleanup(p.stderr.close)
657 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000658 p.stdin.write(b"banana")
659 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000660 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000661 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000662
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000663 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000664 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000665 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200666 'buf = sys.stdout.buffer;'
667 'buf.write(sys.stdin.readline().encode());'
668 'buf.flush();'
669 'buf.write(b"line2\\n");'
670 'buf.flush();'
671 'buf.write(sys.stdin.read().encode());'
672 'buf.flush();'
673 'buf.write(b"line4\\n");'
674 'buf.flush();'
675 'buf.write(b"line5\\r\\n");'
676 'buf.flush();'
677 'buf.write(b"line6\\r");'
678 'buf.flush();'
679 'buf.write(b"\\nline7");'
680 'buf.flush();'
681 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200682 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000683 stdout=subprocess.PIPE,
684 universal_newlines=1)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200685 p.stdin.write("line1\n")
686 self.assertEqual(p.stdout.readline(), "line1\n")
687 p.stdin.write("line3\n")
688 p.stdin.close()
Brian Curtin3c6a9512010-11-05 03:58:52 +0000689 self.addCleanup(p.stdout.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200690 self.assertEqual(p.stdout.readline(),
691 "line2\n")
692 self.assertEqual(p.stdout.read(6),
693 "line3\n")
694 self.assertEqual(p.stdout.read(),
695 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000696
697 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000698 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000699 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000700 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200701 'buf = sys.stdout.buffer;'
702 'buf.write(b"line2\\n");'
703 'buf.flush();'
704 'buf.write(b"line4\\n");'
705 'buf.flush();'
706 'buf.write(b"line5\\r\\n");'
707 'buf.flush();'
708 'buf.write(b"line6\\r");'
709 'buf.flush();'
710 'buf.write(b"\\nline7");'
711 'buf.flush();'
712 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200713 stderr=subprocess.PIPE,
714 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000715 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000716 self.addCleanup(p.stdout.close)
717 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000718 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200719 self.assertEqual(stdout,
720 "line2\nline4\nline5\nline6\nline7\nline8")
721
722 def test_universal_newlines_communicate_stdin(self):
723 # universal newlines through communicate(), with only stdin
724 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300725 'import sys,os;' + SETBINARY + textwrap.dedent('''
726 s = sys.stdin.readline()
727 assert s == "line1\\n", repr(s)
728 s = sys.stdin.read()
729 assert s == "line3\\n", repr(s)
730 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200731 stdin=subprocess.PIPE,
732 universal_newlines=1)
733 (stdout, stderr) = p.communicate("line1\nline3\n")
734 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000735
Andrew Svetlovf3765072012-08-14 18:35:17 +0300736 def test_universal_newlines_communicate_input_none(self):
737 # Test communicate(input=None) with universal newlines.
738 #
739 # We set stdout to PIPE because, as of this writing, a different
740 # code path is tested when the number of pipes is zero or one.
741 p = subprocess.Popen([sys.executable, "-c", "pass"],
742 stdin=subprocess.PIPE,
743 stdout=subprocess.PIPE,
744 universal_newlines=True)
745 p.communicate()
746 self.assertEqual(p.returncode, 0)
747
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300748 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300749 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300750 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300751 'import sys,os;' + SETBINARY + textwrap.dedent('''
752 s = sys.stdin.buffer.readline()
753 sys.stdout.buffer.write(s)
754 sys.stdout.buffer.write(b"line2\\r")
755 sys.stderr.buffer.write(b"eline2\\n")
756 s = sys.stdin.buffer.read()
757 sys.stdout.buffer.write(s)
758 sys.stdout.buffer.write(b"line4\\n")
759 sys.stdout.buffer.write(b"line5\\r\\n")
760 sys.stderr.buffer.write(b"eline6\\r")
761 sys.stderr.buffer.write(b"eline7\\r\\nz")
762 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300763 stdin=subprocess.PIPE,
764 stderr=subprocess.PIPE,
765 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300766 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300767 self.addCleanup(p.stdout.close)
768 self.addCleanup(p.stderr.close)
769 (stdout, stderr) = p.communicate("line1\nline3\n")
770 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300771 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300772 # Python debug build push something like "[42442 refs]\n"
773 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300774 # Don't use assertStderrEqual because it strips CR and LF from output.
775 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300776
Andrew Svetlov82860712012-08-19 22:13:41 +0300777 def test_universal_newlines_communicate_encodings(self):
778 # Check that universal newlines mode works for various encodings,
779 # in particular for encodings in the UTF-16 and UTF-32 families.
780 # See issue #15595.
781 #
782 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
783 # without, and UTF-16 and UTF-32.
784 for encoding in ['utf-16', 'utf-32-be']:
785 old_getpreferredencoding = locale.getpreferredencoding
786 # Indirectly via io.TextIOWrapper, Popen() defaults to
787 # locale.getpreferredencoding(False) and earlier in Python 3.2 to
788 # locale.getpreferredencoding().
789 def getpreferredencoding(do_setlocale=True):
790 return encoding
791 code = ("import sys; "
792 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
793 encoding)
794 args = [sys.executable, '-c', code]
795 try:
796 locale.getpreferredencoding = getpreferredencoding
797 # We set stdin to be non-None because, as of this writing,
798 # a different code path is used when the number of pipes is
799 # zero or one.
800 popen = subprocess.Popen(args, universal_newlines=True,
801 stdin=subprocess.PIPE,
802 stdout=subprocess.PIPE)
803 stdout, stderr = popen.communicate(input='')
804 finally:
805 locale.getpreferredencoding = old_getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300806 self.assertEqual(stdout, '1\n2\n3\n4')
807
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000808 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000809 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000810 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000811 max_handles = 1026 # too much for most UNIX systems
812 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000813 max_handles = 2050 # too much for (at least some) Windows setups
814 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400815 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000816 try:
817 for i in range(max_handles):
818 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400819 tmpfile = os.path.join(tmpdir, support.TESTFN)
820 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000821 except OSError as e:
822 if e.errno != errno.EMFILE:
823 raise
824 break
825 else:
826 self.skipTest("failed to reach the file descriptor limit "
827 "(tried %d)" % max_handles)
828 # Close a couple of them (should be enough for a subprocess)
829 for i in range(10):
830 os.close(handles.pop())
831 # Loop creating some subprocesses. If one of them leaks some fds,
832 # the next loop iteration will fail by reaching the max fd limit.
833 for i in range(15):
834 p = subprocess.Popen([sys.executable, "-c",
835 "import sys;"
836 "sys.stdout.write(sys.stdin.read())"],
837 stdin=subprocess.PIPE,
838 stdout=subprocess.PIPE,
839 stderr=subprocess.PIPE)
840 data = p.communicate(b"lime")[0]
841 self.assertEqual(data, b"lime")
842 finally:
843 for h in handles:
844 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400845 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000846
847 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000848 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
849 '"a b c" d e')
850 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
851 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000852 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
853 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000854 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
855 'a\\\\\\b "de fg" h')
856 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
857 'a\\\\\\"b c d')
858 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
859 '"a\\\\b c" d e')
860 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
861 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000862 self.assertEqual(subprocess.list2cmdline(['ab', '']),
863 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000864
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000865 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200866 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +0200867 "import os; os.read(0, 1)"],
868 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200869 self.addCleanup(p.stdin.close)
870 self.assertIsNone(p.poll())
871 os.write(p.stdin.fileno(), b'A')
872 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000873 # Subsequent invocations should just return the returncode
874 self.assertEqual(p.poll(), 0)
875
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000876 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200877 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000878 self.assertEqual(p.wait(), 0)
879 # Subsequent invocations should just return the returncode
880 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000881
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400882 def test_wait_timeout(self):
883 p = subprocess.Popen([sys.executable,
Reid Kleckner93479cc2011-03-14 19:32:41 -0400884 "-c", "import time; time.sleep(0.1)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -0400885 with self.assertRaises(subprocess.TimeoutExpired) as c:
886 p.wait(timeout=0.01)
887 self.assertIn("0.01", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -0400888 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
889 # time to start.
890 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400891
Peter Astrand738131d2004-11-30 21:04:45 +0000892 def test_invalid_bufsize(self):
893 # an invalid type of the bufsize argument should raise
894 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000895 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000896 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000897
Guido van Rossum46a05a72007-06-07 21:56:45 +0000898 def test_bufsize_is_none(self):
899 # bufsize=None should be the same as bufsize=0.
900 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
901 self.assertEqual(p.wait(), 0)
902 # Again with keyword arg
903 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
904 self.assertEqual(p.wait(), 0)
905
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000906 def test_leaking_fds_on_error(self):
907 # see bug #5179: Popen leaks file descriptors to PIPEs if
908 # the child fails to execute; this will eventually exhaust
909 # the maximum number of open fds. 1024 seems a very common
910 # value for that limit, but Windows has 2048, so we loop
911 # 1024 times (each call leaked two fds).
912 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000913 # Windows raises IOError. Others raise OSError.
914 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000915 subprocess.Popen(['nonexisting_i_hope'],
916 stdout=subprocess.PIPE,
917 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400918 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400919 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000920 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000921
Victor Stinnerb3693582010-05-21 20:13:12 +0000922 def test_issue8780(self):
923 # Ensure that stdout is inherited from the parent
924 # if stdout=PIPE is not used
925 code = ';'.join((
926 'import subprocess, sys',
927 'retcode = subprocess.call('
928 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
929 'assert retcode == 0'))
930 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000931 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000932
Tim Goldenaf5ac392010-08-06 13:03:56 +0000933 def test_handles_closed_on_exception(self):
934 # If CreateProcess exits with an error, ensure the
935 # duplicate output handles are released
936 ifhandle, ifname = mkstemp()
937 ofhandle, ofname = mkstemp()
938 efhandle, efname = mkstemp()
939 try:
940 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
941 stderr=efhandle)
942 except OSError:
943 os.close(ifhandle)
944 os.remove(ifname)
945 os.close(ofhandle)
946 os.remove(ofname)
947 os.close(efhandle)
948 os.remove(efname)
949 self.assertFalse(os.path.exists(ifname))
950 self.assertFalse(os.path.exists(ofname))
951 self.assertFalse(os.path.exists(efname))
952
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200953 def test_communicate_epipe(self):
954 # Issue 10963: communicate() should hide EPIPE
955 p = subprocess.Popen([sys.executable, "-c", 'pass'],
956 stdin=subprocess.PIPE,
957 stdout=subprocess.PIPE,
958 stderr=subprocess.PIPE)
959 self.addCleanup(p.stdout.close)
960 self.addCleanup(p.stderr.close)
961 self.addCleanup(p.stdin.close)
962 p.communicate(b"x" * 2**20)
963
964 def test_communicate_epipe_only_stdin(self):
965 # Issue 10963: communicate() should hide EPIPE
966 p = subprocess.Popen([sys.executable, "-c", 'pass'],
967 stdin=subprocess.PIPE)
968 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200969 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200970 p.communicate(b"x" * 2**20)
971
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200972 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
973 "Requires signal.SIGUSR1")
974 @unittest.skipUnless(hasattr(os, 'kill'),
975 "Requires os.kill")
976 @unittest.skipUnless(hasattr(os, 'getppid'),
977 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200978 def test_communicate_eintr(self):
979 # Issue #12493: communicate() should handle EINTR
980 def handler(signum, frame):
981 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200982 old_handler = signal.signal(signal.SIGUSR1, handler)
983 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200984
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200985 args = [sys.executable, "-c",
986 'import os, signal;'
987 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200988 for stream in ('stdout', 'stderr'):
989 kw = {stream: subprocess.PIPE}
990 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200991 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200992 process.communicate()
993
Tim Peterse718f612004-10-12 21:51:32 +0000994
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000995# context manager
996class _SuppressCoreFiles(object):
997 """Try to prevent core files from being created."""
998 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000999
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001000 def __enter__(self):
1001 """Try to save previous ulimit, then set it to (0, 0)."""
Benjamin Peterson964561b2011-12-10 12:31:42 -05001002 if resource is not None:
1003 try:
1004 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
1005 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
1006 except (ValueError, resource.error):
1007 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001008
Ronald Oussoren102d11a2010-07-23 09:50:05 +00001009 if sys.platform == 'darwin':
1010 # Check if the 'Crash Reporter' on OSX was configured
1011 # in 'Developer' mode and warn that it will get triggered
1012 # when it is.
1013 #
1014 # This assumes that this context manager is used in tests
1015 # that might trigger the next manager.
1016 value = subprocess.Popen(['/usr/bin/defaults', 'read',
1017 'com.apple.CrashReporter', 'DialogType'],
1018 stdout=subprocess.PIPE).communicate()[0]
1019 if value.strip() == b'developer':
1020 print("this tests triggers the Crash Reporter, "
1021 "that is intentional", end='')
1022 sys.stdout.flush()
1023
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001024 def __exit__(self, *args):
1025 """Return core file behavior to default."""
1026 if self.old_limit is None:
1027 return
Benjamin Peterson964561b2011-12-10 12:31:42 -05001028 if resource is not None:
1029 try:
1030 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
1031 except (ValueError, resource.error):
1032 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001033
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001034
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001035@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001036class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001037
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001038 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001039 nonexistent_dir = "/_this/pa.th/does/not/exist"
1040 try:
1041 os.chdir(nonexistent_dir)
1042 except OSError as e:
1043 # This avoids hard coding the errno value or the OS perror()
1044 # string and instead capture the exception that we want to see
1045 # below for comparison.
1046 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +00001047 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001048 else:
1049 self.fail("chdir to nonexistant directory %s succeeded." %
1050 nonexistent_dir)
1051
1052 # Error in the child re-raised in the parent.
1053 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001054 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001055 cwd=nonexistent_dir)
1056 except OSError as e:
1057 # Test that the child process chdir failure actually makes
1058 # it up to the parent process as the correct exception.
1059 self.assertEqual(desired_exception.errno, e.errno)
1060 self.assertEqual(desired_exception.strerror, e.strerror)
1061 else:
1062 self.fail("Expected OSError: %s" % desired_exception)
1063
1064 def test_restore_signals(self):
1065 # Code coverage for both values of restore_signals to make sure it
1066 # at least does not blow up.
1067 # A test for behavior would be complex. Contributions welcome.
1068 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1069 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1070
1071 def test_start_new_session(self):
1072 # For code coverage of calling setsid(). We don't care if we get an
1073 # EPERM error from it depending on the test execution environment, that
1074 # still indicates that it was called.
1075 try:
1076 output = subprocess.check_output(
1077 [sys.executable, "-c",
1078 "import os; print(os.getpgid(os.getpid()))"],
1079 start_new_session=True)
1080 except OSError as e:
1081 if e.errno != errno.EPERM:
1082 raise
1083 else:
1084 parent_pgid = os.getpgid(os.getpid())
1085 child_pgid = int(output)
1086 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001087
1088 def test_run_abort(self):
1089 # returncode handles signal termination
1090 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001091 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001092 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001093 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001094 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001095
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001096 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001097 # DISCLAIMER: Setting environment variables is *not* a good use
1098 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001099 p = subprocess.Popen([sys.executable, "-c",
1100 'import sys,os;'
1101 'sys.stdout.write(os.getenv("FRUIT"))'],
1102 stdout=subprocess.PIPE,
1103 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +00001104 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001105 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001106
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001107 def test_preexec_exception(self):
1108 def raise_it():
1109 raise ValueError("What if two swallows carried a coconut?")
1110 try:
1111 p = subprocess.Popen([sys.executable, "-c", ""],
1112 preexec_fn=raise_it)
1113 except RuntimeError as e:
1114 self.assertTrue(
1115 subprocess._posixsubprocess,
1116 "Expected a ValueError from the preexec_fn")
1117 except ValueError as e:
1118 self.assertIn("coconut", e.args[0])
1119 else:
1120 self.fail("Exception raised by preexec_fn did not make it "
1121 "to the parent process.")
1122
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001123 def test_preexec_gc_module_failure(self):
1124 # This tests the code that disables garbage collection if the child
1125 # process will execute any Python.
1126 def raise_runtime_error():
1127 raise RuntimeError("this shouldn't escape")
1128 enabled = gc.isenabled()
1129 orig_gc_disable = gc.disable
1130 orig_gc_isenabled = gc.isenabled
1131 try:
1132 gc.disable()
1133 self.assertFalse(gc.isenabled())
1134 subprocess.call([sys.executable, '-c', ''],
1135 preexec_fn=lambda: None)
1136 self.assertFalse(gc.isenabled(),
1137 "Popen enabled gc when it shouldn't.")
1138
1139 gc.enable()
1140 self.assertTrue(gc.isenabled())
1141 subprocess.call([sys.executable, '-c', ''],
1142 preexec_fn=lambda: None)
1143 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1144
1145 gc.disable = raise_runtime_error
1146 self.assertRaises(RuntimeError, subprocess.Popen,
1147 [sys.executable, '-c', ''],
1148 preexec_fn=lambda: None)
1149
1150 del gc.isenabled # force an AttributeError
1151 self.assertRaises(AttributeError, subprocess.Popen,
1152 [sys.executable, '-c', ''],
1153 preexec_fn=lambda: None)
1154 finally:
1155 gc.disable = orig_gc_disable
1156 gc.isenabled = orig_gc_isenabled
1157 if not enabled:
1158 gc.disable()
1159
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001160 def test_args_string(self):
1161 # args is a string
1162 fd, fname = mkstemp()
1163 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001164 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001165 fobj.write("#!/bin/sh\n")
1166 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1167 sys.executable)
1168 os.chmod(fname, 0o700)
1169 p = subprocess.Popen(fname)
1170 p.wait()
1171 os.remove(fname)
1172 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001173
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001174 def test_invalid_args(self):
1175 # invalid arguments should raise ValueError
1176 self.assertRaises(ValueError, subprocess.call,
1177 [sys.executable, "-c",
1178 "import sys; sys.exit(47)"],
1179 startupinfo=47)
1180 self.assertRaises(ValueError, subprocess.call,
1181 [sys.executable, "-c",
1182 "import sys; sys.exit(47)"],
1183 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001184
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001185 def test_shell_sequence(self):
1186 # Run command through the shell (sequence)
1187 newenv = os.environ.copy()
1188 newenv["FRUIT"] = "apple"
1189 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1190 stdout=subprocess.PIPE,
1191 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001192 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001193 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001194
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001195 def test_shell_string(self):
1196 # Run command through the shell (string)
1197 newenv = os.environ.copy()
1198 newenv["FRUIT"] = "apple"
1199 p = subprocess.Popen("echo $FRUIT", shell=1,
1200 stdout=subprocess.PIPE,
1201 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001202 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001203 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001204
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001205 def test_call_string(self):
1206 # call() function with string argument on UNIX
1207 fd, fname = mkstemp()
1208 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001209 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001210 fobj.write("#!/bin/sh\n")
1211 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1212 sys.executable)
1213 os.chmod(fname, 0o700)
1214 rc = subprocess.call(fname)
1215 os.remove(fname)
1216 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001217
Stefan Krah9542cc62010-07-19 14:20:53 +00001218 def test_specific_shell(self):
1219 # Issue #9265: Incorrect name passed as arg[0].
1220 shells = []
1221 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1222 for name in ['bash', 'ksh']:
1223 sh = os.path.join(prefix, name)
1224 if os.path.isfile(sh):
1225 shells.append(sh)
1226 if not shells: # Will probably work for any shell but csh.
1227 self.skipTest("bash or ksh required for this test")
1228 sh = '/bin/sh'
1229 if os.path.isfile(sh) and not os.path.islink(sh):
1230 # Test will fail if /bin/sh is a symlink to csh.
1231 shells.append(sh)
1232 for sh in shells:
1233 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1234 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001235 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001236 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1237
Florent Xicluna4886d242010-03-08 13:27:26 +00001238 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001239 # Do not inherit file handles from the parent.
1240 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001241 p = subprocess.Popen([sys.executable, "-c", """if 1:
1242 import sys, time
1243 sys.stdout.write('x\\n')
1244 sys.stdout.flush()
1245 time.sleep(30)
1246 """],
1247 close_fds=True,
1248 stdin=subprocess.PIPE,
1249 stdout=subprocess.PIPE,
1250 stderr=subprocess.PIPE)
1251 # Wait for the interpreter to be completely initialized before
1252 # sending any signal.
1253 p.stdout.read(1)
1254 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001255 return p
1256
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001257 def _kill_dead_process(self, method, *args):
1258 # Do not inherit file handles from the parent.
1259 # It should fix failures on some platforms.
1260 p = subprocess.Popen([sys.executable, "-c", """if 1:
1261 import sys, time
1262 sys.stdout.write('x\\n')
1263 sys.stdout.flush()
1264 """],
1265 close_fds=True,
1266 stdin=subprocess.PIPE,
1267 stdout=subprocess.PIPE,
1268 stderr=subprocess.PIPE)
1269 # Wait for the interpreter to be completely initialized before
1270 # sending any signal.
1271 p.stdout.read(1)
1272 # The process should end after this
1273 time.sleep(1)
1274 # This shouldn't raise even though the child is now dead
1275 getattr(p, method)(*args)
1276 p.communicate()
1277
Florent Xicluna4886d242010-03-08 13:27:26 +00001278 def test_send_signal(self):
1279 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001280 _, stderr = p.communicate()
1281 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001282 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001283
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001284 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001285 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001286 _, stderr = p.communicate()
1287 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001288 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001289
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001290 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001291 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001292 _, stderr = p.communicate()
1293 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001294 self.assertEqual(p.wait(), -signal.SIGTERM)
1295
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001296 def test_send_signal_dead(self):
1297 # Sending a signal to a dead process
1298 self._kill_dead_process('send_signal', signal.SIGINT)
1299
1300 def test_kill_dead(self):
1301 # Killing a dead process
1302 self._kill_dead_process('kill')
1303
1304 def test_terminate_dead(self):
1305 # Terminating a dead process
1306 self._kill_dead_process('terminate')
1307
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001308 def check_close_std_fds(self, fds):
1309 # Issue #9905: test that subprocess pipes still work properly with
1310 # some standard fds closed
1311 stdin = 0
1312 newfds = []
1313 for a in fds:
1314 b = os.dup(a)
1315 newfds.append(b)
1316 if a == 0:
1317 stdin = b
1318 try:
1319 for fd in fds:
1320 os.close(fd)
1321 out, err = subprocess.Popen([sys.executable, "-c",
1322 'import sys;'
1323 'sys.stdout.write("apple");'
1324 'sys.stdout.flush();'
1325 'sys.stderr.write("orange")'],
1326 stdin=stdin,
1327 stdout=subprocess.PIPE,
1328 stderr=subprocess.PIPE).communicate()
1329 err = support.strip_python_stderr(err)
1330 self.assertEqual((out, err), (b'apple', b'orange'))
1331 finally:
1332 for b, a in zip(newfds, fds):
1333 os.dup2(b, a)
1334 for b in newfds:
1335 os.close(b)
1336
1337 def test_close_fd_0(self):
1338 self.check_close_std_fds([0])
1339
1340 def test_close_fd_1(self):
1341 self.check_close_std_fds([1])
1342
1343 def test_close_fd_2(self):
1344 self.check_close_std_fds([2])
1345
1346 def test_close_fds_0_1(self):
1347 self.check_close_std_fds([0, 1])
1348
1349 def test_close_fds_0_2(self):
1350 self.check_close_std_fds([0, 2])
1351
1352 def test_close_fds_1_2(self):
1353 self.check_close_std_fds([1, 2])
1354
1355 def test_close_fds_0_1_2(self):
1356 # Issue #10806: test that subprocess pipes still work properly with
1357 # all standard fds closed.
1358 self.check_close_std_fds([0, 1, 2])
1359
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001360 def test_remapping_std_fds(self):
1361 # open up some temporary files
1362 temps = [mkstemp() for i in range(3)]
1363 try:
1364 temp_fds = [fd for fd, fname in temps]
1365
1366 # unlink the files -- we won't need to reopen them
1367 for fd, fname in temps:
1368 os.unlink(fname)
1369
1370 # write some data to what will become stdin, and rewind
1371 os.write(temp_fds[1], b"STDIN")
1372 os.lseek(temp_fds[1], 0, 0)
1373
1374 # move the standard file descriptors out of the way
1375 saved_fds = [os.dup(fd) for fd in range(3)]
1376 try:
1377 # duplicate the file objects over the standard fd's
1378 for fd, temp_fd in enumerate(temp_fds):
1379 os.dup2(temp_fd, fd)
1380
1381 # now use those files in the "wrong" order, so that subprocess
1382 # has to rearrange them in the child
1383 p = subprocess.Popen([sys.executable, "-c",
1384 'import sys; got = sys.stdin.read();'
1385 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1386 stdin=temp_fds[1],
1387 stdout=temp_fds[2],
1388 stderr=temp_fds[0])
1389 p.wait()
1390 finally:
1391 # restore the original fd's underneath sys.stdin, etc.
1392 for std, saved in enumerate(saved_fds):
1393 os.dup2(saved, std)
1394 os.close(saved)
1395
1396 for fd in temp_fds:
1397 os.lseek(fd, 0, 0)
1398
1399 out = os.read(temp_fds[2], 1024)
1400 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1401 self.assertEqual(out, b"got STDIN")
1402 self.assertEqual(err, b"err")
1403
1404 finally:
1405 for fd in temp_fds:
1406 os.close(fd)
1407
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001408 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1409 # open up some temporary files
1410 temps = [mkstemp() for i in range(3)]
1411 temp_fds = [fd for fd, fname in temps]
1412 try:
1413 # unlink the files -- we won't need to reopen them
1414 for fd, fname in temps:
1415 os.unlink(fname)
1416
1417 # save a copy of the standard file descriptors
1418 saved_fds = [os.dup(fd) for fd in range(3)]
1419 try:
1420 # duplicate the temp files over the standard fd's 0, 1, 2
1421 for fd, temp_fd in enumerate(temp_fds):
1422 os.dup2(temp_fd, fd)
1423
1424 # write some data to what will become stdin, and rewind
1425 os.write(stdin_no, b"STDIN")
1426 os.lseek(stdin_no, 0, 0)
1427
1428 # now use those files in the given order, so that subprocess
1429 # has to rearrange them in the child
1430 p = subprocess.Popen([sys.executable, "-c",
1431 'import sys; got = sys.stdin.read();'
1432 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1433 stdin=stdin_no,
1434 stdout=stdout_no,
1435 stderr=stderr_no)
1436 p.wait()
1437
1438 for fd in temp_fds:
1439 os.lseek(fd, 0, 0)
1440
1441 out = os.read(stdout_no, 1024)
1442 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1443 finally:
1444 for std, saved in enumerate(saved_fds):
1445 os.dup2(saved, std)
1446 os.close(saved)
1447
1448 self.assertEqual(out, b"got STDIN")
1449 self.assertEqual(err, b"err")
1450
1451 finally:
1452 for fd in temp_fds:
1453 os.close(fd)
1454
1455 # When duping fds, if there arises a situation where one of the fds is
1456 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1457 # This tests all combinations of this.
1458 def test_swap_fds(self):
1459 self.check_swap_fds(0, 1, 2)
1460 self.check_swap_fds(0, 2, 1)
1461 self.check_swap_fds(1, 0, 2)
1462 self.check_swap_fds(1, 2, 0)
1463 self.check_swap_fds(2, 0, 1)
1464 self.check_swap_fds(2, 1, 0)
1465
Victor Stinner13bb71c2010-04-23 21:41:56 +00001466 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001467 def prepare():
1468 raise ValueError("surrogate:\uDCff")
1469
1470 try:
1471 subprocess.call(
1472 [sys.executable, "-c", "pass"],
1473 preexec_fn=prepare)
1474 except ValueError as err:
1475 # Pure Python implementations keeps the message
1476 self.assertIsNone(subprocess._posixsubprocess)
1477 self.assertEqual(str(err), "surrogate:\uDCff")
1478 except RuntimeError as err:
1479 # _posixsubprocess uses a default message
1480 self.assertIsNotNone(subprocess._posixsubprocess)
1481 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1482 else:
1483 self.fail("Expected ValueError or RuntimeError")
1484
Victor Stinner13bb71c2010-04-23 21:41:56 +00001485 def test_undecodable_env(self):
1486 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001487 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001488 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001489 env = os.environ.copy()
1490 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001491 # Use C locale to get ascii for the locale encoding to force
1492 # surrogate-escaping of \xFF in the child process; otherwise it can
1493 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001494 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001495 stdout = subprocess.check_output(
1496 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001497 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001498 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001499 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001500
1501 # test bytes
1502 key = key.encode("ascii", "surrogateescape")
1503 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001504 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001505 env = os.environ.copy()
1506 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001507 stdout = subprocess.check_output(
1508 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001509 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001510 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001511 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001512
Victor Stinnerb745a742010-05-18 17:17:23 +00001513 def test_bytes_program(self):
1514 abs_program = os.fsencode(sys.executable)
1515 path, program = os.path.split(sys.executable)
1516 program = os.fsencode(program)
1517
1518 # absolute bytes path
1519 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001520 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001521
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001522 # absolute bytes path as a string
1523 cmd = b"'" + abs_program + b"' -c pass"
1524 exitcode = subprocess.call(cmd, shell=True)
1525 self.assertEqual(exitcode, 0)
1526
Victor Stinnerb745a742010-05-18 17:17:23 +00001527 # bytes program, unicode PATH
1528 env = os.environ.copy()
1529 env["PATH"] = path
1530 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001531 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001532
1533 # bytes program, bytes PATH
1534 envb = os.environb.copy()
1535 envb[b"PATH"] = os.fsencode(path)
1536 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001537 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001538
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001539 def test_pipe_cloexec(self):
1540 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1541 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1542
1543 p1 = subprocess.Popen([sys.executable, sleeper],
1544 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1545 stderr=subprocess.PIPE, close_fds=False)
1546
1547 self.addCleanup(p1.communicate, b'')
1548
1549 p2 = subprocess.Popen([sys.executable, fd_status],
1550 stdout=subprocess.PIPE, close_fds=False)
1551
1552 output, error = p2.communicate()
1553 result_fds = set(map(int, output.split(b',')))
1554 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1555 p1.stderr.fileno()])
1556
1557 self.assertFalse(result_fds & unwanted_fds,
1558 "Expected no fds from %r to be open in child, "
1559 "found %r" %
1560 (unwanted_fds, result_fds & unwanted_fds))
1561
1562 def test_pipe_cloexec_real_tools(self):
1563 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1564 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1565
1566 subdata = b'zxcvbn'
1567 data = subdata * 4 + b'\n'
1568
1569 p1 = subprocess.Popen([sys.executable, qcat],
1570 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1571 close_fds=False)
1572
1573 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1574 stdin=p1.stdout, stdout=subprocess.PIPE,
1575 close_fds=False)
1576
1577 self.addCleanup(p1.wait)
1578 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001579 def kill_p1():
1580 try:
1581 p1.terminate()
1582 except ProcessLookupError:
1583 pass
1584 def kill_p2():
1585 try:
1586 p2.terminate()
1587 except ProcessLookupError:
1588 pass
1589 self.addCleanup(kill_p1)
1590 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001591
1592 p1.stdin.write(data)
1593 p1.stdin.close()
1594
1595 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1596
1597 self.assertTrue(readfiles, "The child hung")
1598 self.assertEqual(p2.stdout.read(), data)
1599
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001600 p1.stdout.close()
1601 p2.stdout.close()
1602
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001603 def test_close_fds(self):
1604 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1605
1606 fds = os.pipe()
1607 self.addCleanup(os.close, fds[0])
1608 self.addCleanup(os.close, fds[1])
1609
1610 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001611 # add a bunch more fds
1612 for _ in range(9):
1613 fd = os.open("/dev/null", os.O_RDONLY)
1614 self.addCleanup(os.close, fd)
1615 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001616
1617 p = subprocess.Popen([sys.executable, fd_status],
1618 stdout=subprocess.PIPE, close_fds=False)
1619 output, ignored = p.communicate()
1620 remaining_fds = set(map(int, output.split(b',')))
1621
1622 self.assertEqual(remaining_fds & open_fds, open_fds,
1623 "Some fds were closed")
1624
1625 p = subprocess.Popen([sys.executable, fd_status],
1626 stdout=subprocess.PIPE, close_fds=True)
1627 output, ignored = p.communicate()
1628 remaining_fds = set(map(int, output.split(b',')))
1629
1630 self.assertFalse(remaining_fds & open_fds,
1631 "Some fds were left open")
1632 self.assertIn(1, remaining_fds, "Subprocess failed")
1633
Gregory P. Smith8facece2012-01-21 14:01:08 -08001634 # Keep some of the fd's we opened open in the subprocess.
1635 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1636 fds_to_keep = set(open_fds.pop() for _ in range(8))
1637 p = subprocess.Popen([sys.executable, fd_status],
1638 stdout=subprocess.PIPE, close_fds=True,
1639 pass_fds=())
1640 output, ignored = p.communicate()
1641 remaining_fds = set(map(int, output.split(b',')))
1642
1643 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1644 "Some fds not in pass_fds were left open")
1645 self.assertIn(1, remaining_fds, "Subprocess failed")
1646
Victor Stinner88701e22011-06-01 13:13:04 +02001647 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1648 # descriptor of a pipe closed in the parent process is valid in the
1649 # child process according to fstat(), but the mode of the file
1650 # descriptor is invalid, and read or write raise an error.
1651 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001652 def test_pass_fds(self):
1653 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1654
1655 open_fds = set()
1656
1657 for x in range(5):
1658 fds = os.pipe()
1659 self.addCleanup(os.close, fds[0])
1660 self.addCleanup(os.close, fds[1])
1661 open_fds.update(fds)
1662
1663 for fd in open_fds:
1664 p = subprocess.Popen([sys.executable, fd_status],
1665 stdout=subprocess.PIPE, close_fds=True,
1666 pass_fds=(fd, ))
1667 output, ignored = p.communicate()
1668
1669 remaining_fds = set(map(int, output.split(b',')))
1670 to_be_closed = open_fds - {fd}
1671
1672 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1673 self.assertFalse(remaining_fds & to_be_closed,
1674 "fd to be closed passed")
1675
1676 # pass_fds overrides close_fds with a warning.
1677 with self.assertWarns(RuntimeWarning) as context:
1678 self.assertFalse(subprocess.call(
1679 [sys.executable, "-c", "import sys; sys.exit(0)"],
1680 close_fds=False, pass_fds=(fd, )))
1681 self.assertIn('overriding close_fds', str(context.warning))
1682
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001683 def test_stdout_stdin_are_single_inout_fd(self):
1684 with io.open(os.devnull, "r+") as inout:
1685 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1686 stdout=inout, stdin=inout)
1687 p.wait()
1688
1689 def test_stdout_stderr_are_single_inout_fd(self):
1690 with io.open(os.devnull, "r+") as inout:
1691 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1692 stdout=inout, stderr=inout)
1693 p.wait()
1694
1695 def test_stderr_stdin_are_single_inout_fd(self):
1696 with io.open(os.devnull, "r+") as inout:
1697 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1698 stderr=inout, stdin=inout)
1699 p.wait()
1700
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001701 def test_wait_when_sigchild_ignored(self):
1702 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1703 sigchild_ignore = support.findfile("sigchild_ignore.py",
1704 subdir="subprocessdata")
1705 p = subprocess.Popen([sys.executable, sigchild_ignore],
1706 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1707 stdout, stderr = p.communicate()
1708 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001709 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001710 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001711
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001712 def test_select_unbuffered(self):
1713 # Issue #11459: bufsize=0 should really set the pipes as
1714 # unbuffered (and therefore let select() work properly).
1715 select = support.import_module("select")
1716 p = subprocess.Popen([sys.executable, "-c",
1717 'import sys;'
1718 'sys.stdout.write("apple")'],
1719 stdout=subprocess.PIPE,
1720 bufsize=0)
1721 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001722 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001723 try:
1724 self.assertEqual(f.read(4), b"appl")
1725 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1726 finally:
1727 p.wait()
1728
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001729 def test_zombie_fast_process_del(self):
1730 # Issue #12650: on Unix, if Popen.__del__() was called before the
1731 # process exited, it wouldn't be added to subprocess._active, and would
1732 # remain a zombie.
1733 # spawn a Popen, and delete its reference before it exits
1734 p = subprocess.Popen([sys.executable, "-c",
1735 'import sys, time;'
1736 'time.sleep(0.2)'],
1737 stdout=subprocess.PIPE,
1738 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001739 self.addCleanup(p.stdout.close)
1740 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001741 ident = id(p)
1742 pid = p.pid
1743 del p
1744 # check that p is in the active processes list
1745 self.assertIn(ident, [id(o) for o in subprocess._active])
1746
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001747 def test_leak_fast_process_del_killed(self):
1748 # Issue #12650: on Unix, if Popen.__del__() was called before the
1749 # process exited, and the process got killed by a signal, it would never
1750 # be removed from subprocess._active, which triggered a FD and memory
1751 # leak.
1752 # spawn a Popen, delete its reference and kill it
1753 p = subprocess.Popen([sys.executable, "-c",
1754 'import time;'
1755 'time.sleep(3)'],
1756 stdout=subprocess.PIPE,
1757 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001758 self.addCleanup(p.stdout.close)
1759 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001760 ident = id(p)
1761 pid = p.pid
1762 del p
1763 os.kill(pid, signal.SIGKILL)
1764 # check that p is in the active processes list
1765 self.assertIn(ident, [id(o) for o in subprocess._active])
1766
1767 # let some time for the process to exit, and create a new Popen: this
1768 # should trigger the wait() of p
1769 time.sleep(0.2)
1770 with self.assertRaises(EnvironmentError) as c:
1771 with subprocess.Popen(['nonexisting_i_hope'],
1772 stdout=subprocess.PIPE,
1773 stderr=subprocess.PIPE) as proc:
1774 pass
1775 # p should have been wait()ed on, and removed from the _active list
1776 self.assertRaises(OSError, os.waitpid, pid, 0)
1777 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1778
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001779
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001780@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001781class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001782
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001783 def test_startupinfo(self):
1784 # startupinfo argument
1785 # We uses hardcoded constants, because we do not want to
1786 # depend on win32all.
1787 STARTF_USESHOWWINDOW = 1
1788 SW_MAXIMIZE = 3
1789 startupinfo = subprocess.STARTUPINFO()
1790 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1791 startupinfo.wShowWindow = SW_MAXIMIZE
1792 # Since Python is a console process, it won't be affected
1793 # by wShowWindow, but the argument should be silently
1794 # ignored
1795 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001796 startupinfo=startupinfo)
1797
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001798 def test_creationflags(self):
1799 # creationflags argument
1800 CREATE_NEW_CONSOLE = 16
1801 sys.stderr.write(" a DOS box should flash briefly ...\n")
1802 subprocess.call(sys.executable +
1803 ' -c "import time; time.sleep(0.25)"',
1804 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001805
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001806 def test_invalid_args(self):
1807 # invalid arguments should raise ValueError
1808 self.assertRaises(ValueError, subprocess.call,
1809 [sys.executable, "-c",
1810 "import sys; sys.exit(47)"],
1811 preexec_fn=lambda: 1)
1812 self.assertRaises(ValueError, subprocess.call,
1813 [sys.executable, "-c",
1814 "import sys; sys.exit(47)"],
1815 stdout=subprocess.PIPE,
1816 close_fds=True)
1817
1818 def test_close_fds(self):
1819 # close file descriptors
1820 rc = subprocess.call([sys.executable, "-c",
1821 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001822 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001823 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001824
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001825 def test_shell_sequence(self):
1826 # Run command through the shell (sequence)
1827 newenv = os.environ.copy()
1828 newenv["FRUIT"] = "physalis"
1829 p = subprocess.Popen(["set"], shell=1,
1830 stdout=subprocess.PIPE,
1831 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001832 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001833 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001834
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001835 def test_shell_string(self):
1836 # Run command through the shell (string)
1837 newenv = os.environ.copy()
1838 newenv["FRUIT"] = "physalis"
1839 p = subprocess.Popen("set", shell=1,
1840 stdout=subprocess.PIPE,
1841 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001842 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001843 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001844
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001845 def test_call_string(self):
1846 # call() function with string argument on Windows
1847 rc = subprocess.call(sys.executable +
1848 ' -c "import sys; sys.exit(47)"')
1849 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001850
Florent Xicluna4886d242010-03-08 13:27:26 +00001851 def _kill_process(self, method, *args):
1852 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001853 p = subprocess.Popen([sys.executable, "-c", """if 1:
1854 import sys, time
1855 sys.stdout.write('x\\n')
1856 sys.stdout.flush()
1857 time.sleep(30)
1858 """],
1859 stdin=subprocess.PIPE,
1860 stdout=subprocess.PIPE,
1861 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001862 self.addCleanup(p.stdout.close)
1863 self.addCleanup(p.stderr.close)
1864 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001865 # Wait for the interpreter to be completely initialized before
1866 # sending any signal.
1867 p.stdout.read(1)
1868 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001869 _, stderr = p.communicate()
1870 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001871 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001872 self.assertNotEqual(returncode, 0)
1873
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001874 def _kill_dead_process(self, method, *args):
1875 p = subprocess.Popen([sys.executable, "-c", """if 1:
1876 import sys, time
1877 sys.stdout.write('x\\n')
1878 sys.stdout.flush()
1879 sys.exit(42)
1880 """],
1881 stdin=subprocess.PIPE,
1882 stdout=subprocess.PIPE,
1883 stderr=subprocess.PIPE)
1884 self.addCleanup(p.stdout.close)
1885 self.addCleanup(p.stderr.close)
1886 self.addCleanup(p.stdin.close)
1887 # Wait for the interpreter to be completely initialized before
1888 # sending any signal.
1889 p.stdout.read(1)
1890 # The process should end after this
1891 time.sleep(1)
1892 # This shouldn't raise even though the child is now dead
1893 getattr(p, method)(*args)
1894 _, stderr = p.communicate()
1895 self.assertStderrEqual(stderr, b'')
1896 rc = p.wait()
1897 self.assertEqual(rc, 42)
1898
Florent Xicluna4886d242010-03-08 13:27:26 +00001899 def test_send_signal(self):
1900 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001901
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001902 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001903 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001904
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001905 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001906 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001907
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001908 def test_send_signal_dead(self):
1909 self._kill_dead_process('send_signal', signal.SIGTERM)
1910
1911 def test_kill_dead(self):
1912 self._kill_dead_process('kill')
1913
1914 def test_terminate_dead(self):
1915 self._kill_dead_process('terminate')
1916
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001917
Brett Cannona23810f2008-05-26 19:04:21 +00001918# The module says:
1919# "NB This only works (and is only relevant) for UNIX."
1920#
1921# Actually, getoutput should work on any platform with an os.popen, but
1922# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001923@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001924class CommandTests(unittest.TestCase):
1925 def test_getoutput(self):
1926 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1927 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1928 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001929
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001930 # we use mkdtemp in the next line to create an empty directory
1931 # under our exclusive control; from that, we can invent a pathname
1932 # that we _know_ won't exist. This is guaranteed to fail.
1933 dir = None
1934 try:
1935 dir = tempfile.mkdtemp()
1936 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001937
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001938 status, output = subprocess.getstatusoutput('cat ' + name)
1939 self.assertNotEqual(status, 0)
1940 finally:
1941 if dir is not None:
1942 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001943
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001944
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001945@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1946 "poll system call not supported")
1947class ProcessTestCaseNoPoll(ProcessTestCase):
1948 def setUp(self):
1949 subprocess._has_poll = False
1950 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001951
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001952 def tearDown(self):
1953 subprocess._has_poll = True
1954 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001955
1956
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001957class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001958 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001959 def test_eintr_retry_call(self):
1960 record_calls = []
1961 def fake_os_func(*args):
1962 record_calls.append(args)
1963 if len(record_calls) == 2:
1964 raise OSError(errno.EINTR, "fake interrupted system call")
1965 return tuple(reversed(args))
1966
1967 self.assertEqual((999, 256),
1968 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1969 self.assertEqual([(256, 999)], record_calls)
1970 # This time there will be an EINTR so it will loop once.
1971 self.assertEqual((666,),
1972 subprocess._eintr_retry_call(fake_os_func, 666))
1973 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1974
1975
Tim Golden126c2962010-08-11 14:20:40 +00001976@unittest.skipUnless(mswindows, "Windows-specific tests")
1977class CommandsWithSpaces (BaseTestCase):
1978
1979 def setUp(self):
1980 super().setUp()
1981 f, fname = mkstemp(".py", "te st")
1982 self.fname = fname.lower ()
1983 os.write(f, b"import sys;"
1984 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1985 )
1986 os.close(f)
1987
1988 def tearDown(self):
1989 os.remove(self.fname)
1990 super().tearDown()
1991
1992 def with_spaces(self, *args, **kwargs):
1993 kwargs['stdout'] = subprocess.PIPE
1994 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001995 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001996 self.assertEqual(
1997 p.stdout.read ().decode("mbcs"),
1998 "2 [%r, 'ab cd']" % self.fname
1999 )
2000
2001 def test_shell_string_with_spaces(self):
2002 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002003 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2004 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002005
2006 def test_shell_sequence_with_spaces(self):
2007 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002008 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002009
2010 def test_noshell_string_with_spaces(self):
2011 # call() function with string argument with spaces on Windows
2012 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2013 "ab cd"))
2014
2015 def test_noshell_sequence_with_spaces(self):
2016 # call() function with sequence argument with spaces on Windows
2017 self.with_spaces([sys.executable, self.fname, "ab cd"])
2018
Brian Curtin79cdb662010-12-03 02:46:02 +00002019
Georg Brandla86b2622012-02-20 21:34:57 +01002020class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00002021
2022 def test_pipe(self):
2023 with subprocess.Popen([sys.executable, "-c",
2024 "import sys;"
2025 "sys.stdout.write('stdout');"
2026 "sys.stderr.write('stderr');"],
2027 stdout=subprocess.PIPE,
2028 stderr=subprocess.PIPE) as proc:
2029 self.assertEqual(proc.stdout.read(), b"stdout")
2030 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2031
2032 self.assertTrue(proc.stdout.closed)
2033 self.assertTrue(proc.stderr.closed)
2034
2035 def test_returncode(self):
2036 with subprocess.Popen([sys.executable, "-c",
2037 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002038 pass
2039 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002040 self.assertEqual(proc.returncode, 100)
2041
2042 def test_communicate_stdin(self):
2043 with subprocess.Popen([sys.executable, "-c",
2044 "import sys;"
2045 "sys.exit(sys.stdin.read() == 'context')"],
2046 stdin=subprocess.PIPE) as proc:
2047 proc.communicate(b"context")
2048 self.assertEqual(proc.returncode, 1)
2049
2050 def test_invalid_args(self):
2051 with self.assertRaises(EnvironmentError) as c:
2052 with subprocess.Popen(['nonexisting_i_hope'],
2053 stdout=subprocess.PIPE,
2054 stderr=subprocess.PIPE) as proc:
2055 pass
2056
2057 if c.exception.errno != errno.ENOENT: # ignore "no such file"
2058 raise c.exception
2059
2060
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002061def test_main():
2062 unit_tests = (ProcessTestCase,
2063 POSIXProcessTestCase,
2064 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002065 CommandTests,
2066 ProcessTestCaseNoPoll,
2067 HelperFunctionTests,
2068 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02002069 ContextManagerTests,
2070 )
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002071
2072 support.run_unittest(*unit_tests)
2073 support.reap_children()
2074
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002075if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002076 unittest.main()