blob: 5494feb6f4905978d9d403bcd88b9b3ffa2c29da [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
Andrew Svetlovafbf90c2012-10-06 18:02:05 +0300195 @unittest.skipIf(mswindows, "path not included in Windows message")
196 def test_path_in_arg_not_found_message(self):
197 # Check that the error message displays the path not found when
198 # args[0] is not found.
199 self.assertRaisesRegex(FileNotFoundError, "notfound_blahblah",
200 subprocess.Popen, ["notfound_blahblah"])
201
202 @unittest.skipIf(mswindows, "path not displayed in Windows message")
203 def test_path_in_executable_not_found_message(self):
204 # Check that the error message displays the executable argument (and
205 # not args[0]) when the executable argument is not found
206 # (issue #16114).
207 # We call sys.exit() inside the code to prevent the test runner
208 # from hanging if the test fails and finds python.
209 self.assertRaisesRegex(FileNotFoundError, "notfound_blahblah",
210 subprocess.Popen, [sys.executable, "-c",
211 "import sys; sys.exit(47)"],
212 executable="notfound_blahblah")
213 self.assertRaisesRegex(FileNotFoundError, "exenotfound_blahblah",
214 subprocess.Popen, ["argnotfound_blahblah"],
215 executable="exenotfound_blahblah")
216
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700217 # For use in the test_cwd* tests below.
218 def _normalize_cwd(self, cwd):
219 # Normalize an expected cwd (for Tru64 support).
220 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
221 # strings. See bug #1063571.
222 original_cwd = os.getcwd()
223 os.chdir(cwd)
224 cwd = os.getcwd()
225 os.chdir(original_cwd)
226 return cwd
227
228 # For use in the test_cwd* tests below.
229 def _split_python_path(self):
230 # Return normalized (python_dir, python_base).
231 python_path = os.path.realpath(sys.executable)
232 return os.path.split(python_path)
233
234 # For use in the test_cwd* tests below.
235 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
236 # Invoke Python via Popen, and assert that (1) the call succeeds,
237 # and that (2) the current working directory of the child process
238 # matches *expected_cwd*.
239 p = subprocess.Popen([python_arg, "-c",
240 "import os, sys; "
241 "sys.stdout.write(os.getcwd()); "
242 "sys.exit(47)"],
243 stdout=subprocess.PIPE,
244 **kwargs)
245 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000246 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700247 self.assertEqual(47, p.returncode)
248 normcase = os.path.normcase
249 self.assertEqual(normcase(expected_cwd),
250 normcase(p.stdout.read().decode("utf-8")))
251
252 def test_cwd(self):
253 # Check that cwd changes the cwd for the child process.
254 temp_dir = tempfile.gettempdir()
255 temp_dir = self._normalize_cwd(temp_dir)
256 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
257
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700258 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700259 def test_cwd_with_relative_arg(self):
260 # Check that Popen looks for args[0] relative to cwd if args[0]
261 # is relative.
262 python_dir, python_base = self._split_python_path()
263 rel_python = os.path.join(os.curdir, python_base)
264 with support.temp_cwd() as wrong_dir:
265 # Before calling with the correct cwd, confirm that the call fails
266 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700267 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700268 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700269 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700270 [rel_python], cwd=wrong_dir)
271 python_dir = self._normalize_cwd(python_dir)
272 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
273
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700274 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700275 def test_cwd_with_relative_executable(self):
276 # Check that Popen looks for executable relative to cwd if executable
277 # is relative (and that executable takes precedence over args[0]).
278 python_dir, python_base = self._split_python_path()
279 rel_python = os.path.join(os.curdir, python_base)
280 doesntexist = "somethingyoudonthave"
281 with support.temp_cwd() as wrong_dir:
282 # Before calling with the correct cwd, confirm that the call fails
283 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700284 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700285 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700286 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700287 [doesntexist], executable=rel_python,
288 cwd=wrong_dir)
289 python_dir = self._normalize_cwd(python_dir)
290 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
291 cwd=python_dir)
292
293 def test_cwd_with_absolute_arg(self):
294 # Check that Popen can find the executable when the cwd is wrong
295 # if args[0] is an absolute path.
296 python_dir, python_base = self._split_python_path()
297 abs_python = os.path.join(python_dir, python_base)
298 rel_python = os.path.join(os.curdir, python_base)
299 with script_helper.temp_dir() as wrong_dir:
300 # Before calling with an absolute path, confirm that using a
301 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700302 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700303 [rel_python], cwd=wrong_dir)
304 wrong_dir = self._normalize_cwd(wrong_dir)
305 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
306
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100307 @unittest.skipIf(sys.base_prefix != sys.prefix,
308 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000309 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700310 python_dir, python_base = self._split_python_path()
311 python_dir = self._normalize_cwd(python_dir)
312 self._assert_cwd(python_dir, "somethingyoudonthave",
313 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000314
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100315 @unittest.skipIf(sys.base_prefix != sys.prefix,
316 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000317 @unittest.skipIf(sysconfig.is_python_build(),
318 "need an installed Python. See #7774")
319 def test_executable_without_cwd(self):
320 # For a normal installation, it should work without 'cwd'
321 # argument. For test runs in the build directory, see #7774.
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700322 self._assert_cwd('', "somethingyoudonthave", executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000323
Andrew Svetlov1a53c0c2012-10-05 22:52:15 +0300324 def test_executable_precedence(self):
325 # To the precedence of executable argument over args[0]
326 # For a normal installation, it should work without 'cwd'
327 # argument. For test runs in the build directory, see #7774.
328 python_dir = os.path.dirname(os.path.realpath(sys.executable))
329 p = subprocess.Popen(["nonexistent","-c",'import sys; sys.exit(42)'],
330 executable=sys.executable, cwd=python_dir)
331 p.wait()
332 self.assertEqual(p.returncode, 42)
333
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000334 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000335 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000336 p = subprocess.Popen([sys.executable, "-c",
337 'import sys; sys.exit(sys.stdin.read() == "pear")'],
338 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000339 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000340 p.stdin.close()
341 p.wait()
342 self.assertEqual(p.returncode, 1)
343
344 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000345 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000346 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000347 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000348 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000349 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000350 os.lseek(d, 0, 0)
351 p = subprocess.Popen([sys.executable, "-c",
352 'import sys; sys.exit(sys.stdin.read() == "pear")'],
353 stdin=d)
354 p.wait()
355 self.assertEqual(p.returncode, 1)
356
357 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000358 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000359 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000360 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000361 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000362 tf.seek(0)
363 p = subprocess.Popen([sys.executable, "-c",
364 'import sys; sys.exit(sys.stdin.read() == "pear")'],
365 stdin=tf)
366 p.wait()
367 self.assertEqual(p.returncode, 1)
368
369 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000370 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000371 p = subprocess.Popen([sys.executable, "-c",
372 'import sys; sys.stdout.write("orange")'],
373 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000374 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000375 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000376
377 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000378 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000379 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000380 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000381 d = tf.fileno()
382 p = subprocess.Popen([sys.executable, "-c",
383 'import sys; sys.stdout.write("orange")'],
384 stdout=d)
385 p.wait()
386 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000387 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000388
389 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000390 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000391 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000392 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000393 p = subprocess.Popen([sys.executable, "-c",
394 'import sys; sys.stdout.write("orange")'],
395 stdout=tf)
396 p.wait()
397 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000398 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000399
400 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000401 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000402 p = subprocess.Popen([sys.executable, "-c",
403 'import sys; sys.stderr.write("strawberry")'],
404 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000405 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000406 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000407
408 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000409 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000410 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000411 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000412 d = tf.fileno()
413 p = subprocess.Popen([sys.executable, "-c",
414 'import sys; sys.stderr.write("strawberry")'],
415 stderr=d)
416 p.wait()
417 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000418 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000419
420 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000421 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000422 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000423 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000424 p = subprocess.Popen([sys.executable, "-c",
425 'import sys; sys.stderr.write("strawberry")'],
426 stderr=tf)
427 p.wait()
428 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000429 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000430
431 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000432 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000433 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000434 'import sys;'
435 'sys.stdout.write("apple");'
436 'sys.stdout.flush();'
437 'sys.stderr.write("orange")'],
438 stdout=subprocess.PIPE,
439 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000440 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000441 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000442
443 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000444 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000445 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000446 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000447 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000448 'import sys;'
449 'sys.stdout.write("apple");'
450 'sys.stdout.flush();'
451 'sys.stderr.write("orange")'],
452 stdout=tf,
453 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000454 p.wait()
455 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000456 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000457
Thomas Wouters89f507f2006-12-13 04:49:30 +0000458 def test_stdout_filedes_of_stdout(self):
459 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000460 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000461 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000462 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000463
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200464 def test_stdout_devnull(self):
465 p = subprocess.Popen([sys.executable, "-c",
466 'for i in range(10240):'
467 'print("x" * 1024)'],
468 stdout=subprocess.DEVNULL)
469 p.wait()
470 self.assertEqual(p.stdout, None)
471
472 def test_stderr_devnull(self):
473 p = subprocess.Popen([sys.executable, "-c",
474 'import sys\n'
475 'for i in range(10240):'
476 'sys.stderr.write("x" * 1024)'],
477 stderr=subprocess.DEVNULL)
478 p.wait()
479 self.assertEqual(p.stderr, None)
480
481 def test_stdin_devnull(self):
482 p = subprocess.Popen([sys.executable, "-c",
483 'import sys;'
484 'sys.stdin.read(1)'],
485 stdin=subprocess.DEVNULL)
486 p.wait()
487 self.assertEqual(p.stdin, None)
488
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000489 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000490 newenv = os.environ.copy()
491 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200492 with subprocess.Popen([sys.executable, "-c",
493 'import sys,os;'
494 'sys.stdout.write(os.getenv("FRUIT"))'],
495 stdout=subprocess.PIPE,
496 env=newenv) as p:
497 stdout, stderr = p.communicate()
498 self.assertEqual(stdout, b"orange")
499
Victor Stinner62d51182011-06-23 01:02:25 +0200500 # Windows requires at least the SYSTEMROOT environment variable to start
501 # Python
502 @unittest.skipIf(sys.platform == 'win32',
503 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200504 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200505 'the python library cannot be loaded '
506 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200507 def test_empty_env(self):
508 with subprocess.Popen([sys.executable, "-c",
509 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200510 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200511 stdout=subprocess.PIPE,
512 env={}) as p:
513 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200514 self.assertIn(stdout.strip(),
515 (b"[]",
516 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
517 # environment
518 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000519
Peter Astrandcbac93c2005-03-03 20:24:28 +0000520 def test_communicate_stdin(self):
521 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000522 'import sys;'
523 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000524 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000525 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000526 self.assertEqual(p.returncode, 1)
527
528 def test_communicate_stdout(self):
529 p = subprocess.Popen([sys.executable, "-c",
530 'import sys; sys.stdout.write("pineapple")'],
531 stdout=subprocess.PIPE)
532 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000533 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000534 self.assertEqual(stderr, None)
535
536 def test_communicate_stderr(self):
537 p = subprocess.Popen([sys.executable, "-c",
538 'import sys; sys.stderr.write("pineapple")'],
539 stderr=subprocess.PIPE)
540 (stdout, stderr) = p.communicate()
541 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000542 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000543
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000544 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000545 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000546 'import sys,os;'
547 'sys.stderr.write("pineapple");'
548 'sys.stdout.write(sys.stdin.read())'],
549 stdin=subprocess.PIPE,
550 stdout=subprocess.PIPE,
551 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000552 self.addCleanup(p.stdout.close)
553 self.addCleanup(p.stderr.close)
554 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000555 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000556 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000557 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000558
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400559 def test_communicate_timeout(self):
560 p = subprocess.Popen([sys.executable, "-c",
561 'import sys,os,time;'
562 'sys.stderr.write("pineapple\\n");'
563 'time.sleep(1);'
564 'sys.stderr.write("pear\\n");'
565 'sys.stdout.write(sys.stdin.read())'],
566 universal_newlines=True,
567 stdin=subprocess.PIPE,
568 stdout=subprocess.PIPE,
569 stderr=subprocess.PIPE)
570 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
571 timeout=0.3)
572 # Make sure we can keep waiting for it, and that we get the whole output
573 # after it completes.
574 (stdout, stderr) = p.communicate()
575 self.assertEqual(stdout, "banana")
576 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
577
578 def test_communicate_timeout_large_ouput(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200579 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400580 p = subprocess.Popen([sys.executable, "-c",
581 'import sys,os,time;'
582 'sys.stdout.write("a" * (64 * 1024));'
583 'time.sleep(0.2);'
584 'sys.stdout.write("a" * (64 * 1024));'
585 'time.sleep(0.2);'
586 'sys.stdout.write("a" * (64 * 1024));'
587 'time.sleep(0.2);'
588 'sys.stdout.write("a" * (64 * 1024));'],
589 stdout=subprocess.PIPE)
590 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
591 (stdout, _) = p.communicate()
592 self.assertEqual(len(stdout), 4 * 64 * 1024)
593
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000594 # Test for the fd leak reported in http://bugs.python.org/issue2791.
595 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000596 for stdin_pipe in (False, True):
597 for stdout_pipe in (False, True):
598 for stderr_pipe in (False, True):
599 options = {}
600 if stdin_pipe:
601 options['stdin'] = subprocess.PIPE
602 if stdout_pipe:
603 options['stdout'] = subprocess.PIPE
604 if stderr_pipe:
605 options['stderr'] = subprocess.PIPE
606 if not options:
607 continue
608 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
609 p.communicate()
610 if p.stdin is not None:
611 self.assertTrue(p.stdin.closed)
612 if p.stdout is not None:
613 self.assertTrue(p.stdout.closed)
614 if p.stderr is not None:
615 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000616
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000617 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000618 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000619 p = subprocess.Popen([sys.executable, "-c",
620 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000621 (stdout, stderr) = p.communicate()
622 self.assertEqual(stdout, None)
623 self.assertEqual(stderr, None)
624
625 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000626 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000627 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000628 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000629 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000630 os.close(x)
631 os.close(y)
632 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000633 'import sys,os;'
634 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200635 'sys.stderr.write("x" * %d);'
636 'sys.stdout.write(sys.stdin.read())' %
637 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000638 stdin=subprocess.PIPE,
639 stdout=subprocess.PIPE,
640 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000641 self.addCleanup(p.stdout.close)
642 self.addCleanup(p.stderr.close)
643 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200644 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000645 (stdout, stderr) = p.communicate(string_to_write)
646 self.assertEqual(stdout, string_to_write)
647
648 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000649 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000650 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000651 'import sys,os;'
652 'sys.stdout.write(sys.stdin.read())'],
653 stdin=subprocess.PIPE,
654 stdout=subprocess.PIPE,
655 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000656 self.addCleanup(p.stdout.close)
657 self.addCleanup(p.stderr.close)
658 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000659 p.stdin.write(b"banana")
660 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000661 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000662 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000663
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000664 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000665 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000666 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200667 'buf = sys.stdout.buffer;'
668 'buf.write(sys.stdin.readline().encode());'
669 'buf.flush();'
670 'buf.write(b"line2\\n");'
671 'buf.flush();'
672 'buf.write(sys.stdin.read().encode());'
673 'buf.flush();'
674 'buf.write(b"line4\\n");'
675 'buf.flush();'
676 'buf.write(b"line5\\r\\n");'
677 'buf.flush();'
678 'buf.write(b"line6\\r");'
679 'buf.flush();'
680 'buf.write(b"\\nline7");'
681 'buf.flush();'
682 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200683 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000684 stdout=subprocess.PIPE,
685 universal_newlines=1)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200686 p.stdin.write("line1\n")
687 self.assertEqual(p.stdout.readline(), "line1\n")
688 p.stdin.write("line3\n")
689 p.stdin.close()
Brian Curtin3c6a9512010-11-05 03:58:52 +0000690 self.addCleanup(p.stdout.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200691 self.assertEqual(p.stdout.readline(),
692 "line2\n")
693 self.assertEqual(p.stdout.read(6),
694 "line3\n")
695 self.assertEqual(p.stdout.read(),
696 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000697
698 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000699 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000700 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000701 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200702 'buf = sys.stdout.buffer;'
703 'buf.write(b"line2\\n");'
704 'buf.flush();'
705 'buf.write(b"line4\\n");'
706 'buf.flush();'
707 'buf.write(b"line5\\r\\n");'
708 'buf.flush();'
709 'buf.write(b"line6\\r");'
710 'buf.flush();'
711 'buf.write(b"\\nline7");'
712 'buf.flush();'
713 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200714 stderr=subprocess.PIPE,
715 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000716 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000717 self.addCleanup(p.stdout.close)
718 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000719 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200720 self.assertEqual(stdout,
721 "line2\nline4\nline5\nline6\nline7\nline8")
722
723 def test_universal_newlines_communicate_stdin(self):
724 # universal newlines through communicate(), with only stdin
725 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300726 'import sys,os;' + SETBINARY + textwrap.dedent('''
727 s = sys.stdin.readline()
728 assert s == "line1\\n", repr(s)
729 s = sys.stdin.read()
730 assert s == "line3\\n", repr(s)
731 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200732 stdin=subprocess.PIPE,
733 universal_newlines=1)
734 (stdout, stderr) = p.communicate("line1\nline3\n")
735 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000736
Andrew Svetlovf3765072012-08-14 18:35:17 +0300737 def test_universal_newlines_communicate_input_none(self):
738 # Test communicate(input=None) with universal newlines.
739 #
740 # We set stdout to PIPE because, as of this writing, a different
741 # code path is tested when the number of pipes is zero or one.
742 p = subprocess.Popen([sys.executable, "-c", "pass"],
743 stdin=subprocess.PIPE,
744 stdout=subprocess.PIPE,
745 universal_newlines=True)
746 p.communicate()
747 self.assertEqual(p.returncode, 0)
748
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300749 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300750 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300751 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300752 'import sys,os;' + SETBINARY + textwrap.dedent('''
753 s = sys.stdin.buffer.readline()
754 sys.stdout.buffer.write(s)
755 sys.stdout.buffer.write(b"line2\\r")
756 sys.stderr.buffer.write(b"eline2\\n")
757 s = sys.stdin.buffer.read()
758 sys.stdout.buffer.write(s)
759 sys.stdout.buffer.write(b"line4\\n")
760 sys.stdout.buffer.write(b"line5\\r\\n")
761 sys.stderr.buffer.write(b"eline6\\r")
762 sys.stderr.buffer.write(b"eline7\\r\\nz")
763 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300764 stdin=subprocess.PIPE,
765 stderr=subprocess.PIPE,
766 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300767 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300768 self.addCleanup(p.stdout.close)
769 self.addCleanup(p.stderr.close)
770 (stdout, stderr) = p.communicate("line1\nline3\n")
771 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300772 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300773 # Python debug build push something like "[42442 refs]\n"
774 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300775 # Don't use assertStderrEqual because it strips CR and LF from output.
776 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300777
Andrew Svetlov82860712012-08-19 22:13:41 +0300778 def test_universal_newlines_communicate_encodings(self):
779 # Check that universal newlines mode works for various encodings,
780 # in particular for encodings in the UTF-16 and UTF-32 families.
781 # See issue #15595.
782 #
783 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
784 # without, and UTF-16 and UTF-32.
785 for encoding in ['utf-16', 'utf-32-be']:
786 old_getpreferredencoding = locale.getpreferredencoding
787 # Indirectly via io.TextIOWrapper, Popen() defaults to
788 # locale.getpreferredencoding(False) and earlier in Python 3.2 to
789 # locale.getpreferredencoding().
790 def getpreferredencoding(do_setlocale=True):
791 return encoding
792 code = ("import sys; "
793 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
794 encoding)
795 args = [sys.executable, '-c', code]
796 try:
797 locale.getpreferredencoding = getpreferredencoding
798 # We set stdin to be non-None because, as of this writing,
799 # a different code path is used when the number of pipes is
800 # zero or one.
801 popen = subprocess.Popen(args, universal_newlines=True,
802 stdin=subprocess.PIPE,
803 stdout=subprocess.PIPE)
804 stdout, stderr = popen.communicate(input='')
805 finally:
806 locale.getpreferredencoding = old_getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300807 self.assertEqual(stdout, '1\n2\n3\n4')
808
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000809 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000810 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000811 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000812 max_handles = 1026 # too much for most UNIX systems
813 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000814 max_handles = 2050 # too much for (at least some) Windows setups
815 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400816 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000817 try:
818 for i in range(max_handles):
819 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400820 tmpfile = os.path.join(tmpdir, support.TESTFN)
821 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000822 except OSError as e:
823 if e.errno != errno.EMFILE:
824 raise
825 break
826 else:
827 self.skipTest("failed to reach the file descriptor limit "
828 "(tried %d)" % max_handles)
829 # Close a couple of them (should be enough for a subprocess)
830 for i in range(10):
831 os.close(handles.pop())
832 # Loop creating some subprocesses. If one of them leaks some fds,
833 # the next loop iteration will fail by reaching the max fd limit.
834 for i in range(15):
835 p = subprocess.Popen([sys.executable, "-c",
836 "import sys;"
837 "sys.stdout.write(sys.stdin.read())"],
838 stdin=subprocess.PIPE,
839 stdout=subprocess.PIPE,
840 stderr=subprocess.PIPE)
841 data = p.communicate(b"lime")[0]
842 self.assertEqual(data, b"lime")
843 finally:
844 for h in handles:
845 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400846 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000847
848 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000849 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
850 '"a b c" d e')
851 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
852 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000853 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
854 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000855 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
856 'a\\\\\\b "de fg" h')
857 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
858 'a\\\\\\"b c d')
859 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
860 '"a\\\\b c" d e')
861 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
862 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000863 self.assertEqual(subprocess.list2cmdline(['ab', '']),
864 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000865
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000866 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200867 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +0200868 "import os; os.read(0, 1)"],
869 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200870 self.addCleanup(p.stdin.close)
871 self.assertIsNone(p.poll())
872 os.write(p.stdin.fileno(), b'A')
873 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000874 # Subsequent invocations should just return the returncode
875 self.assertEqual(p.poll(), 0)
876
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000877 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200878 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000879 self.assertEqual(p.wait(), 0)
880 # Subsequent invocations should just return the returncode
881 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000882
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400883 def test_wait_timeout(self):
884 p = subprocess.Popen([sys.executable,
Reid Kleckner93479cc2011-03-14 19:32:41 -0400885 "-c", "import time; time.sleep(0.1)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -0400886 with self.assertRaises(subprocess.TimeoutExpired) as c:
887 p.wait(timeout=0.01)
888 self.assertIn("0.01", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -0400889 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
890 # time to start.
891 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400892
Peter Astrand738131d2004-11-30 21:04:45 +0000893 def test_invalid_bufsize(self):
894 # an invalid type of the bufsize argument should raise
895 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000896 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000897 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000898
Guido van Rossum46a05a72007-06-07 21:56:45 +0000899 def test_bufsize_is_none(self):
900 # bufsize=None should be the same as bufsize=0.
901 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
902 self.assertEqual(p.wait(), 0)
903 # Again with keyword arg
904 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
905 self.assertEqual(p.wait(), 0)
906
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000907 def test_leaking_fds_on_error(self):
908 # see bug #5179: Popen leaks file descriptors to PIPEs if
909 # the child fails to execute; this will eventually exhaust
910 # the maximum number of open fds. 1024 seems a very common
911 # value for that limit, but Windows has 2048, so we loop
912 # 1024 times (each call leaked two fds).
913 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000914 # Windows raises IOError. Others raise OSError.
915 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000916 subprocess.Popen(['nonexisting_i_hope'],
917 stdout=subprocess.PIPE,
918 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400919 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400920 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000921 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000922
Victor Stinnerb3693582010-05-21 20:13:12 +0000923 def test_issue8780(self):
924 # Ensure that stdout is inherited from the parent
925 # if stdout=PIPE is not used
926 code = ';'.join((
927 'import subprocess, sys',
928 'retcode = subprocess.call('
929 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
930 'assert retcode == 0'))
931 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000932 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000933
Tim Goldenaf5ac392010-08-06 13:03:56 +0000934 def test_handles_closed_on_exception(self):
935 # If CreateProcess exits with an error, ensure the
936 # duplicate output handles are released
937 ifhandle, ifname = mkstemp()
938 ofhandle, ofname = mkstemp()
939 efhandle, efname = mkstemp()
940 try:
941 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
942 stderr=efhandle)
943 except OSError:
944 os.close(ifhandle)
945 os.remove(ifname)
946 os.close(ofhandle)
947 os.remove(ofname)
948 os.close(efhandle)
949 os.remove(efname)
950 self.assertFalse(os.path.exists(ifname))
951 self.assertFalse(os.path.exists(ofname))
952 self.assertFalse(os.path.exists(efname))
953
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200954 def test_communicate_epipe(self):
955 # Issue 10963: communicate() should hide EPIPE
956 p = subprocess.Popen([sys.executable, "-c", 'pass'],
957 stdin=subprocess.PIPE,
958 stdout=subprocess.PIPE,
959 stderr=subprocess.PIPE)
960 self.addCleanup(p.stdout.close)
961 self.addCleanup(p.stderr.close)
962 self.addCleanup(p.stdin.close)
963 p.communicate(b"x" * 2**20)
964
965 def test_communicate_epipe_only_stdin(self):
966 # Issue 10963: communicate() should hide EPIPE
967 p = subprocess.Popen([sys.executable, "-c", 'pass'],
968 stdin=subprocess.PIPE)
969 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200970 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200971 p.communicate(b"x" * 2**20)
972
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200973 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
974 "Requires signal.SIGUSR1")
975 @unittest.skipUnless(hasattr(os, 'kill'),
976 "Requires os.kill")
977 @unittest.skipUnless(hasattr(os, 'getppid'),
978 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200979 def test_communicate_eintr(self):
980 # Issue #12493: communicate() should handle EINTR
981 def handler(signum, frame):
982 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200983 old_handler = signal.signal(signal.SIGUSR1, handler)
984 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200985
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200986 args = [sys.executable, "-c",
987 'import os, signal;'
988 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200989 for stream in ('stdout', 'stderr'):
990 kw = {stream: subprocess.PIPE}
991 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200992 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200993 process.communicate()
994
Tim Peterse718f612004-10-12 21:51:32 +0000995
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000996# context manager
997class _SuppressCoreFiles(object):
998 """Try to prevent core files from being created."""
999 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001000
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001001 def __enter__(self):
1002 """Try to save previous ulimit, then set it to (0, 0)."""
Benjamin Peterson964561b2011-12-10 12:31:42 -05001003 if resource is not None:
1004 try:
1005 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
1006 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
1007 except (ValueError, resource.error):
1008 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001009
Ronald Oussoren102d11a2010-07-23 09:50:05 +00001010 if sys.platform == 'darwin':
1011 # Check if the 'Crash Reporter' on OSX was configured
1012 # in 'Developer' mode and warn that it will get triggered
1013 # when it is.
1014 #
1015 # This assumes that this context manager is used in tests
1016 # that might trigger the next manager.
1017 value = subprocess.Popen(['/usr/bin/defaults', 'read',
1018 'com.apple.CrashReporter', 'DialogType'],
1019 stdout=subprocess.PIPE).communicate()[0]
1020 if value.strip() == b'developer':
1021 print("this tests triggers the Crash Reporter, "
1022 "that is intentional", end='')
1023 sys.stdout.flush()
1024
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001025 def __exit__(self, *args):
1026 """Return core file behavior to default."""
1027 if self.old_limit is None:
1028 return
Benjamin Peterson964561b2011-12-10 12:31:42 -05001029 if resource is not None:
1030 try:
1031 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
1032 except (ValueError, resource.error):
1033 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001034
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001035
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001036@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001037class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001038
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001039 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001040 nonexistent_dir = "/_this/pa.th/does/not/exist"
1041 try:
1042 os.chdir(nonexistent_dir)
1043 except OSError as e:
1044 # This avoids hard coding the errno value or the OS perror()
1045 # string and instead capture the exception that we want to see
1046 # below for comparison.
1047 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +00001048 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001049 else:
1050 self.fail("chdir to nonexistant directory %s succeeded." %
1051 nonexistent_dir)
1052
1053 # Error in the child re-raised in the parent.
1054 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001055 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001056 cwd=nonexistent_dir)
1057 except OSError as e:
1058 # Test that the child process chdir failure actually makes
1059 # it up to the parent process as the correct exception.
1060 self.assertEqual(desired_exception.errno, e.errno)
1061 self.assertEqual(desired_exception.strerror, e.strerror)
1062 else:
1063 self.fail("Expected OSError: %s" % desired_exception)
1064
1065 def test_restore_signals(self):
1066 # Code coverage for both values of restore_signals to make sure it
1067 # at least does not blow up.
1068 # A test for behavior would be complex. Contributions welcome.
1069 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1070 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1071
1072 def test_start_new_session(self):
1073 # For code coverage of calling setsid(). We don't care if we get an
1074 # EPERM error from it depending on the test execution environment, that
1075 # still indicates that it was called.
1076 try:
1077 output = subprocess.check_output(
1078 [sys.executable, "-c",
1079 "import os; print(os.getpgid(os.getpid()))"],
1080 start_new_session=True)
1081 except OSError as e:
1082 if e.errno != errno.EPERM:
1083 raise
1084 else:
1085 parent_pgid = os.getpgid(os.getpid())
1086 child_pgid = int(output)
1087 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001088
1089 def test_run_abort(self):
1090 # returncode handles signal termination
1091 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001092 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001093 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001094 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001095 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001096
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001097 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001098 # DISCLAIMER: Setting environment variables is *not* a good use
1099 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001100 p = subprocess.Popen([sys.executable, "-c",
1101 'import sys,os;'
1102 'sys.stdout.write(os.getenv("FRUIT"))'],
1103 stdout=subprocess.PIPE,
1104 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +00001105 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001106 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001107
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001108 def test_preexec_exception(self):
1109 def raise_it():
1110 raise ValueError("What if two swallows carried a coconut?")
1111 try:
1112 p = subprocess.Popen([sys.executable, "-c", ""],
1113 preexec_fn=raise_it)
1114 except RuntimeError as e:
1115 self.assertTrue(
1116 subprocess._posixsubprocess,
1117 "Expected a ValueError from the preexec_fn")
1118 except ValueError as e:
1119 self.assertIn("coconut", e.args[0])
1120 else:
1121 self.fail("Exception raised by preexec_fn did not make it "
1122 "to the parent process.")
1123
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001124 def test_preexec_gc_module_failure(self):
1125 # This tests the code that disables garbage collection if the child
1126 # process will execute any Python.
1127 def raise_runtime_error():
1128 raise RuntimeError("this shouldn't escape")
1129 enabled = gc.isenabled()
1130 orig_gc_disable = gc.disable
1131 orig_gc_isenabled = gc.isenabled
1132 try:
1133 gc.disable()
1134 self.assertFalse(gc.isenabled())
1135 subprocess.call([sys.executable, '-c', ''],
1136 preexec_fn=lambda: None)
1137 self.assertFalse(gc.isenabled(),
1138 "Popen enabled gc when it shouldn't.")
1139
1140 gc.enable()
1141 self.assertTrue(gc.isenabled())
1142 subprocess.call([sys.executable, '-c', ''],
1143 preexec_fn=lambda: None)
1144 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1145
1146 gc.disable = raise_runtime_error
1147 self.assertRaises(RuntimeError, subprocess.Popen,
1148 [sys.executable, '-c', ''],
1149 preexec_fn=lambda: None)
1150
1151 del gc.isenabled # force an AttributeError
1152 self.assertRaises(AttributeError, subprocess.Popen,
1153 [sys.executable, '-c', ''],
1154 preexec_fn=lambda: None)
1155 finally:
1156 gc.disable = orig_gc_disable
1157 gc.isenabled = orig_gc_isenabled
1158 if not enabled:
1159 gc.disable()
1160
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001161 def test_args_string(self):
1162 # args is a string
1163 fd, fname = mkstemp()
1164 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001165 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001166 fobj.write("#!/bin/sh\n")
1167 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1168 sys.executable)
1169 os.chmod(fname, 0o700)
1170 p = subprocess.Popen(fname)
1171 p.wait()
1172 os.remove(fname)
1173 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001174
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001175 def test_invalid_args(self):
1176 # invalid arguments should raise ValueError
1177 self.assertRaises(ValueError, subprocess.call,
1178 [sys.executable, "-c",
1179 "import sys; sys.exit(47)"],
1180 startupinfo=47)
1181 self.assertRaises(ValueError, subprocess.call,
1182 [sys.executable, "-c",
1183 "import sys; sys.exit(47)"],
1184 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001185
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001186 def test_shell_sequence(self):
1187 # Run command through the shell (sequence)
1188 newenv = os.environ.copy()
1189 newenv["FRUIT"] = "apple"
1190 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1191 stdout=subprocess.PIPE,
1192 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001193 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001194 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001195
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001196 def test_shell_string(self):
1197 # Run command through the shell (string)
1198 newenv = os.environ.copy()
1199 newenv["FRUIT"] = "apple"
1200 p = subprocess.Popen("echo $FRUIT", shell=1,
1201 stdout=subprocess.PIPE,
1202 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001203 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001204 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001205
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001206 def test_call_string(self):
1207 # call() function with string argument on UNIX
1208 fd, fname = mkstemp()
1209 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001210 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001211 fobj.write("#!/bin/sh\n")
1212 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1213 sys.executable)
1214 os.chmod(fname, 0o700)
1215 rc = subprocess.call(fname)
1216 os.remove(fname)
1217 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001218
Stefan Krah9542cc62010-07-19 14:20:53 +00001219 def test_specific_shell(self):
1220 # Issue #9265: Incorrect name passed as arg[0].
1221 shells = []
1222 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1223 for name in ['bash', 'ksh']:
1224 sh = os.path.join(prefix, name)
1225 if os.path.isfile(sh):
1226 shells.append(sh)
1227 if not shells: # Will probably work for any shell but csh.
1228 self.skipTest("bash or ksh required for this test")
1229 sh = '/bin/sh'
1230 if os.path.isfile(sh) and not os.path.islink(sh):
1231 # Test will fail if /bin/sh is a symlink to csh.
1232 shells.append(sh)
1233 for sh in shells:
1234 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1235 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001236 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001237 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1238
Florent Xicluna4886d242010-03-08 13:27:26 +00001239 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001240 # Do not inherit file handles from the parent.
1241 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001242 p = subprocess.Popen([sys.executable, "-c", """if 1:
1243 import sys, time
1244 sys.stdout.write('x\\n')
1245 sys.stdout.flush()
1246 time.sleep(30)
1247 """],
1248 close_fds=True,
1249 stdin=subprocess.PIPE,
1250 stdout=subprocess.PIPE,
1251 stderr=subprocess.PIPE)
1252 # Wait for the interpreter to be completely initialized before
1253 # sending any signal.
1254 p.stdout.read(1)
1255 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001256 return p
1257
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001258 def _kill_dead_process(self, method, *args):
1259 # Do not inherit file handles from the parent.
1260 # It should fix failures on some platforms.
1261 p = subprocess.Popen([sys.executable, "-c", """if 1:
1262 import sys, time
1263 sys.stdout.write('x\\n')
1264 sys.stdout.flush()
1265 """],
1266 close_fds=True,
1267 stdin=subprocess.PIPE,
1268 stdout=subprocess.PIPE,
1269 stderr=subprocess.PIPE)
1270 # Wait for the interpreter to be completely initialized before
1271 # sending any signal.
1272 p.stdout.read(1)
1273 # The process should end after this
1274 time.sleep(1)
1275 # This shouldn't raise even though the child is now dead
1276 getattr(p, method)(*args)
1277 p.communicate()
1278
Florent Xicluna4886d242010-03-08 13:27:26 +00001279 def test_send_signal(self):
1280 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001281 _, stderr = p.communicate()
1282 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001283 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001284
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001285 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001286 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001287 _, stderr = p.communicate()
1288 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001289 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001290
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001291 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001292 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001293 _, stderr = p.communicate()
1294 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001295 self.assertEqual(p.wait(), -signal.SIGTERM)
1296
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001297 def test_send_signal_dead(self):
1298 # Sending a signal to a dead process
1299 self._kill_dead_process('send_signal', signal.SIGINT)
1300
1301 def test_kill_dead(self):
1302 # Killing a dead process
1303 self._kill_dead_process('kill')
1304
1305 def test_terminate_dead(self):
1306 # Terminating a dead process
1307 self._kill_dead_process('terminate')
1308
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001309 def check_close_std_fds(self, fds):
1310 # Issue #9905: test that subprocess pipes still work properly with
1311 # some standard fds closed
1312 stdin = 0
1313 newfds = []
1314 for a in fds:
1315 b = os.dup(a)
1316 newfds.append(b)
1317 if a == 0:
1318 stdin = b
1319 try:
1320 for fd in fds:
1321 os.close(fd)
1322 out, err = subprocess.Popen([sys.executable, "-c",
1323 'import sys;'
1324 'sys.stdout.write("apple");'
1325 'sys.stdout.flush();'
1326 'sys.stderr.write("orange")'],
1327 stdin=stdin,
1328 stdout=subprocess.PIPE,
1329 stderr=subprocess.PIPE).communicate()
1330 err = support.strip_python_stderr(err)
1331 self.assertEqual((out, err), (b'apple', b'orange'))
1332 finally:
1333 for b, a in zip(newfds, fds):
1334 os.dup2(b, a)
1335 for b in newfds:
1336 os.close(b)
1337
1338 def test_close_fd_0(self):
1339 self.check_close_std_fds([0])
1340
1341 def test_close_fd_1(self):
1342 self.check_close_std_fds([1])
1343
1344 def test_close_fd_2(self):
1345 self.check_close_std_fds([2])
1346
1347 def test_close_fds_0_1(self):
1348 self.check_close_std_fds([0, 1])
1349
1350 def test_close_fds_0_2(self):
1351 self.check_close_std_fds([0, 2])
1352
1353 def test_close_fds_1_2(self):
1354 self.check_close_std_fds([1, 2])
1355
1356 def test_close_fds_0_1_2(self):
1357 # Issue #10806: test that subprocess pipes still work properly with
1358 # all standard fds closed.
1359 self.check_close_std_fds([0, 1, 2])
1360
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001361 def test_remapping_std_fds(self):
1362 # open up some temporary files
1363 temps = [mkstemp() for i in range(3)]
1364 try:
1365 temp_fds = [fd for fd, fname in temps]
1366
1367 # unlink the files -- we won't need to reopen them
1368 for fd, fname in temps:
1369 os.unlink(fname)
1370
1371 # write some data to what will become stdin, and rewind
1372 os.write(temp_fds[1], b"STDIN")
1373 os.lseek(temp_fds[1], 0, 0)
1374
1375 # move the standard file descriptors out of the way
1376 saved_fds = [os.dup(fd) for fd in range(3)]
1377 try:
1378 # duplicate the file objects over the standard fd's
1379 for fd, temp_fd in enumerate(temp_fds):
1380 os.dup2(temp_fd, fd)
1381
1382 # now use those files in the "wrong" order, so that subprocess
1383 # has to rearrange them in the child
1384 p = subprocess.Popen([sys.executable, "-c",
1385 'import sys; got = sys.stdin.read();'
1386 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1387 stdin=temp_fds[1],
1388 stdout=temp_fds[2],
1389 stderr=temp_fds[0])
1390 p.wait()
1391 finally:
1392 # restore the original fd's underneath sys.stdin, etc.
1393 for std, saved in enumerate(saved_fds):
1394 os.dup2(saved, std)
1395 os.close(saved)
1396
1397 for fd in temp_fds:
1398 os.lseek(fd, 0, 0)
1399
1400 out = os.read(temp_fds[2], 1024)
1401 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1402 self.assertEqual(out, b"got STDIN")
1403 self.assertEqual(err, b"err")
1404
1405 finally:
1406 for fd in temp_fds:
1407 os.close(fd)
1408
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001409 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1410 # open up some temporary files
1411 temps = [mkstemp() for i in range(3)]
1412 temp_fds = [fd for fd, fname in temps]
1413 try:
1414 # unlink the files -- we won't need to reopen them
1415 for fd, fname in temps:
1416 os.unlink(fname)
1417
1418 # save a copy of the standard file descriptors
1419 saved_fds = [os.dup(fd) for fd in range(3)]
1420 try:
1421 # duplicate the temp files over the standard fd's 0, 1, 2
1422 for fd, temp_fd in enumerate(temp_fds):
1423 os.dup2(temp_fd, fd)
1424
1425 # write some data to what will become stdin, and rewind
1426 os.write(stdin_no, b"STDIN")
1427 os.lseek(stdin_no, 0, 0)
1428
1429 # now use those files in the given order, so that subprocess
1430 # has to rearrange them in the child
1431 p = subprocess.Popen([sys.executable, "-c",
1432 'import sys; got = sys.stdin.read();'
1433 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1434 stdin=stdin_no,
1435 stdout=stdout_no,
1436 stderr=stderr_no)
1437 p.wait()
1438
1439 for fd in temp_fds:
1440 os.lseek(fd, 0, 0)
1441
1442 out = os.read(stdout_no, 1024)
1443 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1444 finally:
1445 for std, saved in enumerate(saved_fds):
1446 os.dup2(saved, std)
1447 os.close(saved)
1448
1449 self.assertEqual(out, b"got STDIN")
1450 self.assertEqual(err, b"err")
1451
1452 finally:
1453 for fd in temp_fds:
1454 os.close(fd)
1455
1456 # When duping fds, if there arises a situation where one of the fds is
1457 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1458 # This tests all combinations of this.
1459 def test_swap_fds(self):
1460 self.check_swap_fds(0, 1, 2)
1461 self.check_swap_fds(0, 2, 1)
1462 self.check_swap_fds(1, 0, 2)
1463 self.check_swap_fds(1, 2, 0)
1464 self.check_swap_fds(2, 0, 1)
1465 self.check_swap_fds(2, 1, 0)
1466
Victor Stinner13bb71c2010-04-23 21:41:56 +00001467 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001468 def prepare():
1469 raise ValueError("surrogate:\uDCff")
1470
1471 try:
1472 subprocess.call(
1473 [sys.executable, "-c", "pass"],
1474 preexec_fn=prepare)
1475 except ValueError as err:
1476 # Pure Python implementations keeps the message
1477 self.assertIsNone(subprocess._posixsubprocess)
1478 self.assertEqual(str(err), "surrogate:\uDCff")
1479 except RuntimeError as err:
1480 # _posixsubprocess uses a default message
1481 self.assertIsNotNone(subprocess._posixsubprocess)
1482 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1483 else:
1484 self.fail("Expected ValueError or RuntimeError")
1485
Victor Stinner13bb71c2010-04-23 21:41:56 +00001486 def test_undecodable_env(self):
1487 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001488 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001489 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001490 env = os.environ.copy()
1491 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001492 # Use C locale to get ascii for the locale encoding to force
1493 # surrogate-escaping of \xFF in the child process; otherwise it can
1494 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001495 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001496 stdout = subprocess.check_output(
1497 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001498 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001499 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001500 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001501
1502 # test bytes
1503 key = key.encode("ascii", "surrogateescape")
1504 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001505 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001506 env = os.environ.copy()
1507 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001508 stdout = subprocess.check_output(
1509 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001510 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001511 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001512 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001513
Victor Stinnerb745a742010-05-18 17:17:23 +00001514 def test_bytes_program(self):
1515 abs_program = os.fsencode(sys.executable)
1516 path, program = os.path.split(sys.executable)
1517 program = os.fsencode(program)
1518
1519 # absolute bytes path
1520 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001521 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001522
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001523 # absolute bytes path as a string
1524 cmd = b"'" + abs_program + b"' -c pass"
1525 exitcode = subprocess.call(cmd, shell=True)
1526 self.assertEqual(exitcode, 0)
1527
Victor Stinnerb745a742010-05-18 17:17:23 +00001528 # bytes program, unicode PATH
1529 env = os.environ.copy()
1530 env["PATH"] = path
1531 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001532 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001533
1534 # bytes program, bytes PATH
1535 envb = os.environb.copy()
1536 envb[b"PATH"] = os.fsencode(path)
1537 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001538 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001539
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001540 def test_pipe_cloexec(self):
1541 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1542 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1543
1544 p1 = subprocess.Popen([sys.executable, sleeper],
1545 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1546 stderr=subprocess.PIPE, close_fds=False)
1547
1548 self.addCleanup(p1.communicate, b'')
1549
1550 p2 = subprocess.Popen([sys.executable, fd_status],
1551 stdout=subprocess.PIPE, close_fds=False)
1552
1553 output, error = p2.communicate()
1554 result_fds = set(map(int, output.split(b',')))
1555 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1556 p1.stderr.fileno()])
1557
1558 self.assertFalse(result_fds & unwanted_fds,
1559 "Expected no fds from %r to be open in child, "
1560 "found %r" %
1561 (unwanted_fds, result_fds & unwanted_fds))
1562
1563 def test_pipe_cloexec_real_tools(self):
1564 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1565 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1566
1567 subdata = b'zxcvbn'
1568 data = subdata * 4 + b'\n'
1569
1570 p1 = subprocess.Popen([sys.executable, qcat],
1571 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1572 close_fds=False)
1573
1574 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1575 stdin=p1.stdout, stdout=subprocess.PIPE,
1576 close_fds=False)
1577
1578 self.addCleanup(p1.wait)
1579 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001580 def kill_p1():
1581 try:
1582 p1.terminate()
1583 except ProcessLookupError:
1584 pass
1585 def kill_p2():
1586 try:
1587 p2.terminate()
1588 except ProcessLookupError:
1589 pass
1590 self.addCleanup(kill_p1)
1591 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001592
1593 p1.stdin.write(data)
1594 p1.stdin.close()
1595
1596 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1597
1598 self.assertTrue(readfiles, "The child hung")
1599 self.assertEqual(p2.stdout.read(), data)
1600
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001601 p1.stdout.close()
1602 p2.stdout.close()
1603
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001604 def test_close_fds(self):
1605 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1606
1607 fds = os.pipe()
1608 self.addCleanup(os.close, fds[0])
1609 self.addCleanup(os.close, fds[1])
1610
1611 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001612 # add a bunch more fds
1613 for _ in range(9):
1614 fd = os.open("/dev/null", os.O_RDONLY)
1615 self.addCleanup(os.close, fd)
1616 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001617
1618 p = subprocess.Popen([sys.executable, fd_status],
1619 stdout=subprocess.PIPE, close_fds=False)
1620 output, ignored = p.communicate()
1621 remaining_fds = set(map(int, output.split(b',')))
1622
1623 self.assertEqual(remaining_fds & open_fds, open_fds,
1624 "Some fds were closed")
1625
1626 p = subprocess.Popen([sys.executable, fd_status],
1627 stdout=subprocess.PIPE, close_fds=True)
1628 output, ignored = p.communicate()
1629 remaining_fds = set(map(int, output.split(b',')))
1630
1631 self.assertFalse(remaining_fds & open_fds,
1632 "Some fds were left open")
1633 self.assertIn(1, remaining_fds, "Subprocess failed")
1634
Gregory P. Smith8facece2012-01-21 14:01:08 -08001635 # Keep some of the fd's we opened open in the subprocess.
1636 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1637 fds_to_keep = set(open_fds.pop() for _ in range(8))
1638 p = subprocess.Popen([sys.executable, fd_status],
1639 stdout=subprocess.PIPE, close_fds=True,
1640 pass_fds=())
1641 output, ignored = p.communicate()
1642 remaining_fds = set(map(int, output.split(b',')))
1643
1644 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1645 "Some fds not in pass_fds were left open")
1646 self.assertIn(1, remaining_fds, "Subprocess failed")
1647
Victor Stinner88701e22011-06-01 13:13:04 +02001648 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1649 # descriptor of a pipe closed in the parent process is valid in the
1650 # child process according to fstat(), but the mode of the file
1651 # descriptor is invalid, and read or write raise an error.
1652 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001653 def test_pass_fds(self):
1654 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1655
1656 open_fds = set()
1657
1658 for x in range(5):
1659 fds = os.pipe()
1660 self.addCleanup(os.close, fds[0])
1661 self.addCleanup(os.close, fds[1])
1662 open_fds.update(fds)
1663
1664 for fd in open_fds:
1665 p = subprocess.Popen([sys.executable, fd_status],
1666 stdout=subprocess.PIPE, close_fds=True,
1667 pass_fds=(fd, ))
1668 output, ignored = p.communicate()
1669
1670 remaining_fds = set(map(int, output.split(b',')))
1671 to_be_closed = open_fds - {fd}
1672
1673 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1674 self.assertFalse(remaining_fds & to_be_closed,
1675 "fd to be closed passed")
1676
1677 # pass_fds overrides close_fds with a warning.
1678 with self.assertWarns(RuntimeWarning) as context:
1679 self.assertFalse(subprocess.call(
1680 [sys.executable, "-c", "import sys; sys.exit(0)"],
1681 close_fds=False, pass_fds=(fd, )))
1682 self.assertIn('overriding close_fds', str(context.warning))
1683
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001684 def test_stdout_stdin_are_single_inout_fd(self):
1685 with io.open(os.devnull, "r+") as inout:
1686 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1687 stdout=inout, stdin=inout)
1688 p.wait()
1689
1690 def test_stdout_stderr_are_single_inout_fd(self):
1691 with io.open(os.devnull, "r+") as inout:
1692 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1693 stdout=inout, stderr=inout)
1694 p.wait()
1695
1696 def test_stderr_stdin_are_single_inout_fd(self):
1697 with io.open(os.devnull, "r+") as inout:
1698 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1699 stderr=inout, stdin=inout)
1700 p.wait()
1701
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001702 def test_wait_when_sigchild_ignored(self):
1703 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1704 sigchild_ignore = support.findfile("sigchild_ignore.py",
1705 subdir="subprocessdata")
1706 p = subprocess.Popen([sys.executable, sigchild_ignore],
1707 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1708 stdout, stderr = p.communicate()
1709 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001710 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001711 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001712
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001713 def test_select_unbuffered(self):
1714 # Issue #11459: bufsize=0 should really set the pipes as
1715 # unbuffered (and therefore let select() work properly).
1716 select = support.import_module("select")
1717 p = subprocess.Popen([sys.executable, "-c",
1718 'import sys;'
1719 'sys.stdout.write("apple")'],
1720 stdout=subprocess.PIPE,
1721 bufsize=0)
1722 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001723 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001724 try:
1725 self.assertEqual(f.read(4), b"appl")
1726 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1727 finally:
1728 p.wait()
1729
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001730 def test_zombie_fast_process_del(self):
1731 # Issue #12650: on Unix, if Popen.__del__() was called before the
1732 # process exited, it wouldn't be added to subprocess._active, and would
1733 # remain a zombie.
1734 # spawn a Popen, and delete its reference before it exits
1735 p = subprocess.Popen([sys.executable, "-c",
1736 'import sys, time;'
1737 'time.sleep(0.2)'],
1738 stdout=subprocess.PIPE,
1739 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001740 self.addCleanup(p.stdout.close)
1741 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001742 ident = id(p)
1743 pid = p.pid
1744 del p
1745 # check that p is in the active processes list
1746 self.assertIn(ident, [id(o) for o in subprocess._active])
1747
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001748 def test_leak_fast_process_del_killed(self):
1749 # Issue #12650: on Unix, if Popen.__del__() was called before the
1750 # process exited, and the process got killed by a signal, it would never
1751 # be removed from subprocess._active, which triggered a FD and memory
1752 # leak.
1753 # spawn a Popen, delete its reference and kill it
1754 p = subprocess.Popen([sys.executable, "-c",
1755 'import time;'
1756 'time.sleep(3)'],
1757 stdout=subprocess.PIPE,
1758 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001759 self.addCleanup(p.stdout.close)
1760 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001761 ident = id(p)
1762 pid = p.pid
1763 del p
1764 os.kill(pid, signal.SIGKILL)
1765 # check that p is in the active processes list
1766 self.assertIn(ident, [id(o) for o in subprocess._active])
1767
1768 # let some time for the process to exit, and create a new Popen: this
1769 # should trigger the wait() of p
1770 time.sleep(0.2)
1771 with self.assertRaises(EnvironmentError) as c:
1772 with subprocess.Popen(['nonexisting_i_hope'],
1773 stdout=subprocess.PIPE,
1774 stderr=subprocess.PIPE) as proc:
1775 pass
1776 # p should have been wait()ed on, and removed from the _active list
1777 self.assertRaises(OSError, os.waitpid, pid, 0)
1778 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1779
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001780
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001781@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001782class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001783
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001784 def test_startupinfo(self):
1785 # startupinfo argument
1786 # We uses hardcoded constants, because we do not want to
1787 # depend on win32all.
1788 STARTF_USESHOWWINDOW = 1
1789 SW_MAXIMIZE = 3
1790 startupinfo = subprocess.STARTUPINFO()
1791 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1792 startupinfo.wShowWindow = SW_MAXIMIZE
1793 # Since Python is a console process, it won't be affected
1794 # by wShowWindow, but the argument should be silently
1795 # ignored
1796 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001797 startupinfo=startupinfo)
1798
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001799 def test_creationflags(self):
1800 # creationflags argument
1801 CREATE_NEW_CONSOLE = 16
1802 sys.stderr.write(" a DOS box should flash briefly ...\n")
1803 subprocess.call(sys.executable +
1804 ' -c "import time; time.sleep(0.25)"',
1805 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001806
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001807 def test_invalid_args(self):
1808 # invalid arguments should raise ValueError
1809 self.assertRaises(ValueError, subprocess.call,
1810 [sys.executable, "-c",
1811 "import sys; sys.exit(47)"],
1812 preexec_fn=lambda: 1)
1813 self.assertRaises(ValueError, subprocess.call,
1814 [sys.executable, "-c",
1815 "import sys; sys.exit(47)"],
1816 stdout=subprocess.PIPE,
1817 close_fds=True)
1818
1819 def test_close_fds(self):
1820 # close file descriptors
1821 rc = subprocess.call([sys.executable, "-c",
1822 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001823 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001824 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001825
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001826 def test_shell_sequence(self):
1827 # Run command through the shell (sequence)
1828 newenv = os.environ.copy()
1829 newenv["FRUIT"] = "physalis"
1830 p = subprocess.Popen(["set"], shell=1,
1831 stdout=subprocess.PIPE,
1832 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001833 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001834 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001835
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001836 def test_shell_string(self):
1837 # Run command through the shell (string)
1838 newenv = os.environ.copy()
1839 newenv["FRUIT"] = "physalis"
1840 p = subprocess.Popen("set", shell=1,
1841 stdout=subprocess.PIPE,
1842 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001843 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001844 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001845
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001846 def test_call_string(self):
1847 # call() function with string argument on Windows
1848 rc = subprocess.call(sys.executable +
1849 ' -c "import sys; sys.exit(47)"')
1850 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001851
Florent Xicluna4886d242010-03-08 13:27:26 +00001852 def _kill_process(self, method, *args):
1853 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001854 p = subprocess.Popen([sys.executable, "-c", """if 1:
1855 import sys, time
1856 sys.stdout.write('x\\n')
1857 sys.stdout.flush()
1858 time.sleep(30)
1859 """],
1860 stdin=subprocess.PIPE,
1861 stdout=subprocess.PIPE,
1862 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001863 self.addCleanup(p.stdout.close)
1864 self.addCleanup(p.stderr.close)
1865 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001866 # Wait for the interpreter to be completely initialized before
1867 # sending any signal.
1868 p.stdout.read(1)
1869 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001870 _, stderr = p.communicate()
1871 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001872 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001873 self.assertNotEqual(returncode, 0)
1874
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001875 def _kill_dead_process(self, method, *args):
1876 p = subprocess.Popen([sys.executable, "-c", """if 1:
1877 import sys, time
1878 sys.stdout.write('x\\n')
1879 sys.stdout.flush()
1880 sys.exit(42)
1881 """],
1882 stdin=subprocess.PIPE,
1883 stdout=subprocess.PIPE,
1884 stderr=subprocess.PIPE)
1885 self.addCleanup(p.stdout.close)
1886 self.addCleanup(p.stderr.close)
1887 self.addCleanup(p.stdin.close)
1888 # Wait for the interpreter to be completely initialized before
1889 # sending any signal.
1890 p.stdout.read(1)
1891 # The process should end after this
1892 time.sleep(1)
1893 # This shouldn't raise even though the child is now dead
1894 getattr(p, method)(*args)
1895 _, stderr = p.communicate()
1896 self.assertStderrEqual(stderr, b'')
1897 rc = p.wait()
1898 self.assertEqual(rc, 42)
1899
Florent Xicluna4886d242010-03-08 13:27:26 +00001900 def test_send_signal(self):
1901 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001902
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001903 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001904 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001905
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001906 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001907 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001908
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001909 def test_send_signal_dead(self):
1910 self._kill_dead_process('send_signal', signal.SIGTERM)
1911
1912 def test_kill_dead(self):
1913 self._kill_dead_process('kill')
1914
1915 def test_terminate_dead(self):
1916 self._kill_dead_process('terminate')
1917
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001918
Brett Cannona23810f2008-05-26 19:04:21 +00001919# The module says:
1920# "NB This only works (and is only relevant) for UNIX."
1921#
1922# Actually, getoutput should work on any platform with an os.popen, but
1923# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001924@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001925class CommandTests(unittest.TestCase):
1926 def test_getoutput(self):
1927 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1928 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1929 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001930
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001931 # we use mkdtemp in the next line to create an empty directory
1932 # under our exclusive control; from that, we can invent a pathname
1933 # that we _know_ won't exist. This is guaranteed to fail.
1934 dir = None
1935 try:
1936 dir = tempfile.mkdtemp()
1937 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001938
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001939 status, output = subprocess.getstatusoutput('cat ' + name)
1940 self.assertNotEqual(status, 0)
1941 finally:
1942 if dir is not None:
1943 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001944
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001945
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001946@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1947 "poll system call not supported")
1948class ProcessTestCaseNoPoll(ProcessTestCase):
1949 def setUp(self):
1950 subprocess._has_poll = False
1951 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001952
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001953 def tearDown(self):
1954 subprocess._has_poll = True
1955 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001956
1957
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001958class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001959 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001960 def test_eintr_retry_call(self):
1961 record_calls = []
1962 def fake_os_func(*args):
1963 record_calls.append(args)
1964 if len(record_calls) == 2:
1965 raise OSError(errno.EINTR, "fake interrupted system call")
1966 return tuple(reversed(args))
1967
1968 self.assertEqual((999, 256),
1969 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1970 self.assertEqual([(256, 999)], record_calls)
1971 # This time there will be an EINTR so it will loop once.
1972 self.assertEqual((666,),
1973 subprocess._eintr_retry_call(fake_os_func, 666))
1974 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1975
1976
Tim Golden126c2962010-08-11 14:20:40 +00001977@unittest.skipUnless(mswindows, "Windows-specific tests")
1978class CommandsWithSpaces (BaseTestCase):
1979
1980 def setUp(self):
1981 super().setUp()
1982 f, fname = mkstemp(".py", "te st")
1983 self.fname = fname.lower ()
1984 os.write(f, b"import sys;"
1985 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1986 )
1987 os.close(f)
1988
1989 def tearDown(self):
1990 os.remove(self.fname)
1991 super().tearDown()
1992
1993 def with_spaces(self, *args, **kwargs):
1994 kwargs['stdout'] = subprocess.PIPE
1995 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001996 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001997 self.assertEqual(
1998 p.stdout.read ().decode("mbcs"),
1999 "2 [%r, 'ab cd']" % self.fname
2000 )
2001
2002 def test_shell_string_with_spaces(self):
2003 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002004 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2005 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002006
2007 def test_shell_sequence_with_spaces(self):
2008 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002009 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002010
2011 def test_noshell_string_with_spaces(self):
2012 # call() function with string argument with spaces on Windows
2013 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2014 "ab cd"))
2015
2016 def test_noshell_sequence_with_spaces(self):
2017 # call() function with sequence argument with spaces on Windows
2018 self.with_spaces([sys.executable, self.fname, "ab cd"])
2019
Brian Curtin79cdb662010-12-03 02:46:02 +00002020
Georg Brandla86b2622012-02-20 21:34:57 +01002021class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00002022
2023 def test_pipe(self):
2024 with subprocess.Popen([sys.executable, "-c",
2025 "import sys;"
2026 "sys.stdout.write('stdout');"
2027 "sys.stderr.write('stderr');"],
2028 stdout=subprocess.PIPE,
2029 stderr=subprocess.PIPE) as proc:
2030 self.assertEqual(proc.stdout.read(), b"stdout")
2031 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2032
2033 self.assertTrue(proc.stdout.closed)
2034 self.assertTrue(proc.stderr.closed)
2035
2036 def test_returncode(self):
2037 with subprocess.Popen([sys.executable, "-c",
2038 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002039 pass
2040 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002041 self.assertEqual(proc.returncode, 100)
2042
2043 def test_communicate_stdin(self):
2044 with subprocess.Popen([sys.executable, "-c",
2045 "import sys;"
2046 "sys.exit(sys.stdin.read() == 'context')"],
2047 stdin=subprocess.PIPE) as proc:
2048 proc.communicate(b"context")
2049 self.assertEqual(proc.returncode, 1)
2050
2051 def test_invalid_args(self):
2052 with self.assertRaises(EnvironmentError) as c:
2053 with subprocess.Popen(['nonexisting_i_hope'],
2054 stdout=subprocess.PIPE,
2055 stderr=subprocess.PIPE) as proc:
2056 pass
2057
2058 if c.exception.errno != errno.ENOENT: # ignore "no such file"
2059 raise c.exception
2060
2061
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002062def test_main():
2063 unit_tests = (ProcessTestCase,
2064 POSIXProcessTestCase,
2065 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002066 CommandTests,
2067 ProcessTestCaseNoPoll,
2068 HelperFunctionTests,
2069 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02002070 ContextManagerTests,
2071 )
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002072
2073 support.run_unittest(*unit_tests)
2074 support.reap_children()
2075
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002076if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002077 unittest.main()