blob: 24924f609ce3ed4a5be6b6f350c588b7781032e9 [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 Jerdonekec3ea942012-09-30 00:10:28 -0700195 # For use in the test_cwd* tests below.
196 def _normalize_cwd(self, cwd):
197 # Normalize an expected cwd (for Tru64 support).
198 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
199 # strings. See bug #1063571.
200 original_cwd = os.getcwd()
201 os.chdir(cwd)
202 cwd = os.getcwd()
203 os.chdir(original_cwd)
204 return cwd
205
206 # For use in the test_cwd* tests below.
207 def _split_python_path(self):
208 # Return normalized (python_dir, python_base).
209 python_path = os.path.realpath(sys.executable)
210 return os.path.split(python_path)
211
212 # For use in the test_cwd* tests below.
213 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
214 # Invoke Python via Popen, and assert that (1) the call succeeds,
215 # and that (2) the current working directory of the child process
216 # matches *expected_cwd*.
217 p = subprocess.Popen([python_arg, "-c",
218 "import os, sys; "
219 "sys.stdout.write(os.getcwd()); "
220 "sys.exit(47)"],
221 stdout=subprocess.PIPE,
222 **kwargs)
223 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000224 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700225 self.assertEqual(47, p.returncode)
226 normcase = os.path.normcase
227 self.assertEqual(normcase(expected_cwd),
228 normcase(p.stdout.read().decode("utf-8")))
229
230 def test_cwd(self):
231 # Check that cwd changes the cwd for the child process.
232 temp_dir = tempfile.gettempdir()
233 temp_dir = self._normalize_cwd(temp_dir)
234 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
235
236 def test_cwd_with_relative_arg(self):
237 # Check that Popen looks for args[0] relative to cwd if args[0]
238 # is relative.
239 python_dir, python_base = self._split_python_path()
240 rel_python = os.path.join(os.curdir, python_base)
241 with support.temp_cwd() as wrong_dir:
242 # Before calling with the correct cwd, confirm that the call fails
243 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700244 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700245 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700246 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700247 [rel_python], cwd=wrong_dir)
248 python_dir = self._normalize_cwd(python_dir)
249 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
250
251 def test_cwd_with_relative_executable(self):
252 # Check that Popen looks for executable relative to cwd if executable
253 # is relative (and that executable takes precedence over args[0]).
254 python_dir, python_base = self._split_python_path()
255 rel_python = os.path.join(os.curdir, python_base)
256 doesntexist = "somethingyoudonthave"
257 with support.temp_cwd() as wrong_dir:
258 # Before calling with the correct cwd, confirm that the call fails
259 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700260 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700261 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700262 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700263 [doesntexist], executable=rel_python,
264 cwd=wrong_dir)
265 python_dir = self._normalize_cwd(python_dir)
266 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
267 cwd=python_dir)
268
269 def test_cwd_with_absolute_arg(self):
270 # Check that Popen can find the executable when the cwd is wrong
271 # if args[0] is an absolute path.
272 python_dir, python_base = self._split_python_path()
273 abs_python = os.path.join(python_dir, python_base)
274 rel_python = os.path.join(os.curdir, python_base)
275 with script_helper.temp_dir() as wrong_dir:
276 # Before calling with an absolute path, confirm that using a
277 # relative path fails.
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 wrong_dir = self._normalize_cwd(wrong_dir)
281 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
282
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100283 @unittest.skipIf(sys.base_prefix != sys.prefix,
284 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000285 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700286 python_dir, python_base = self._split_python_path()
287 python_dir = self._normalize_cwd(python_dir)
288 self._assert_cwd(python_dir, "somethingyoudonthave",
289 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000290
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100291 @unittest.skipIf(sys.base_prefix != sys.prefix,
292 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000293 @unittest.skipIf(sysconfig.is_python_build(),
294 "need an installed Python. See #7774")
295 def test_executable_without_cwd(self):
296 # For a normal installation, it should work without 'cwd'
297 # argument. For test runs in the build directory, see #7774.
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700298 self._assert_cwd('', "somethingyoudonthave", executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000299
300 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000301 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000302 p = subprocess.Popen([sys.executable, "-c",
303 'import sys; sys.exit(sys.stdin.read() == "pear")'],
304 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000305 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000306 p.stdin.close()
307 p.wait()
308 self.assertEqual(p.returncode, 1)
309
310 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000311 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000312 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000313 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000314 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000315 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000316 os.lseek(d, 0, 0)
317 p = subprocess.Popen([sys.executable, "-c",
318 'import sys; sys.exit(sys.stdin.read() == "pear")'],
319 stdin=d)
320 p.wait()
321 self.assertEqual(p.returncode, 1)
322
323 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000324 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000325 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000326 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000327 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000328 tf.seek(0)
329 p = subprocess.Popen([sys.executable, "-c",
330 'import sys; sys.exit(sys.stdin.read() == "pear")'],
331 stdin=tf)
332 p.wait()
333 self.assertEqual(p.returncode, 1)
334
335 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000336 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000337 p = subprocess.Popen([sys.executable, "-c",
338 'import sys; sys.stdout.write("orange")'],
339 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000340 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000341 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000342
343 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000344 # stdout 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()
348 p = subprocess.Popen([sys.executable, "-c",
349 'import sys; sys.stdout.write("orange")'],
350 stdout=d)
351 p.wait()
352 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000353 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000354
355 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000356 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000357 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000358 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000359 p = subprocess.Popen([sys.executable, "-c",
360 'import sys; sys.stdout.write("orange")'],
361 stdout=tf)
362 p.wait()
363 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000364 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000365
366 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000367 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000368 p = subprocess.Popen([sys.executable, "-c",
369 'import sys; sys.stderr.write("strawberry")'],
370 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000371 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000372 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000373
374 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000375 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000376 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000377 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000378 d = tf.fileno()
379 p = subprocess.Popen([sys.executable, "-c",
380 'import sys; sys.stderr.write("strawberry")'],
381 stderr=d)
382 p.wait()
383 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000384 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000385
386 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000387 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000388 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000389 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000390 p = subprocess.Popen([sys.executable, "-c",
391 'import sys; sys.stderr.write("strawberry")'],
392 stderr=tf)
393 p.wait()
394 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000395 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000396
397 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000398 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000399 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000400 'import sys;'
401 'sys.stdout.write("apple");'
402 'sys.stdout.flush();'
403 'sys.stderr.write("orange")'],
404 stdout=subprocess.PIPE,
405 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000406 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000407 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000408
409 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000410 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000411 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000412 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000413 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000414 'import sys;'
415 'sys.stdout.write("apple");'
416 'sys.stdout.flush();'
417 'sys.stderr.write("orange")'],
418 stdout=tf,
419 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000420 p.wait()
421 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000422 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000423
Thomas Wouters89f507f2006-12-13 04:49:30 +0000424 def test_stdout_filedes_of_stdout(self):
425 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000426 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000427 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000428 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000429
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200430 def test_stdout_devnull(self):
431 p = subprocess.Popen([sys.executable, "-c",
432 'for i in range(10240):'
433 'print("x" * 1024)'],
434 stdout=subprocess.DEVNULL)
435 p.wait()
436 self.assertEqual(p.stdout, None)
437
438 def test_stderr_devnull(self):
439 p = subprocess.Popen([sys.executable, "-c",
440 'import sys\n'
441 'for i in range(10240):'
442 'sys.stderr.write("x" * 1024)'],
443 stderr=subprocess.DEVNULL)
444 p.wait()
445 self.assertEqual(p.stderr, None)
446
447 def test_stdin_devnull(self):
448 p = subprocess.Popen([sys.executable, "-c",
449 'import sys;'
450 'sys.stdin.read(1)'],
451 stdin=subprocess.DEVNULL)
452 p.wait()
453 self.assertEqual(p.stdin, None)
454
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000455 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000456 newenv = os.environ.copy()
457 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200458 with subprocess.Popen([sys.executable, "-c",
459 'import sys,os;'
460 'sys.stdout.write(os.getenv("FRUIT"))'],
461 stdout=subprocess.PIPE,
462 env=newenv) as p:
463 stdout, stderr = p.communicate()
464 self.assertEqual(stdout, b"orange")
465
Victor Stinner62d51182011-06-23 01:02:25 +0200466 # Windows requires at least the SYSTEMROOT environment variable to start
467 # Python
468 @unittest.skipIf(sys.platform == 'win32',
469 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200470 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200471 'the python library cannot be loaded '
472 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200473 def test_empty_env(self):
474 with subprocess.Popen([sys.executable, "-c",
475 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200476 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200477 stdout=subprocess.PIPE,
478 env={}) as p:
479 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200480 self.assertIn(stdout.strip(),
481 (b"[]",
482 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
483 # environment
484 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000485
Peter Astrandcbac93c2005-03-03 20:24:28 +0000486 def test_communicate_stdin(self):
487 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000488 'import sys;'
489 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000490 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000491 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000492 self.assertEqual(p.returncode, 1)
493
494 def test_communicate_stdout(self):
495 p = subprocess.Popen([sys.executable, "-c",
496 'import sys; sys.stdout.write("pineapple")'],
497 stdout=subprocess.PIPE)
498 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000499 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000500 self.assertEqual(stderr, None)
501
502 def test_communicate_stderr(self):
503 p = subprocess.Popen([sys.executable, "-c",
504 'import sys; sys.stderr.write("pineapple")'],
505 stderr=subprocess.PIPE)
506 (stdout, stderr) = p.communicate()
507 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000508 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000509
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000510 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000511 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000512 'import sys,os;'
513 'sys.stderr.write("pineapple");'
514 'sys.stdout.write(sys.stdin.read())'],
515 stdin=subprocess.PIPE,
516 stdout=subprocess.PIPE,
517 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000518 self.addCleanup(p.stdout.close)
519 self.addCleanup(p.stderr.close)
520 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000521 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000522 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000523 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000524
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400525 def test_communicate_timeout(self):
526 p = subprocess.Popen([sys.executable, "-c",
527 'import sys,os,time;'
528 'sys.stderr.write("pineapple\\n");'
529 'time.sleep(1);'
530 'sys.stderr.write("pear\\n");'
531 'sys.stdout.write(sys.stdin.read())'],
532 universal_newlines=True,
533 stdin=subprocess.PIPE,
534 stdout=subprocess.PIPE,
535 stderr=subprocess.PIPE)
536 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
537 timeout=0.3)
538 # Make sure we can keep waiting for it, and that we get the whole output
539 # after it completes.
540 (stdout, stderr) = p.communicate()
541 self.assertEqual(stdout, "banana")
542 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
543
544 def test_communicate_timeout_large_ouput(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200545 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400546 p = subprocess.Popen([sys.executable, "-c",
547 'import sys,os,time;'
548 'sys.stdout.write("a" * (64 * 1024));'
549 'time.sleep(0.2);'
550 'sys.stdout.write("a" * (64 * 1024));'
551 'time.sleep(0.2);'
552 'sys.stdout.write("a" * (64 * 1024));'
553 'time.sleep(0.2);'
554 'sys.stdout.write("a" * (64 * 1024));'],
555 stdout=subprocess.PIPE)
556 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
557 (stdout, _) = p.communicate()
558 self.assertEqual(len(stdout), 4 * 64 * 1024)
559
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000560 # Test for the fd leak reported in http://bugs.python.org/issue2791.
561 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000562 for stdin_pipe in (False, True):
563 for stdout_pipe in (False, True):
564 for stderr_pipe in (False, True):
565 options = {}
566 if stdin_pipe:
567 options['stdin'] = subprocess.PIPE
568 if stdout_pipe:
569 options['stdout'] = subprocess.PIPE
570 if stderr_pipe:
571 options['stderr'] = subprocess.PIPE
572 if not options:
573 continue
574 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
575 p.communicate()
576 if p.stdin is not None:
577 self.assertTrue(p.stdin.closed)
578 if p.stdout is not None:
579 self.assertTrue(p.stdout.closed)
580 if p.stderr is not None:
581 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000582
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000583 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000584 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000585 p = subprocess.Popen([sys.executable, "-c",
586 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000587 (stdout, stderr) = p.communicate()
588 self.assertEqual(stdout, None)
589 self.assertEqual(stderr, None)
590
591 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000592 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000593 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000594 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000595 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000596 os.close(x)
597 os.close(y)
598 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000599 'import sys,os;'
600 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200601 'sys.stderr.write("x" * %d);'
602 'sys.stdout.write(sys.stdin.read())' %
603 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000604 stdin=subprocess.PIPE,
605 stdout=subprocess.PIPE,
606 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000607 self.addCleanup(p.stdout.close)
608 self.addCleanup(p.stderr.close)
609 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200610 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000611 (stdout, stderr) = p.communicate(string_to_write)
612 self.assertEqual(stdout, string_to_write)
613
614 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000615 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000616 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000617 'import sys,os;'
618 'sys.stdout.write(sys.stdin.read())'],
619 stdin=subprocess.PIPE,
620 stdout=subprocess.PIPE,
621 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000622 self.addCleanup(p.stdout.close)
623 self.addCleanup(p.stderr.close)
624 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000625 p.stdin.write(b"banana")
626 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000627 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000628 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000629
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000630 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000631 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000632 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200633 'buf = sys.stdout.buffer;'
634 'buf.write(sys.stdin.readline().encode());'
635 'buf.flush();'
636 'buf.write(b"line2\\n");'
637 'buf.flush();'
638 'buf.write(sys.stdin.read().encode());'
639 'buf.flush();'
640 'buf.write(b"line4\\n");'
641 'buf.flush();'
642 'buf.write(b"line5\\r\\n");'
643 'buf.flush();'
644 'buf.write(b"line6\\r");'
645 'buf.flush();'
646 'buf.write(b"\\nline7");'
647 'buf.flush();'
648 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200649 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000650 stdout=subprocess.PIPE,
651 universal_newlines=1)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200652 p.stdin.write("line1\n")
653 self.assertEqual(p.stdout.readline(), "line1\n")
654 p.stdin.write("line3\n")
655 p.stdin.close()
Brian Curtin3c6a9512010-11-05 03:58:52 +0000656 self.addCleanup(p.stdout.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200657 self.assertEqual(p.stdout.readline(),
658 "line2\n")
659 self.assertEqual(p.stdout.read(6),
660 "line3\n")
661 self.assertEqual(p.stdout.read(),
662 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000663
664 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000665 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000666 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000667 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200668 'buf = sys.stdout.buffer;'
669 'buf.write(b"line2\\n");'
670 'buf.flush();'
671 'buf.write(b"line4\\n");'
672 'buf.flush();'
673 'buf.write(b"line5\\r\\n");'
674 'buf.flush();'
675 'buf.write(b"line6\\r");'
676 'buf.flush();'
677 'buf.write(b"\\nline7");'
678 'buf.flush();'
679 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200680 stderr=subprocess.PIPE,
681 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000682 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000683 self.addCleanup(p.stdout.close)
684 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000685 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200686 self.assertEqual(stdout,
687 "line2\nline4\nline5\nline6\nline7\nline8")
688
689 def test_universal_newlines_communicate_stdin(self):
690 # universal newlines through communicate(), with only stdin
691 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300692 'import sys,os;' + SETBINARY + textwrap.dedent('''
693 s = sys.stdin.readline()
694 assert s == "line1\\n", repr(s)
695 s = sys.stdin.read()
696 assert s == "line3\\n", repr(s)
697 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200698 stdin=subprocess.PIPE,
699 universal_newlines=1)
700 (stdout, stderr) = p.communicate("line1\nline3\n")
701 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000702
Andrew Svetlovf3765072012-08-14 18:35:17 +0300703 def test_universal_newlines_communicate_input_none(self):
704 # Test communicate(input=None) with universal newlines.
705 #
706 # We set stdout to PIPE because, as of this writing, a different
707 # code path is tested when the number of pipes is zero or one.
708 p = subprocess.Popen([sys.executable, "-c", "pass"],
709 stdin=subprocess.PIPE,
710 stdout=subprocess.PIPE,
711 universal_newlines=True)
712 p.communicate()
713 self.assertEqual(p.returncode, 0)
714
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300715 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300716 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300717 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300718 'import sys,os;' + SETBINARY + textwrap.dedent('''
719 s = sys.stdin.buffer.readline()
720 sys.stdout.buffer.write(s)
721 sys.stdout.buffer.write(b"line2\\r")
722 sys.stderr.buffer.write(b"eline2\\n")
723 s = sys.stdin.buffer.read()
724 sys.stdout.buffer.write(s)
725 sys.stdout.buffer.write(b"line4\\n")
726 sys.stdout.buffer.write(b"line5\\r\\n")
727 sys.stderr.buffer.write(b"eline6\\r")
728 sys.stderr.buffer.write(b"eline7\\r\\nz")
729 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300730 stdin=subprocess.PIPE,
731 stderr=subprocess.PIPE,
732 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300733 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300734 self.addCleanup(p.stdout.close)
735 self.addCleanup(p.stderr.close)
736 (stdout, stderr) = p.communicate("line1\nline3\n")
737 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300738 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300739 # Python debug build push something like "[42442 refs]\n"
740 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300741 # Don't use assertStderrEqual because it strips CR and LF from output.
742 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300743
Andrew Svetlov82860712012-08-19 22:13:41 +0300744 def test_universal_newlines_communicate_encodings(self):
745 # Check that universal newlines mode works for various encodings,
746 # in particular for encodings in the UTF-16 and UTF-32 families.
747 # See issue #15595.
748 #
749 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
750 # without, and UTF-16 and UTF-32.
751 for encoding in ['utf-16', 'utf-32-be']:
752 old_getpreferredencoding = locale.getpreferredencoding
753 # Indirectly via io.TextIOWrapper, Popen() defaults to
754 # locale.getpreferredencoding(False) and earlier in Python 3.2 to
755 # locale.getpreferredencoding().
756 def getpreferredencoding(do_setlocale=True):
757 return encoding
758 code = ("import sys; "
759 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
760 encoding)
761 args = [sys.executable, '-c', code]
762 try:
763 locale.getpreferredencoding = getpreferredencoding
764 # We set stdin to be non-None because, as of this writing,
765 # a different code path is used when the number of pipes is
766 # zero or one.
767 popen = subprocess.Popen(args, universal_newlines=True,
768 stdin=subprocess.PIPE,
769 stdout=subprocess.PIPE)
770 stdout, stderr = popen.communicate(input='')
771 finally:
772 locale.getpreferredencoding = old_getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300773 self.assertEqual(stdout, '1\n2\n3\n4')
774
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000775 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000776 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000777 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000778 max_handles = 1026 # too much for most UNIX systems
779 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000780 max_handles = 2050 # too much for (at least some) Windows setups
781 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400782 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000783 try:
784 for i in range(max_handles):
785 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400786 tmpfile = os.path.join(tmpdir, support.TESTFN)
787 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000788 except OSError as e:
789 if e.errno != errno.EMFILE:
790 raise
791 break
792 else:
793 self.skipTest("failed to reach the file descriptor limit "
794 "(tried %d)" % max_handles)
795 # Close a couple of them (should be enough for a subprocess)
796 for i in range(10):
797 os.close(handles.pop())
798 # Loop creating some subprocesses. If one of them leaks some fds,
799 # the next loop iteration will fail by reaching the max fd limit.
800 for i in range(15):
801 p = subprocess.Popen([sys.executable, "-c",
802 "import sys;"
803 "sys.stdout.write(sys.stdin.read())"],
804 stdin=subprocess.PIPE,
805 stdout=subprocess.PIPE,
806 stderr=subprocess.PIPE)
807 data = p.communicate(b"lime")[0]
808 self.assertEqual(data, b"lime")
809 finally:
810 for h in handles:
811 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400812 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000813
814 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000815 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
816 '"a b c" d e')
817 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
818 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000819 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
820 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000821 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
822 'a\\\\\\b "de fg" h')
823 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
824 'a\\\\\\"b c d')
825 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
826 '"a\\\\b c" d e')
827 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
828 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000829 self.assertEqual(subprocess.list2cmdline(['ab', '']),
830 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000831
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000832 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200833 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +0200834 "import os; os.read(0, 1)"],
835 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200836 self.addCleanup(p.stdin.close)
837 self.assertIsNone(p.poll())
838 os.write(p.stdin.fileno(), b'A')
839 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000840 # Subsequent invocations should just return the returncode
841 self.assertEqual(p.poll(), 0)
842
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000843 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200844 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000845 self.assertEqual(p.wait(), 0)
846 # Subsequent invocations should just return the returncode
847 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000848
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400849 def test_wait_timeout(self):
850 p = subprocess.Popen([sys.executable,
Reid Kleckner93479cc2011-03-14 19:32:41 -0400851 "-c", "import time; time.sleep(0.1)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -0400852 with self.assertRaises(subprocess.TimeoutExpired) as c:
853 p.wait(timeout=0.01)
854 self.assertIn("0.01", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -0400855 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
856 # time to start.
857 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400858
Peter Astrand738131d2004-11-30 21:04:45 +0000859 def test_invalid_bufsize(self):
860 # an invalid type of the bufsize argument should raise
861 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000862 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000863 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000864
Guido van Rossum46a05a72007-06-07 21:56:45 +0000865 def test_bufsize_is_none(self):
866 # bufsize=None should be the same as bufsize=0.
867 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
868 self.assertEqual(p.wait(), 0)
869 # Again with keyword arg
870 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
871 self.assertEqual(p.wait(), 0)
872
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000873 def test_leaking_fds_on_error(self):
874 # see bug #5179: Popen leaks file descriptors to PIPEs if
875 # the child fails to execute; this will eventually exhaust
876 # the maximum number of open fds. 1024 seems a very common
877 # value for that limit, but Windows has 2048, so we loop
878 # 1024 times (each call leaked two fds).
879 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000880 # Windows raises IOError. Others raise OSError.
881 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000882 subprocess.Popen(['nonexisting_i_hope'],
883 stdout=subprocess.PIPE,
884 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400885 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400886 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000887 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000888
Victor Stinnerb3693582010-05-21 20:13:12 +0000889 def test_issue8780(self):
890 # Ensure that stdout is inherited from the parent
891 # if stdout=PIPE is not used
892 code = ';'.join((
893 'import subprocess, sys',
894 'retcode = subprocess.call('
895 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
896 'assert retcode == 0'))
897 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000898 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000899
Tim Goldenaf5ac392010-08-06 13:03:56 +0000900 def test_handles_closed_on_exception(self):
901 # If CreateProcess exits with an error, ensure the
902 # duplicate output handles are released
903 ifhandle, ifname = mkstemp()
904 ofhandle, ofname = mkstemp()
905 efhandle, efname = mkstemp()
906 try:
907 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
908 stderr=efhandle)
909 except OSError:
910 os.close(ifhandle)
911 os.remove(ifname)
912 os.close(ofhandle)
913 os.remove(ofname)
914 os.close(efhandle)
915 os.remove(efname)
916 self.assertFalse(os.path.exists(ifname))
917 self.assertFalse(os.path.exists(ofname))
918 self.assertFalse(os.path.exists(efname))
919
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200920 def test_communicate_epipe(self):
921 # Issue 10963: communicate() should hide EPIPE
922 p = subprocess.Popen([sys.executable, "-c", 'pass'],
923 stdin=subprocess.PIPE,
924 stdout=subprocess.PIPE,
925 stderr=subprocess.PIPE)
926 self.addCleanup(p.stdout.close)
927 self.addCleanup(p.stderr.close)
928 self.addCleanup(p.stdin.close)
929 p.communicate(b"x" * 2**20)
930
931 def test_communicate_epipe_only_stdin(self):
932 # Issue 10963: communicate() should hide EPIPE
933 p = subprocess.Popen([sys.executable, "-c", 'pass'],
934 stdin=subprocess.PIPE)
935 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200936 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200937 p.communicate(b"x" * 2**20)
938
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200939 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
940 "Requires signal.SIGUSR1")
941 @unittest.skipUnless(hasattr(os, 'kill'),
942 "Requires os.kill")
943 @unittest.skipUnless(hasattr(os, 'getppid'),
944 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200945 def test_communicate_eintr(self):
946 # Issue #12493: communicate() should handle EINTR
947 def handler(signum, frame):
948 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200949 old_handler = signal.signal(signal.SIGUSR1, handler)
950 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200951
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200952 args = [sys.executable, "-c",
953 'import os, signal;'
954 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200955 for stream in ('stdout', 'stderr'):
956 kw = {stream: subprocess.PIPE}
957 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200958 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200959 process.communicate()
960
Tim Peterse718f612004-10-12 21:51:32 +0000961
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000962# context manager
963class _SuppressCoreFiles(object):
964 """Try to prevent core files from being created."""
965 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000966
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000967 def __enter__(self):
968 """Try to save previous ulimit, then set it to (0, 0)."""
Benjamin Peterson964561b2011-12-10 12:31:42 -0500969 if resource is not None:
970 try:
971 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
972 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
973 except (ValueError, resource.error):
974 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000975
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000976 if sys.platform == 'darwin':
977 # Check if the 'Crash Reporter' on OSX was configured
978 # in 'Developer' mode and warn that it will get triggered
979 # when it is.
980 #
981 # This assumes that this context manager is used in tests
982 # that might trigger the next manager.
983 value = subprocess.Popen(['/usr/bin/defaults', 'read',
984 'com.apple.CrashReporter', 'DialogType'],
985 stdout=subprocess.PIPE).communicate()[0]
986 if value.strip() == b'developer':
987 print("this tests triggers the Crash Reporter, "
988 "that is intentional", end='')
989 sys.stdout.flush()
990
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000991 def __exit__(self, *args):
992 """Return core file behavior to default."""
993 if self.old_limit is None:
994 return
Benjamin Peterson964561b2011-12-10 12:31:42 -0500995 if resource is not None:
996 try:
997 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
998 except (ValueError, resource.error):
999 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001000
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001001
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001002@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001003class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001004
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001005 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001006 nonexistent_dir = "/_this/pa.th/does/not/exist"
1007 try:
1008 os.chdir(nonexistent_dir)
1009 except OSError as e:
1010 # This avoids hard coding the errno value or the OS perror()
1011 # string and instead capture the exception that we want to see
1012 # below for comparison.
1013 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +00001014 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001015 else:
1016 self.fail("chdir to nonexistant directory %s succeeded." %
1017 nonexistent_dir)
1018
1019 # Error in the child re-raised in the parent.
1020 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001021 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001022 cwd=nonexistent_dir)
1023 except OSError as e:
1024 # Test that the child process chdir failure actually makes
1025 # it up to the parent process as the correct exception.
1026 self.assertEqual(desired_exception.errno, e.errno)
1027 self.assertEqual(desired_exception.strerror, e.strerror)
1028 else:
1029 self.fail("Expected OSError: %s" % desired_exception)
1030
1031 def test_restore_signals(self):
1032 # Code coverage for both values of restore_signals to make sure it
1033 # at least does not blow up.
1034 # A test for behavior would be complex. Contributions welcome.
1035 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1036 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1037
1038 def test_start_new_session(self):
1039 # For code coverage of calling setsid(). We don't care if we get an
1040 # EPERM error from it depending on the test execution environment, that
1041 # still indicates that it was called.
1042 try:
1043 output = subprocess.check_output(
1044 [sys.executable, "-c",
1045 "import os; print(os.getpgid(os.getpid()))"],
1046 start_new_session=True)
1047 except OSError as e:
1048 if e.errno != errno.EPERM:
1049 raise
1050 else:
1051 parent_pgid = os.getpgid(os.getpid())
1052 child_pgid = int(output)
1053 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001054
1055 def test_run_abort(self):
1056 # returncode handles signal termination
1057 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001058 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001059 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001060 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001061 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001062
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001063 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001064 # DISCLAIMER: Setting environment variables is *not* a good use
1065 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001066 p = subprocess.Popen([sys.executable, "-c",
1067 'import sys,os;'
1068 'sys.stdout.write(os.getenv("FRUIT"))'],
1069 stdout=subprocess.PIPE,
1070 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +00001071 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001072 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001073
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001074 def test_preexec_exception(self):
1075 def raise_it():
1076 raise ValueError("What if two swallows carried a coconut?")
1077 try:
1078 p = subprocess.Popen([sys.executable, "-c", ""],
1079 preexec_fn=raise_it)
1080 except RuntimeError as e:
1081 self.assertTrue(
1082 subprocess._posixsubprocess,
1083 "Expected a ValueError from the preexec_fn")
1084 except ValueError as e:
1085 self.assertIn("coconut", e.args[0])
1086 else:
1087 self.fail("Exception raised by preexec_fn did not make it "
1088 "to the parent process.")
1089
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001090 def test_preexec_gc_module_failure(self):
1091 # This tests the code that disables garbage collection if the child
1092 # process will execute any Python.
1093 def raise_runtime_error():
1094 raise RuntimeError("this shouldn't escape")
1095 enabled = gc.isenabled()
1096 orig_gc_disable = gc.disable
1097 orig_gc_isenabled = gc.isenabled
1098 try:
1099 gc.disable()
1100 self.assertFalse(gc.isenabled())
1101 subprocess.call([sys.executable, '-c', ''],
1102 preexec_fn=lambda: None)
1103 self.assertFalse(gc.isenabled(),
1104 "Popen enabled gc when it shouldn't.")
1105
1106 gc.enable()
1107 self.assertTrue(gc.isenabled())
1108 subprocess.call([sys.executable, '-c', ''],
1109 preexec_fn=lambda: None)
1110 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1111
1112 gc.disable = raise_runtime_error
1113 self.assertRaises(RuntimeError, subprocess.Popen,
1114 [sys.executable, '-c', ''],
1115 preexec_fn=lambda: None)
1116
1117 del gc.isenabled # force an AttributeError
1118 self.assertRaises(AttributeError, subprocess.Popen,
1119 [sys.executable, '-c', ''],
1120 preexec_fn=lambda: None)
1121 finally:
1122 gc.disable = orig_gc_disable
1123 gc.isenabled = orig_gc_isenabled
1124 if not enabled:
1125 gc.disable()
1126
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001127 def test_args_string(self):
1128 # args is a string
1129 fd, fname = mkstemp()
1130 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001131 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001132 fobj.write("#!/bin/sh\n")
1133 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1134 sys.executable)
1135 os.chmod(fname, 0o700)
1136 p = subprocess.Popen(fname)
1137 p.wait()
1138 os.remove(fname)
1139 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001140
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001141 def test_invalid_args(self):
1142 # invalid arguments should raise ValueError
1143 self.assertRaises(ValueError, subprocess.call,
1144 [sys.executable, "-c",
1145 "import sys; sys.exit(47)"],
1146 startupinfo=47)
1147 self.assertRaises(ValueError, subprocess.call,
1148 [sys.executable, "-c",
1149 "import sys; sys.exit(47)"],
1150 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001151
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001152 def test_shell_sequence(self):
1153 # Run command through the shell (sequence)
1154 newenv = os.environ.copy()
1155 newenv["FRUIT"] = "apple"
1156 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1157 stdout=subprocess.PIPE,
1158 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001159 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001160 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001161
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001162 def test_shell_string(self):
1163 # Run command through the shell (string)
1164 newenv = os.environ.copy()
1165 newenv["FRUIT"] = "apple"
1166 p = subprocess.Popen("echo $FRUIT", shell=1,
1167 stdout=subprocess.PIPE,
1168 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001169 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001170 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001171
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001172 def test_call_string(self):
1173 # call() function with string argument on UNIX
1174 fd, fname = mkstemp()
1175 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001176 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001177 fobj.write("#!/bin/sh\n")
1178 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1179 sys.executable)
1180 os.chmod(fname, 0o700)
1181 rc = subprocess.call(fname)
1182 os.remove(fname)
1183 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001184
Stefan Krah9542cc62010-07-19 14:20:53 +00001185 def test_specific_shell(self):
1186 # Issue #9265: Incorrect name passed as arg[0].
1187 shells = []
1188 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1189 for name in ['bash', 'ksh']:
1190 sh = os.path.join(prefix, name)
1191 if os.path.isfile(sh):
1192 shells.append(sh)
1193 if not shells: # Will probably work for any shell but csh.
1194 self.skipTest("bash or ksh required for this test")
1195 sh = '/bin/sh'
1196 if os.path.isfile(sh) and not os.path.islink(sh):
1197 # Test will fail if /bin/sh is a symlink to csh.
1198 shells.append(sh)
1199 for sh in shells:
1200 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1201 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001202 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001203 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1204
Florent Xicluna4886d242010-03-08 13:27:26 +00001205 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001206 # Do not inherit file handles from the parent.
1207 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001208 p = subprocess.Popen([sys.executable, "-c", """if 1:
1209 import sys, time
1210 sys.stdout.write('x\\n')
1211 sys.stdout.flush()
1212 time.sleep(30)
1213 """],
1214 close_fds=True,
1215 stdin=subprocess.PIPE,
1216 stdout=subprocess.PIPE,
1217 stderr=subprocess.PIPE)
1218 # Wait for the interpreter to be completely initialized before
1219 # sending any signal.
1220 p.stdout.read(1)
1221 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001222 return p
1223
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001224 def _kill_dead_process(self, method, *args):
1225 # Do not inherit file handles from the parent.
1226 # It should fix failures on some platforms.
1227 p = subprocess.Popen([sys.executable, "-c", """if 1:
1228 import sys, time
1229 sys.stdout.write('x\\n')
1230 sys.stdout.flush()
1231 """],
1232 close_fds=True,
1233 stdin=subprocess.PIPE,
1234 stdout=subprocess.PIPE,
1235 stderr=subprocess.PIPE)
1236 # Wait for the interpreter to be completely initialized before
1237 # sending any signal.
1238 p.stdout.read(1)
1239 # The process should end after this
1240 time.sleep(1)
1241 # This shouldn't raise even though the child is now dead
1242 getattr(p, method)(*args)
1243 p.communicate()
1244
Florent Xicluna4886d242010-03-08 13:27:26 +00001245 def test_send_signal(self):
1246 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001247 _, stderr = p.communicate()
1248 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001249 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001250
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001251 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001252 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001253 _, stderr = p.communicate()
1254 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001255 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001256
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001257 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001258 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001259 _, stderr = p.communicate()
1260 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001261 self.assertEqual(p.wait(), -signal.SIGTERM)
1262
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001263 def test_send_signal_dead(self):
1264 # Sending a signal to a dead process
1265 self._kill_dead_process('send_signal', signal.SIGINT)
1266
1267 def test_kill_dead(self):
1268 # Killing a dead process
1269 self._kill_dead_process('kill')
1270
1271 def test_terminate_dead(self):
1272 # Terminating a dead process
1273 self._kill_dead_process('terminate')
1274
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001275 def check_close_std_fds(self, fds):
1276 # Issue #9905: test that subprocess pipes still work properly with
1277 # some standard fds closed
1278 stdin = 0
1279 newfds = []
1280 for a in fds:
1281 b = os.dup(a)
1282 newfds.append(b)
1283 if a == 0:
1284 stdin = b
1285 try:
1286 for fd in fds:
1287 os.close(fd)
1288 out, err = subprocess.Popen([sys.executable, "-c",
1289 'import sys;'
1290 'sys.stdout.write("apple");'
1291 'sys.stdout.flush();'
1292 'sys.stderr.write("orange")'],
1293 stdin=stdin,
1294 stdout=subprocess.PIPE,
1295 stderr=subprocess.PIPE).communicate()
1296 err = support.strip_python_stderr(err)
1297 self.assertEqual((out, err), (b'apple', b'orange'))
1298 finally:
1299 for b, a in zip(newfds, fds):
1300 os.dup2(b, a)
1301 for b in newfds:
1302 os.close(b)
1303
1304 def test_close_fd_0(self):
1305 self.check_close_std_fds([0])
1306
1307 def test_close_fd_1(self):
1308 self.check_close_std_fds([1])
1309
1310 def test_close_fd_2(self):
1311 self.check_close_std_fds([2])
1312
1313 def test_close_fds_0_1(self):
1314 self.check_close_std_fds([0, 1])
1315
1316 def test_close_fds_0_2(self):
1317 self.check_close_std_fds([0, 2])
1318
1319 def test_close_fds_1_2(self):
1320 self.check_close_std_fds([1, 2])
1321
1322 def test_close_fds_0_1_2(self):
1323 # Issue #10806: test that subprocess pipes still work properly with
1324 # all standard fds closed.
1325 self.check_close_std_fds([0, 1, 2])
1326
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001327 def test_remapping_std_fds(self):
1328 # open up some temporary files
1329 temps = [mkstemp() for i in range(3)]
1330 try:
1331 temp_fds = [fd for fd, fname in temps]
1332
1333 # unlink the files -- we won't need to reopen them
1334 for fd, fname in temps:
1335 os.unlink(fname)
1336
1337 # write some data to what will become stdin, and rewind
1338 os.write(temp_fds[1], b"STDIN")
1339 os.lseek(temp_fds[1], 0, 0)
1340
1341 # move the standard file descriptors out of the way
1342 saved_fds = [os.dup(fd) for fd in range(3)]
1343 try:
1344 # duplicate the file objects over the standard fd's
1345 for fd, temp_fd in enumerate(temp_fds):
1346 os.dup2(temp_fd, fd)
1347
1348 # now use those files in the "wrong" order, so that subprocess
1349 # has to rearrange them in the child
1350 p = subprocess.Popen([sys.executable, "-c",
1351 'import sys; got = sys.stdin.read();'
1352 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1353 stdin=temp_fds[1],
1354 stdout=temp_fds[2],
1355 stderr=temp_fds[0])
1356 p.wait()
1357 finally:
1358 # restore the original fd's underneath sys.stdin, etc.
1359 for std, saved in enumerate(saved_fds):
1360 os.dup2(saved, std)
1361 os.close(saved)
1362
1363 for fd in temp_fds:
1364 os.lseek(fd, 0, 0)
1365
1366 out = os.read(temp_fds[2], 1024)
1367 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1368 self.assertEqual(out, b"got STDIN")
1369 self.assertEqual(err, b"err")
1370
1371 finally:
1372 for fd in temp_fds:
1373 os.close(fd)
1374
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001375 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1376 # open up some temporary files
1377 temps = [mkstemp() for i in range(3)]
1378 temp_fds = [fd for fd, fname in temps]
1379 try:
1380 # unlink the files -- we won't need to reopen them
1381 for fd, fname in temps:
1382 os.unlink(fname)
1383
1384 # save a copy of the standard file descriptors
1385 saved_fds = [os.dup(fd) for fd in range(3)]
1386 try:
1387 # duplicate the temp files over the standard fd's 0, 1, 2
1388 for fd, temp_fd in enumerate(temp_fds):
1389 os.dup2(temp_fd, fd)
1390
1391 # write some data to what will become stdin, and rewind
1392 os.write(stdin_no, b"STDIN")
1393 os.lseek(stdin_no, 0, 0)
1394
1395 # now use those files in the given order, so that subprocess
1396 # has to rearrange them in the child
1397 p = subprocess.Popen([sys.executable, "-c",
1398 'import sys; got = sys.stdin.read();'
1399 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1400 stdin=stdin_no,
1401 stdout=stdout_no,
1402 stderr=stderr_no)
1403 p.wait()
1404
1405 for fd in temp_fds:
1406 os.lseek(fd, 0, 0)
1407
1408 out = os.read(stdout_no, 1024)
1409 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1410 finally:
1411 for std, saved in enumerate(saved_fds):
1412 os.dup2(saved, std)
1413 os.close(saved)
1414
1415 self.assertEqual(out, b"got STDIN")
1416 self.assertEqual(err, b"err")
1417
1418 finally:
1419 for fd in temp_fds:
1420 os.close(fd)
1421
1422 # When duping fds, if there arises a situation where one of the fds is
1423 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1424 # This tests all combinations of this.
1425 def test_swap_fds(self):
1426 self.check_swap_fds(0, 1, 2)
1427 self.check_swap_fds(0, 2, 1)
1428 self.check_swap_fds(1, 0, 2)
1429 self.check_swap_fds(1, 2, 0)
1430 self.check_swap_fds(2, 0, 1)
1431 self.check_swap_fds(2, 1, 0)
1432
Victor Stinner13bb71c2010-04-23 21:41:56 +00001433 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001434 def prepare():
1435 raise ValueError("surrogate:\uDCff")
1436
1437 try:
1438 subprocess.call(
1439 [sys.executable, "-c", "pass"],
1440 preexec_fn=prepare)
1441 except ValueError as err:
1442 # Pure Python implementations keeps the message
1443 self.assertIsNone(subprocess._posixsubprocess)
1444 self.assertEqual(str(err), "surrogate:\uDCff")
1445 except RuntimeError as err:
1446 # _posixsubprocess uses a default message
1447 self.assertIsNotNone(subprocess._posixsubprocess)
1448 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1449 else:
1450 self.fail("Expected ValueError or RuntimeError")
1451
Victor Stinner13bb71c2010-04-23 21:41:56 +00001452 def test_undecodable_env(self):
1453 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001454 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001455 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001456 env = os.environ.copy()
1457 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001458 # Use C locale to get ascii for the locale encoding to force
1459 # surrogate-escaping of \xFF in the child process; otherwise it can
1460 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001461 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001462 stdout = subprocess.check_output(
1463 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001464 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001465 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001466 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001467
1468 # test bytes
1469 key = key.encode("ascii", "surrogateescape")
1470 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001471 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001472 env = os.environ.copy()
1473 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001474 stdout = subprocess.check_output(
1475 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001476 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001477 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001478 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001479
Victor Stinnerb745a742010-05-18 17:17:23 +00001480 def test_bytes_program(self):
1481 abs_program = os.fsencode(sys.executable)
1482 path, program = os.path.split(sys.executable)
1483 program = os.fsencode(program)
1484
1485 # absolute bytes path
1486 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001487 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001488
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001489 # absolute bytes path as a string
1490 cmd = b"'" + abs_program + b"' -c pass"
1491 exitcode = subprocess.call(cmd, shell=True)
1492 self.assertEqual(exitcode, 0)
1493
Victor Stinnerb745a742010-05-18 17:17:23 +00001494 # bytes program, unicode PATH
1495 env = os.environ.copy()
1496 env["PATH"] = path
1497 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001498 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001499
1500 # bytes program, bytes PATH
1501 envb = os.environb.copy()
1502 envb[b"PATH"] = os.fsencode(path)
1503 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001504 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001505
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001506 def test_pipe_cloexec(self):
1507 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1508 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1509
1510 p1 = subprocess.Popen([sys.executable, sleeper],
1511 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1512 stderr=subprocess.PIPE, close_fds=False)
1513
1514 self.addCleanup(p1.communicate, b'')
1515
1516 p2 = subprocess.Popen([sys.executable, fd_status],
1517 stdout=subprocess.PIPE, close_fds=False)
1518
1519 output, error = p2.communicate()
1520 result_fds = set(map(int, output.split(b',')))
1521 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1522 p1.stderr.fileno()])
1523
1524 self.assertFalse(result_fds & unwanted_fds,
1525 "Expected no fds from %r to be open in child, "
1526 "found %r" %
1527 (unwanted_fds, result_fds & unwanted_fds))
1528
1529 def test_pipe_cloexec_real_tools(self):
1530 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1531 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1532
1533 subdata = b'zxcvbn'
1534 data = subdata * 4 + b'\n'
1535
1536 p1 = subprocess.Popen([sys.executable, qcat],
1537 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1538 close_fds=False)
1539
1540 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1541 stdin=p1.stdout, stdout=subprocess.PIPE,
1542 close_fds=False)
1543
1544 self.addCleanup(p1.wait)
1545 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001546 def kill_p1():
1547 try:
1548 p1.terminate()
1549 except ProcessLookupError:
1550 pass
1551 def kill_p2():
1552 try:
1553 p2.terminate()
1554 except ProcessLookupError:
1555 pass
1556 self.addCleanup(kill_p1)
1557 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001558
1559 p1.stdin.write(data)
1560 p1.stdin.close()
1561
1562 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1563
1564 self.assertTrue(readfiles, "The child hung")
1565 self.assertEqual(p2.stdout.read(), data)
1566
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001567 p1.stdout.close()
1568 p2.stdout.close()
1569
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001570 def test_close_fds(self):
1571 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1572
1573 fds = os.pipe()
1574 self.addCleanup(os.close, fds[0])
1575 self.addCleanup(os.close, fds[1])
1576
1577 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001578 # add a bunch more fds
1579 for _ in range(9):
1580 fd = os.open("/dev/null", os.O_RDONLY)
1581 self.addCleanup(os.close, fd)
1582 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001583
1584 p = subprocess.Popen([sys.executable, fd_status],
1585 stdout=subprocess.PIPE, close_fds=False)
1586 output, ignored = p.communicate()
1587 remaining_fds = set(map(int, output.split(b',')))
1588
1589 self.assertEqual(remaining_fds & open_fds, open_fds,
1590 "Some fds were closed")
1591
1592 p = subprocess.Popen([sys.executable, fd_status],
1593 stdout=subprocess.PIPE, close_fds=True)
1594 output, ignored = p.communicate()
1595 remaining_fds = set(map(int, output.split(b',')))
1596
1597 self.assertFalse(remaining_fds & open_fds,
1598 "Some fds were left open")
1599 self.assertIn(1, remaining_fds, "Subprocess failed")
1600
Gregory P. Smith8facece2012-01-21 14:01:08 -08001601 # Keep some of the fd's we opened open in the subprocess.
1602 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1603 fds_to_keep = set(open_fds.pop() for _ in range(8))
1604 p = subprocess.Popen([sys.executable, fd_status],
1605 stdout=subprocess.PIPE, close_fds=True,
1606 pass_fds=())
1607 output, ignored = p.communicate()
1608 remaining_fds = set(map(int, output.split(b',')))
1609
1610 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1611 "Some fds not in pass_fds were left open")
1612 self.assertIn(1, remaining_fds, "Subprocess failed")
1613
Victor Stinner88701e22011-06-01 13:13:04 +02001614 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1615 # descriptor of a pipe closed in the parent process is valid in the
1616 # child process according to fstat(), but the mode of the file
1617 # descriptor is invalid, and read or write raise an error.
1618 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001619 def test_pass_fds(self):
1620 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1621
1622 open_fds = set()
1623
1624 for x in range(5):
1625 fds = os.pipe()
1626 self.addCleanup(os.close, fds[0])
1627 self.addCleanup(os.close, fds[1])
1628 open_fds.update(fds)
1629
1630 for fd in open_fds:
1631 p = subprocess.Popen([sys.executable, fd_status],
1632 stdout=subprocess.PIPE, close_fds=True,
1633 pass_fds=(fd, ))
1634 output, ignored = p.communicate()
1635
1636 remaining_fds = set(map(int, output.split(b',')))
1637 to_be_closed = open_fds - {fd}
1638
1639 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1640 self.assertFalse(remaining_fds & to_be_closed,
1641 "fd to be closed passed")
1642
1643 # pass_fds overrides close_fds with a warning.
1644 with self.assertWarns(RuntimeWarning) as context:
1645 self.assertFalse(subprocess.call(
1646 [sys.executable, "-c", "import sys; sys.exit(0)"],
1647 close_fds=False, pass_fds=(fd, )))
1648 self.assertIn('overriding close_fds', str(context.warning))
1649
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001650 def test_stdout_stdin_are_single_inout_fd(self):
1651 with io.open(os.devnull, "r+") as inout:
1652 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1653 stdout=inout, stdin=inout)
1654 p.wait()
1655
1656 def test_stdout_stderr_are_single_inout_fd(self):
1657 with io.open(os.devnull, "r+") as inout:
1658 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1659 stdout=inout, stderr=inout)
1660 p.wait()
1661
1662 def test_stderr_stdin_are_single_inout_fd(self):
1663 with io.open(os.devnull, "r+") as inout:
1664 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1665 stderr=inout, stdin=inout)
1666 p.wait()
1667
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001668 def test_wait_when_sigchild_ignored(self):
1669 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1670 sigchild_ignore = support.findfile("sigchild_ignore.py",
1671 subdir="subprocessdata")
1672 p = subprocess.Popen([sys.executable, sigchild_ignore],
1673 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1674 stdout, stderr = p.communicate()
1675 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001676 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001677 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001678
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001679 def test_select_unbuffered(self):
1680 # Issue #11459: bufsize=0 should really set the pipes as
1681 # unbuffered (and therefore let select() work properly).
1682 select = support.import_module("select")
1683 p = subprocess.Popen([sys.executable, "-c",
1684 'import sys;'
1685 'sys.stdout.write("apple")'],
1686 stdout=subprocess.PIPE,
1687 bufsize=0)
1688 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001689 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001690 try:
1691 self.assertEqual(f.read(4), b"appl")
1692 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1693 finally:
1694 p.wait()
1695
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001696 def test_zombie_fast_process_del(self):
1697 # Issue #12650: on Unix, if Popen.__del__() was called before the
1698 # process exited, it wouldn't be added to subprocess._active, and would
1699 # remain a zombie.
1700 # spawn a Popen, and delete its reference before it exits
1701 p = subprocess.Popen([sys.executable, "-c",
1702 'import sys, time;'
1703 'time.sleep(0.2)'],
1704 stdout=subprocess.PIPE,
1705 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001706 self.addCleanup(p.stdout.close)
1707 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001708 ident = id(p)
1709 pid = p.pid
1710 del p
1711 # check that p is in the active processes list
1712 self.assertIn(ident, [id(o) for o in subprocess._active])
1713
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001714 def test_leak_fast_process_del_killed(self):
1715 # Issue #12650: on Unix, if Popen.__del__() was called before the
1716 # process exited, and the process got killed by a signal, it would never
1717 # be removed from subprocess._active, which triggered a FD and memory
1718 # leak.
1719 # spawn a Popen, delete its reference and kill it
1720 p = subprocess.Popen([sys.executable, "-c",
1721 'import time;'
1722 'time.sleep(3)'],
1723 stdout=subprocess.PIPE,
1724 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001725 self.addCleanup(p.stdout.close)
1726 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001727 ident = id(p)
1728 pid = p.pid
1729 del p
1730 os.kill(pid, signal.SIGKILL)
1731 # check that p is in the active processes list
1732 self.assertIn(ident, [id(o) for o in subprocess._active])
1733
1734 # let some time for the process to exit, and create a new Popen: this
1735 # should trigger the wait() of p
1736 time.sleep(0.2)
1737 with self.assertRaises(EnvironmentError) as c:
1738 with subprocess.Popen(['nonexisting_i_hope'],
1739 stdout=subprocess.PIPE,
1740 stderr=subprocess.PIPE) as proc:
1741 pass
1742 # p should have been wait()ed on, and removed from the _active list
1743 self.assertRaises(OSError, os.waitpid, pid, 0)
1744 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1745
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001746
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001747@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001748class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001749
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001750 def test_startupinfo(self):
1751 # startupinfo argument
1752 # We uses hardcoded constants, because we do not want to
1753 # depend on win32all.
1754 STARTF_USESHOWWINDOW = 1
1755 SW_MAXIMIZE = 3
1756 startupinfo = subprocess.STARTUPINFO()
1757 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1758 startupinfo.wShowWindow = SW_MAXIMIZE
1759 # Since Python is a console process, it won't be affected
1760 # by wShowWindow, but the argument should be silently
1761 # ignored
1762 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001763 startupinfo=startupinfo)
1764
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001765 def test_creationflags(self):
1766 # creationflags argument
1767 CREATE_NEW_CONSOLE = 16
1768 sys.stderr.write(" a DOS box should flash briefly ...\n")
1769 subprocess.call(sys.executable +
1770 ' -c "import time; time.sleep(0.25)"',
1771 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001772
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001773 def test_invalid_args(self):
1774 # invalid arguments should raise ValueError
1775 self.assertRaises(ValueError, subprocess.call,
1776 [sys.executable, "-c",
1777 "import sys; sys.exit(47)"],
1778 preexec_fn=lambda: 1)
1779 self.assertRaises(ValueError, subprocess.call,
1780 [sys.executable, "-c",
1781 "import sys; sys.exit(47)"],
1782 stdout=subprocess.PIPE,
1783 close_fds=True)
1784
1785 def test_close_fds(self):
1786 # close file descriptors
1787 rc = subprocess.call([sys.executable, "-c",
1788 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001789 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001790 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001791
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001792 def test_shell_sequence(self):
1793 # Run command through the shell (sequence)
1794 newenv = os.environ.copy()
1795 newenv["FRUIT"] = "physalis"
1796 p = subprocess.Popen(["set"], shell=1,
1797 stdout=subprocess.PIPE,
1798 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001799 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001800 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001801
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001802 def test_shell_string(self):
1803 # Run command through the shell (string)
1804 newenv = os.environ.copy()
1805 newenv["FRUIT"] = "physalis"
1806 p = subprocess.Popen("set", shell=1,
1807 stdout=subprocess.PIPE,
1808 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001809 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001810 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001811
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001812 def test_call_string(self):
1813 # call() function with string argument on Windows
1814 rc = subprocess.call(sys.executable +
1815 ' -c "import sys; sys.exit(47)"')
1816 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001817
Florent Xicluna4886d242010-03-08 13:27:26 +00001818 def _kill_process(self, method, *args):
1819 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001820 p = subprocess.Popen([sys.executable, "-c", """if 1:
1821 import sys, time
1822 sys.stdout.write('x\\n')
1823 sys.stdout.flush()
1824 time.sleep(30)
1825 """],
1826 stdin=subprocess.PIPE,
1827 stdout=subprocess.PIPE,
1828 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001829 self.addCleanup(p.stdout.close)
1830 self.addCleanup(p.stderr.close)
1831 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001832 # Wait for the interpreter to be completely initialized before
1833 # sending any signal.
1834 p.stdout.read(1)
1835 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001836 _, stderr = p.communicate()
1837 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001838 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001839 self.assertNotEqual(returncode, 0)
1840
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001841 def _kill_dead_process(self, method, *args):
1842 p = subprocess.Popen([sys.executable, "-c", """if 1:
1843 import sys, time
1844 sys.stdout.write('x\\n')
1845 sys.stdout.flush()
1846 sys.exit(42)
1847 """],
1848 stdin=subprocess.PIPE,
1849 stdout=subprocess.PIPE,
1850 stderr=subprocess.PIPE)
1851 self.addCleanup(p.stdout.close)
1852 self.addCleanup(p.stderr.close)
1853 self.addCleanup(p.stdin.close)
1854 # Wait for the interpreter to be completely initialized before
1855 # sending any signal.
1856 p.stdout.read(1)
1857 # The process should end after this
1858 time.sleep(1)
1859 # This shouldn't raise even though the child is now dead
1860 getattr(p, method)(*args)
1861 _, stderr = p.communicate()
1862 self.assertStderrEqual(stderr, b'')
1863 rc = p.wait()
1864 self.assertEqual(rc, 42)
1865
Florent Xicluna4886d242010-03-08 13:27:26 +00001866 def test_send_signal(self):
1867 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001868
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001869 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001870 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001871
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001872 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001873 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001874
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001875 def test_send_signal_dead(self):
1876 self._kill_dead_process('send_signal', signal.SIGTERM)
1877
1878 def test_kill_dead(self):
1879 self._kill_dead_process('kill')
1880
1881 def test_terminate_dead(self):
1882 self._kill_dead_process('terminate')
1883
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001884
Brett Cannona23810f2008-05-26 19:04:21 +00001885# The module says:
1886# "NB This only works (and is only relevant) for UNIX."
1887#
1888# Actually, getoutput should work on any platform with an os.popen, but
1889# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001890@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001891class CommandTests(unittest.TestCase):
1892 def test_getoutput(self):
1893 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1894 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1895 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001896
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001897 # we use mkdtemp in the next line to create an empty directory
1898 # under our exclusive control; from that, we can invent a pathname
1899 # that we _know_ won't exist. This is guaranteed to fail.
1900 dir = None
1901 try:
1902 dir = tempfile.mkdtemp()
1903 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001904
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001905 status, output = subprocess.getstatusoutput('cat ' + name)
1906 self.assertNotEqual(status, 0)
1907 finally:
1908 if dir is not None:
1909 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001910
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001911
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001912@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1913 "poll system call not supported")
1914class ProcessTestCaseNoPoll(ProcessTestCase):
1915 def setUp(self):
1916 subprocess._has_poll = False
1917 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001918
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001919 def tearDown(self):
1920 subprocess._has_poll = True
1921 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001922
1923
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001924class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001925 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001926 def test_eintr_retry_call(self):
1927 record_calls = []
1928 def fake_os_func(*args):
1929 record_calls.append(args)
1930 if len(record_calls) == 2:
1931 raise OSError(errno.EINTR, "fake interrupted system call")
1932 return tuple(reversed(args))
1933
1934 self.assertEqual((999, 256),
1935 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1936 self.assertEqual([(256, 999)], record_calls)
1937 # This time there will be an EINTR so it will loop once.
1938 self.assertEqual((666,),
1939 subprocess._eintr_retry_call(fake_os_func, 666))
1940 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1941
1942
Tim Golden126c2962010-08-11 14:20:40 +00001943@unittest.skipUnless(mswindows, "Windows-specific tests")
1944class CommandsWithSpaces (BaseTestCase):
1945
1946 def setUp(self):
1947 super().setUp()
1948 f, fname = mkstemp(".py", "te st")
1949 self.fname = fname.lower ()
1950 os.write(f, b"import sys;"
1951 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1952 )
1953 os.close(f)
1954
1955 def tearDown(self):
1956 os.remove(self.fname)
1957 super().tearDown()
1958
1959 def with_spaces(self, *args, **kwargs):
1960 kwargs['stdout'] = subprocess.PIPE
1961 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001962 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001963 self.assertEqual(
1964 p.stdout.read ().decode("mbcs"),
1965 "2 [%r, 'ab cd']" % self.fname
1966 )
1967
1968 def test_shell_string_with_spaces(self):
1969 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001970 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1971 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001972
1973 def test_shell_sequence_with_spaces(self):
1974 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001975 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001976
1977 def test_noshell_string_with_spaces(self):
1978 # call() function with string argument with spaces on Windows
1979 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1980 "ab cd"))
1981
1982 def test_noshell_sequence_with_spaces(self):
1983 # call() function with sequence argument with spaces on Windows
1984 self.with_spaces([sys.executable, self.fname, "ab cd"])
1985
Brian Curtin79cdb662010-12-03 02:46:02 +00001986
Georg Brandla86b2622012-02-20 21:34:57 +01001987class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00001988
1989 def test_pipe(self):
1990 with subprocess.Popen([sys.executable, "-c",
1991 "import sys;"
1992 "sys.stdout.write('stdout');"
1993 "sys.stderr.write('stderr');"],
1994 stdout=subprocess.PIPE,
1995 stderr=subprocess.PIPE) as proc:
1996 self.assertEqual(proc.stdout.read(), b"stdout")
1997 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1998
1999 self.assertTrue(proc.stdout.closed)
2000 self.assertTrue(proc.stderr.closed)
2001
2002 def test_returncode(self):
2003 with subprocess.Popen([sys.executable, "-c",
2004 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002005 pass
2006 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002007 self.assertEqual(proc.returncode, 100)
2008
2009 def test_communicate_stdin(self):
2010 with subprocess.Popen([sys.executable, "-c",
2011 "import sys;"
2012 "sys.exit(sys.stdin.read() == 'context')"],
2013 stdin=subprocess.PIPE) as proc:
2014 proc.communicate(b"context")
2015 self.assertEqual(proc.returncode, 1)
2016
2017 def test_invalid_args(self):
2018 with self.assertRaises(EnvironmentError) as c:
2019 with subprocess.Popen(['nonexisting_i_hope'],
2020 stdout=subprocess.PIPE,
2021 stderr=subprocess.PIPE) as proc:
2022 pass
2023
2024 if c.exception.errno != errno.ENOENT: # ignore "no such file"
2025 raise c.exception
2026
2027
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002028def test_main():
2029 unit_tests = (ProcessTestCase,
2030 POSIXProcessTestCase,
2031 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002032 CommandTests,
2033 ProcessTestCaseNoPoll,
2034 HelperFunctionTests,
2035 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02002036 ContextManagerTests,
2037 )
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002038
2039 support.run_unittest(*unit_tests)
2040 support.reap_children()
2041
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002042if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002043 unittest.main()