blob: b260c810fba2e4b76b146fb0d35559e6cf9525fa [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
Chris Jerdonekec3ea942012-09-30 00:10:28 -07002from test import script_helper
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003from test import support
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00004import subprocess
5import sys
6import signal
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04007import io
Andrew Svetlov82860712012-08-19 22:13:41 +03008import locale
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00009import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +000010import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000011import tempfile
12import time
Tim Peters3761e8d2004-10-13 04:07:12 +000013import re
Ezio Melotti184bdfb2010-02-18 09:37:05 +000014import sysconfig
Gregory P. Smithd23047b2010-12-04 09:10:44 +000015import warnings
Gregory P. Smith51ee2702010-12-13 07:59:39 +000016import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040017import shutil
Benjamin Petersonb870aa12011-12-10 12:44:25 -050018import gc
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030019import textwrap
Benjamin Peterson964561b2011-12-10 12:31:42 -050020
21try:
22 import resource
23except ImportError:
24 resource = None
25
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000026mswindows = (sys.platform == "win32")
27
28#
29# Depends on the following external programs: Python
30#
31
32if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000033 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
34 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000035else:
36 SETBINARY = ''
37
Florent Xiclunab1e94e82010-02-27 22:12:37 +000038
39try:
40 mkstemp = tempfile.mkstemp
41except AttributeError:
42 # tempfile.mkstemp is not available
43 def mkstemp():
44 """Replacement for mkstemp, calling mktemp."""
45 fname = tempfile.mktemp()
46 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
47
Tim Peters3761e8d2004-10-13 04:07:12 +000048
Florent Xiclunac049d872010-03-27 22:47:23 +000049class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000050 def setUp(self):
51 # Try to minimize the number of children we have so this test
52 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000053 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000054
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000055 def tearDown(self):
56 for inst in subprocess._active:
57 inst.wait()
58 subprocess._cleanup()
59 self.assertFalse(subprocess._active, "subprocess._active not empty")
60
Florent Xiclunab1e94e82010-02-27 22:12:37 +000061 def assertStderrEqual(self, stderr, expected, msg=None):
62 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
63 # shutdown time. That frustrates tests trying to check stderr produced
64 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000065 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040066 # strip_python_stderr also strips whitespace, so we do too.
67 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000068 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000069
Florent Xiclunac049d872010-03-27 22:47:23 +000070
71class ProcessTestCase(BaseTestCase):
72
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000073 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000074 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000075 rc = subprocess.call([sys.executable, "-c",
76 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000077 self.assertEqual(rc, 47)
78
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040079 def test_call_timeout(self):
80 # call() function with timeout argument; we want to test that the child
81 # process gets killed when the timeout expires. If the child isn't
82 # killed, this call will deadlock since subprocess.call waits for the
83 # child.
84 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
85 [sys.executable, "-c", "while True: pass"],
86 timeout=0.1)
87
Peter Astrand454f7672005-01-01 09:36:35 +000088 def test_check_call_zero(self):
89 # check_call() function with zero return code
90 rc = subprocess.check_call([sys.executable, "-c",
91 "import sys; sys.exit(0)"])
92 self.assertEqual(rc, 0)
93
94 def test_check_call_nonzero(self):
95 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000096 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +000097 subprocess.check_call([sys.executable, "-c",
98 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000099 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000100
Georg Brandlf9734072008-12-07 15:30:06 +0000101 def test_check_output(self):
102 # check_output() function with zero return code
103 output = subprocess.check_output(
104 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000105 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000106
107 def test_check_output_nonzero(self):
108 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000109 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000110 subprocess.check_output(
111 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000112 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000113
114 def test_check_output_stderr(self):
115 # check_output() function stderr redirected to stdout
116 output = subprocess.check_output(
117 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
118 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000119 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000120
121 def test_check_output_stdout_arg(self):
122 # check_output() function stderr redirected to stdout
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000123 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000124 output = subprocess.check_output(
125 [sys.executable, "-c", "print('will not be run')"],
126 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000127 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000128 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000129
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400130 def test_check_output_timeout(self):
131 # check_output() function with timeout arg
132 with self.assertRaises(subprocess.TimeoutExpired) as c:
133 output = subprocess.check_output(
134 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200135 "import sys, time\n"
136 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400137 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200138 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400139 # Some heavily loaded buildbots (sparc Debian 3.x) require
140 # this much time to start and print.
141 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400142 self.fail("Expected TimeoutExpired.")
143 self.assertEqual(c.exception.output, b'BDFL')
144
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000145 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000146 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000147 newenv = os.environ.copy()
148 newenv["FRUIT"] = "banana"
149 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000150 'import sys, os;'
151 'sys.exit(os.getenv("FRUIT")=="banana")'],
152 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000153 self.assertEqual(rc, 1)
154
Victor Stinner87b9bc32011-06-01 00:57:47 +0200155 def test_invalid_args(self):
156 # Popen() called with invalid arguments should raise TypeError
157 # but Popen.__del__ should not complain (issue #12085)
158 with support.captured_stderr() as s:
159 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
160 argcount = subprocess.Popen.__init__.__code__.co_argcount
161 too_many_args = [0] * (argcount + 1)
162 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
163 self.assertEqual(s.getvalue(), '')
164
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000165 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000166 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000167 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000168 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000169 self.addCleanup(p.stdout.close)
170 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000171 p.wait()
172 self.assertEqual(p.stdin, None)
173
174 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000175 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000176 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000177 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000178 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000179 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000180 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000181 self.addCleanup(p.stdin.close)
182 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000183 p.wait()
184 self.assertEqual(p.stdout, None)
185
186 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000187 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000188 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000189 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000190 self.addCleanup(p.stdout.close)
191 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000192 p.wait()
193 self.assertEqual(p.stderr, None)
194
Chris Jerdonek776cb192012-10-08 15:56:43 -0700195 def _assert_python(self, pre_args, **kwargs):
196 # We include sys.exit() to prevent the test runner from hanging
197 # whenever python is found.
198 args = pre_args + ["import sys; sys.exit(47)"]
199 p = subprocess.Popen(args, **kwargs)
200 p.wait()
201 self.assertEqual(47, p.returncode)
202
203 def test_executable(self):
204 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700205 #
206 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
207 # determine where its standard library is, so we need the directory
208 # of args[0] to be valid for the Popen() call to Python to succeed.
209 # See also issue #16170 and issue #7774.
210 doesnotexist = os.path.join(os.path.dirname(sys.executable),
211 "doesnotexist")
212 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700213
214 def test_executable_takes_precedence(self):
215 # Check that the executable argument takes precedence over args[0].
216 #
217 # Verify first that the call succeeds without the executable arg.
218 pre_args = [sys.executable, "-c"]
219 self._assert_python(pre_args)
220 self.assertRaises(FileNotFoundError, self._assert_python, pre_args,
221 executable="doesnotexist")
222
223 @unittest.skipIf(mswindows, "executable argument replaces shell")
224 def test_executable_replaces_shell(self):
225 # Check that the executable argument replaces the default shell
226 # when shell=True.
227 self._assert_python([], executable=sys.executable, shell=True)
228
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700229 # For use in the test_cwd* tests below.
230 def _normalize_cwd(self, cwd):
231 # Normalize an expected cwd (for Tru64 support).
232 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
233 # strings. See bug #1063571.
234 original_cwd = os.getcwd()
235 os.chdir(cwd)
236 cwd = os.getcwd()
237 os.chdir(original_cwd)
238 return cwd
239
240 # For use in the test_cwd* tests below.
241 def _split_python_path(self):
242 # Return normalized (python_dir, python_base).
243 python_path = os.path.realpath(sys.executable)
244 return os.path.split(python_path)
245
246 # For use in the test_cwd* tests below.
247 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
248 # Invoke Python via Popen, and assert that (1) the call succeeds,
249 # and that (2) the current working directory of the child process
250 # matches *expected_cwd*.
251 p = subprocess.Popen([python_arg, "-c",
252 "import os, sys; "
253 "sys.stdout.write(os.getcwd()); "
254 "sys.exit(47)"],
255 stdout=subprocess.PIPE,
256 **kwargs)
257 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000258 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700259 self.assertEqual(47, p.returncode)
260 normcase = os.path.normcase
261 self.assertEqual(normcase(expected_cwd),
262 normcase(p.stdout.read().decode("utf-8")))
263
264 def test_cwd(self):
265 # Check that cwd changes the cwd for the child process.
266 temp_dir = tempfile.gettempdir()
267 temp_dir = self._normalize_cwd(temp_dir)
268 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
269
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700270 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700271 def test_cwd_with_relative_arg(self):
272 # Check that Popen looks for args[0] relative to cwd if args[0]
273 # is relative.
274 python_dir, python_base = self._split_python_path()
275 rel_python = os.path.join(os.curdir, python_base)
276 with support.temp_cwd() as wrong_dir:
277 # Before calling with the correct cwd, confirm that the call fails
278 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700279 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700280 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700281 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700282 [rel_python], cwd=wrong_dir)
283 python_dir = self._normalize_cwd(python_dir)
284 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
285
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700286 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700287 def test_cwd_with_relative_executable(self):
288 # Check that Popen looks for executable relative to cwd if executable
289 # is relative (and that executable takes precedence over args[0]).
290 python_dir, python_base = self._split_python_path()
291 rel_python = os.path.join(os.curdir, python_base)
292 doesntexist = "somethingyoudonthave"
293 with support.temp_cwd() as wrong_dir:
294 # Before calling with the correct cwd, confirm that the call fails
295 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700296 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700297 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700298 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700299 [doesntexist], executable=rel_python,
300 cwd=wrong_dir)
301 python_dir = self._normalize_cwd(python_dir)
302 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
303 cwd=python_dir)
304
305 def test_cwd_with_absolute_arg(self):
306 # Check that Popen can find the executable when the cwd is wrong
307 # if args[0] is an absolute path.
308 python_dir, python_base = self._split_python_path()
309 abs_python = os.path.join(python_dir, python_base)
310 rel_python = os.path.join(os.curdir, python_base)
311 with script_helper.temp_dir() as wrong_dir:
312 # Before calling with an absolute path, confirm that using a
313 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700314 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700315 [rel_python], cwd=wrong_dir)
316 wrong_dir = self._normalize_cwd(wrong_dir)
317 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
318
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100319 @unittest.skipIf(sys.base_prefix != sys.prefix,
320 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000321 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700322 python_dir, python_base = self._split_python_path()
323 python_dir = self._normalize_cwd(python_dir)
324 self._assert_cwd(python_dir, "somethingyoudonthave",
325 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000326
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100327 @unittest.skipIf(sys.base_prefix != sys.prefix,
328 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000329 @unittest.skipIf(sysconfig.is_python_build(),
330 "need an installed Python. See #7774")
331 def test_executable_without_cwd(self):
332 # For a normal installation, it should work without 'cwd'
333 # argument. For test runs in the build directory, see #7774.
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700334 self._assert_cwd('', "somethingyoudonthave", executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000335
336 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000337 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000338 p = subprocess.Popen([sys.executable, "-c",
339 'import sys; sys.exit(sys.stdin.read() == "pear")'],
340 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000341 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000342 p.stdin.close()
343 p.wait()
344 self.assertEqual(p.returncode, 1)
345
346 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000347 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000348 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000349 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000350 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000351 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000352 os.lseek(d, 0, 0)
353 p = subprocess.Popen([sys.executable, "-c",
354 'import sys; sys.exit(sys.stdin.read() == "pear")'],
355 stdin=d)
356 p.wait()
357 self.assertEqual(p.returncode, 1)
358
359 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000360 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000361 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000362 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000363 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000364 tf.seek(0)
365 p = subprocess.Popen([sys.executable, "-c",
366 'import sys; sys.exit(sys.stdin.read() == "pear")'],
367 stdin=tf)
368 p.wait()
369 self.assertEqual(p.returncode, 1)
370
371 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000372 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000373 p = subprocess.Popen([sys.executable, "-c",
374 'import sys; sys.stdout.write("orange")'],
375 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000376 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000377 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000378
379 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000380 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000381 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000382 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000383 d = tf.fileno()
384 p = subprocess.Popen([sys.executable, "-c",
385 'import sys; sys.stdout.write("orange")'],
386 stdout=d)
387 p.wait()
388 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000389 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000390
391 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000392 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000393 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000394 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000395 p = subprocess.Popen([sys.executable, "-c",
396 'import sys; sys.stdout.write("orange")'],
397 stdout=tf)
398 p.wait()
399 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000400 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000401
402 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000403 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000404 p = subprocess.Popen([sys.executable, "-c",
405 'import sys; sys.stderr.write("strawberry")'],
406 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000407 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000408 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000409
410 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000411 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000412 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000413 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000414 d = tf.fileno()
415 p = subprocess.Popen([sys.executable, "-c",
416 'import sys; sys.stderr.write("strawberry")'],
417 stderr=d)
418 p.wait()
419 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000420 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000421
422 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000423 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000424 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000425 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000426 p = subprocess.Popen([sys.executable, "-c",
427 'import sys; sys.stderr.write("strawberry")'],
428 stderr=tf)
429 p.wait()
430 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000431 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000432
433 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000434 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000435 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000436 'import sys;'
437 'sys.stdout.write("apple");'
438 'sys.stdout.flush();'
439 'sys.stderr.write("orange")'],
440 stdout=subprocess.PIPE,
441 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000442 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000443 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000444
445 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000446 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000447 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000448 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000449 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000450 'import sys;'
451 'sys.stdout.write("apple");'
452 'sys.stdout.flush();'
453 'sys.stderr.write("orange")'],
454 stdout=tf,
455 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000456 p.wait()
457 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000458 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000459
Thomas Wouters89f507f2006-12-13 04:49:30 +0000460 def test_stdout_filedes_of_stdout(self):
461 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000462 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000463 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000464 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000465
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200466 def test_stdout_devnull(self):
467 p = subprocess.Popen([sys.executable, "-c",
468 'for i in range(10240):'
469 'print("x" * 1024)'],
470 stdout=subprocess.DEVNULL)
471 p.wait()
472 self.assertEqual(p.stdout, None)
473
474 def test_stderr_devnull(self):
475 p = subprocess.Popen([sys.executable, "-c",
476 'import sys\n'
477 'for i in range(10240):'
478 'sys.stderr.write("x" * 1024)'],
479 stderr=subprocess.DEVNULL)
480 p.wait()
481 self.assertEqual(p.stderr, None)
482
483 def test_stdin_devnull(self):
484 p = subprocess.Popen([sys.executable, "-c",
485 'import sys;'
486 'sys.stdin.read(1)'],
487 stdin=subprocess.DEVNULL)
488 p.wait()
489 self.assertEqual(p.stdin, None)
490
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000491 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000492 newenv = os.environ.copy()
493 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200494 with subprocess.Popen([sys.executable, "-c",
495 'import sys,os;'
496 'sys.stdout.write(os.getenv("FRUIT"))'],
497 stdout=subprocess.PIPE,
498 env=newenv) as p:
499 stdout, stderr = p.communicate()
500 self.assertEqual(stdout, b"orange")
501
Victor Stinner62d51182011-06-23 01:02:25 +0200502 # Windows requires at least the SYSTEMROOT environment variable to start
503 # Python
504 @unittest.skipIf(sys.platform == 'win32',
505 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200506 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200507 'the python library cannot be loaded '
508 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200509 def test_empty_env(self):
510 with subprocess.Popen([sys.executable, "-c",
511 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200512 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200513 stdout=subprocess.PIPE,
514 env={}) as p:
515 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200516 self.assertIn(stdout.strip(),
517 (b"[]",
518 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
519 # environment
520 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000521
Peter Astrandcbac93c2005-03-03 20:24:28 +0000522 def test_communicate_stdin(self):
523 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000524 'import sys;'
525 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000526 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000527 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000528 self.assertEqual(p.returncode, 1)
529
530 def test_communicate_stdout(self):
531 p = subprocess.Popen([sys.executable, "-c",
532 'import sys; sys.stdout.write("pineapple")'],
533 stdout=subprocess.PIPE)
534 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000535 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000536 self.assertEqual(stderr, None)
537
538 def test_communicate_stderr(self):
539 p = subprocess.Popen([sys.executable, "-c",
540 'import sys; sys.stderr.write("pineapple")'],
541 stderr=subprocess.PIPE)
542 (stdout, stderr) = p.communicate()
543 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000544 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000545
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000546 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000547 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000548 'import sys,os;'
549 'sys.stderr.write("pineapple");'
550 'sys.stdout.write(sys.stdin.read())'],
551 stdin=subprocess.PIPE,
552 stdout=subprocess.PIPE,
553 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000554 self.addCleanup(p.stdout.close)
555 self.addCleanup(p.stderr.close)
556 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000557 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000558 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000559 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000560
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400561 def test_communicate_timeout(self):
562 p = subprocess.Popen([sys.executable, "-c",
563 'import sys,os,time;'
564 'sys.stderr.write("pineapple\\n");'
565 'time.sleep(1);'
566 'sys.stderr.write("pear\\n");'
567 'sys.stdout.write(sys.stdin.read())'],
568 universal_newlines=True,
569 stdin=subprocess.PIPE,
570 stdout=subprocess.PIPE,
571 stderr=subprocess.PIPE)
572 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
573 timeout=0.3)
574 # Make sure we can keep waiting for it, and that we get the whole output
575 # after it completes.
576 (stdout, stderr) = p.communicate()
577 self.assertEqual(stdout, "banana")
578 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
579
580 def test_communicate_timeout_large_ouput(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200581 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400582 p = subprocess.Popen([sys.executable, "-c",
583 'import sys,os,time;'
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 'time.sleep(0.2);'
590 'sys.stdout.write("a" * (64 * 1024));'],
591 stdout=subprocess.PIPE)
592 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
593 (stdout, _) = p.communicate()
594 self.assertEqual(len(stdout), 4 * 64 * 1024)
595
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000596 # Test for the fd leak reported in http://bugs.python.org/issue2791.
597 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000598 for stdin_pipe in (False, True):
599 for stdout_pipe in (False, True):
600 for stderr_pipe in (False, True):
601 options = {}
602 if stdin_pipe:
603 options['stdin'] = subprocess.PIPE
604 if stdout_pipe:
605 options['stdout'] = subprocess.PIPE
606 if stderr_pipe:
607 options['stderr'] = subprocess.PIPE
608 if not options:
609 continue
610 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
611 p.communicate()
612 if p.stdin is not None:
613 self.assertTrue(p.stdin.closed)
614 if p.stdout is not None:
615 self.assertTrue(p.stdout.closed)
616 if p.stderr is not None:
617 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000618
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000619 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000620 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000621 p = subprocess.Popen([sys.executable, "-c",
622 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000623 (stdout, stderr) = p.communicate()
624 self.assertEqual(stdout, None)
625 self.assertEqual(stderr, None)
626
627 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000628 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000629 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000630 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000631 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000632 os.close(x)
633 os.close(y)
634 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000635 'import sys,os;'
636 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200637 'sys.stderr.write("x" * %d);'
638 'sys.stdout.write(sys.stdin.read())' %
639 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000640 stdin=subprocess.PIPE,
641 stdout=subprocess.PIPE,
642 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000643 self.addCleanup(p.stdout.close)
644 self.addCleanup(p.stderr.close)
645 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200646 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000647 (stdout, stderr) = p.communicate(string_to_write)
648 self.assertEqual(stdout, string_to_write)
649
650 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000651 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000652 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000653 'import sys,os;'
654 'sys.stdout.write(sys.stdin.read())'],
655 stdin=subprocess.PIPE,
656 stdout=subprocess.PIPE,
657 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000658 self.addCleanup(p.stdout.close)
659 self.addCleanup(p.stderr.close)
660 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000661 p.stdin.write(b"banana")
662 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000663 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000664 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000665
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000666 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000667 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000668 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200669 'buf = sys.stdout.buffer;'
670 'buf.write(sys.stdin.readline().encode());'
671 'buf.flush();'
672 'buf.write(b"line2\\n");'
673 'buf.flush();'
674 'buf.write(sys.stdin.read().encode());'
675 'buf.flush();'
676 'buf.write(b"line4\\n");'
677 'buf.flush();'
678 'buf.write(b"line5\\r\\n");'
679 'buf.flush();'
680 'buf.write(b"line6\\r");'
681 'buf.flush();'
682 'buf.write(b"\\nline7");'
683 'buf.flush();'
684 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200685 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000686 stdout=subprocess.PIPE,
687 universal_newlines=1)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200688 p.stdin.write("line1\n")
689 self.assertEqual(p.stdout.readline(), "line1\n")
690 p.stdin.write("line3\n")
691 p.stdin.close()
Brian Curtin3c6a9512010-11-05 03:58:52 +0000692 self.addCleanup(p.stdout.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200693 self.assertEqual(p.stdout.readline(),
694 "line2\n")
695 self.assertEqual(p.stdout.read(6),
696 "line3\n")
697 self.assertEqual(p.stdout.read(),
698 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000699
700 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000701 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000702 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000703 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200704 'buf = sys.stdout.buffer;'
705 'buf.write(b"line2\\n");'
706 'buf.flush();'
707 'buf.write(b"line4\\n");'
708 'buf.flush();'
709 'buf.write(b"line5\\r\\n");'
710 'buf.flush();'
711 'buf.write(b"line6\\r");'
712 'buf.flush();'
713 'buf.write(b"\\nline7");'
714 'buf.flush();'
715 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200716 stderr=subprocess.PIPE,
717 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000718 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000719 self.addCleanup(p.stdout.close)
720 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000721 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200722 self.assertEqual(stdout,
723 "line2\nline4\nline5\nline6\nline7\nline8")
724
725 def test_universal_newlines_communicate_stdin(self):
726 # universal newlines through communicate(), with only stdin
727 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300728 'import sys,os;' + SETBINARY + textwrap.dedent('''
729 s = sys.stdin.readline()
730 assert s == "line1\\n", repr(s)
731 s = sys.stdin.read()
732 assert s == "line3\\n", repr(s)
733 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200734 stdin=subprocess.PIPE,
735 universal_newlines=1)
736 (stdout, stderr) = p.communicate("line1\nline3\n")
737 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000738
Andrew Svetlovf3765072012-08-14 18:35:17 +0300739 def test_universal_newlines_communicate_input_none(self):
740 # Test communicate(input=None) with universal newlines.
741 #
742 # We set stdout to PIPE because, as of this writing, a different
743 # code path is tested when the number of pipes is zero or one.
744 p = subprocess.Popen([sys.executable, "-c", "pass"],
745 stdin=subprocess.PIPE,
746 stdout=subprocess.PIPE,
747 universal_newlines=True)
748 p.communicate()
749 self.assertEqual(p.returncode, 0)
750
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300751 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300752 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300753 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300754 'import sys,os;' + SETBINARY + textwrap.dedent('''
755 s = sys.stdin.buffer.readline()
756 sys.stdout.buffer.write(s)
757 sys.stdout.buffer.write(b"line2\\r")
758 sys.stderr.buffer.write(b"eline2\\n")
759 s = sys.stdin.buffer.read()
760 sys.stdout.buffer.write(s)
761 sys.stdout.buffer.write(b"line4\\n")
762 sys.stdout.buffer.write(b"line5\\r\\n")
763 sys.stderr.buffer.write(b"eline6\\r")
764 sys.stderr.buffer.write(b"eline7\\r\\nz")
765 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300766 stdin=subprocess.PIPE,
767 stderr=subprocess.PIPE,
768 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300769 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300770 self.addCleanup(p.stdout.close)
771 self.addCleanup(p.stderr.close)
772 (stdout, stderr) = p.communicate("line1\nline3\n")
773 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300774 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300775 # Python debug build push something like "[42442 refs]\n"
776 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300777 # Don't use assertStderrEqual because it strips CR and LF from output.
778 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300779
Andrew Svetlov82860712012-08-19 22:13:41 +0300780 def test_universal_newlines_communicate_encodings(self):
781 # Check that universal newlines mode works for various encodings,
782 # in particular for encodings in the UTF-16 and UTF-32 families.
783 # See issue #15595.
784 #
785 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
786 # without, and UTF-16 and UTF-32.
787 for encoding in ['utf-16', 'utf-32-be']:
788 old_getpreferredencoding = locale.getpreferredencoding
789 # Indirectly via io.TextIOWrapper, Popen() defaults to
790 # locale.getpreferredencoding(False) and earlier in Python 3.2 to
791 # locale.getpreferredencoding().
792 def getpreferredencoding(do_setlocale=True):
793 return encoding
794 code = ("import sys; "
795 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
796 encoding)
797 args = [sys.executable, '-c', code]
798 try:
799 locale.getpreferredencoding = getpreferredencoding
800 # We set stdin to be non-None because, as of this writing,
801 # a different code path is used when the number of pipes is
802 # zero or one.
803 popen = subprocess.Popen(args, universal_newlines=True,
804 stdin=subprocess.PIPE,
805 stdout=subprocess.PIPE)
806 stdout, stderr = popen.communicate(input='')
807 finally:
808 locale.getpreferredencoding = old_getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300809 self.assertEqual(stdout, '1\n2\n3\n4')
810
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000811 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000812 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000813 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000814 max_handles = 1026 # too much for most UNIX systems
815 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000816 max_handles = 2050 # too much for (at least some) Windows setups
817 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400818 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000819 try:
820 for i in range(max_handles):
821 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400822 tmpfile = os.path.join(tmpdir, support.TESTFN)
823 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000824 except OSError as e:
825 if e.errno != errno.EMFILE:
826 raise
827 break
828 else:
829 self.skipTest("failed to reach the file descriptor limit "
830 "(tried %d)" % max_handles)
831 # Close a couple of them (should be enough for a subprocess)
832 for i in range(10):
833 os.close(handles.pop())
834 # Loop creating some subprocesses. If one of them leaks some fds,
835 # the next loop iteration will fail by reaching the max fd limit.
836 for i in range(15):
837 p = subprocess.Popen([sys.executable, "-c",
838 "import sys;"
839 "sys.stdout.write(sys.stdin.read())"],
840 stdin=subprocess.PIPE,
841 stdout=subprocess.PIPE,
842 stderr=subprocess.PIPE)
843 data = p.communicate(b"lime")[0]
844 self.assertEqual(data, b"lime")
845 finally:
846 for h in handles:
847 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400848 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000849
850 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000851 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
852 '"a b c" d e')
853 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
854 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000855 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
856 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000857 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
858 'a\\\\\\b "de fg" h')
859 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
860 'a\\\\\\"b c d')
861 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
862 '"a\\\\b c" d e')
863 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
864 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000865 self.assertEqual(subprocess.list2cmdline(['ab', '']),
866 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000867
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000868 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200869 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +0200870 "import os; os.read(0, 1)"],
871 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200872 self.addCleanup(p.stdin.close)
873 self.assertIsNone(p.poll())
874 os.write(p.stdin.fileno(), b'A')
875 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000876 # Subsequent invocations should just return the returncode
877 self.assertEqual(p.poll(), 0)
878
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000879 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200880 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000881 self.assertEqual(p.wait(), 0)
882 # Subsequent invocations should just return the returncode
883 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000884
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400885 def test_wait_timeout(self):
886 p = subprocess.Popen([sys.executable,
Reid Kleckner93479cc2011-03-14 19:32:41 -0400887 "-c", "import time; time.sleep(0.1)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -0400888 with self.assertRaises(subprocess.TimeoutExpired) as c:
889 p.wait(timeout=0.01)
890 self.assertIn("0.01", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -0400891 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
892 # time to start.
893 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400894
Peter Astrand738131d2004-11-30 21:04:45 +0000895 def test_invalid_bufsize(self):
896 # an invalid type of the bufsize argument should raise
897 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000898 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000899 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000900
Guido van Rossum46a05a72007-06-07 21:56:45 +0000901 def test_bufsize_is_none(self):
902 # bufsize=None should be the same as bufsize=0.
903 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
904 self.assertEqual(p.wait(), 0)
905 # Again with keyword arg
906 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
907 self.assertEqual(p.wait(), 0)
908
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000909 def test_leaking_fds_on_error(self):
910 # see bug #5179: Popen leaks file descriptors to PIPEs if
911 # the child fails to execute; this will eventually exhaust
912 # the maximum number of open fds. 1024 seems a very common
913 # value for that limit, but Windows has 2048, so we loop
914 # 1024 times (each call leaked two fds).
915 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000916 # Windows raises IOError. Others raise OSError.
917 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000918 subprocess.Popen(['nonexisting_i_hope'],
919 stdout=subprocess.PIPE,
920 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400921 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400922 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000923 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000924
Victor Stinnerb3693582010-05-21 20:13:12 +0000925 def test_issue8780(self):
926 # Ensure that stdout is inherited from the parent
927 # if stdout=PIPE is not used
928 code = ';'.join((
929 'import subprocess, sys',
930 'retcode = subprocess.call('
931 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
932 'assert retcode == 0'))
933 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000934 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000935
Tim Goldenaf5ac392010-08-06 13:03:56 +0000936 def test_handles_closed_on_exception(self):
937 # If CreateProcess exits with an error, ensure the
938 # duplicate output handles are released
939 ifhandle, ifname = mkstemp()
940 ofhandle, ofname = mkstemp()
941 efhandle, efname = mkstemp()
942 try:
943 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
944 stderr=efhandle)
945 except OSError:
946 os.close(ifhandle)
947 os.remove(ifname)
948 os.close(ofhandle)
949 os.remove(ofname)
950 os.close(efhandle)
951 os.remove(efname)
952 self.assertFalse(os.path.exists(ifname))
953 self.assertFalse(os.path.exists(ofname))
954 self.assertFalse(os.path.exists(efname))
955
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200956 def test_communicate_epipe(self):
957 # Issue 10963: communicate() should hide EPIPE
958 p = subprocess.Popen([sys.executable, "-c", 'pass'],
959 stdin=subprocess.PIPE,
960 stdout=subprocess.PIPE,
961 stderr=subprocess.PIPE)
962 self.addCleanup(p.stdout.close)
963 self.addCleanup(p.stderr.close)
964 self.addCleanup(p.stdin.close)
965 p.communicate(b"x" * 2**20)
966
967 def test_communicate_epipe_only_stdin(self):
968 # Issue 10963: communicate() should hide EPIPE
969 p = subprocess.Popen([sys.executable, "-c", 'pass'],
970 stdin=subprocess.PIPE)
971 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200972 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200973 p.communicate(b"x" * 2**20)
974
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200975 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
976 "Requires signal.SIGUSR1")
977 @unittest.skipUnless(hasattr(os, 'kill'),
978 "Requires os.kill")
979 @unittest.skipUnless(hasattr(os, 'getppid'),
980 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200981 def test_communicate_eintr(self):
982 # Issue #12493: communicate() should handle EINTR
983 def handler(signum, frame):
984 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200985 old_handler = signal.signal(signal.SIGUSR1, handler)
986 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200987
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200988 args = [sys.executable, "-c",
989 'import os, signal;'
990 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200991 for stream in ('stdout', 'stderr'):
992 kw = {stream: subprocess.PIPE}
993 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200994 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200995 process.communicate()
996
Tim Peterse718f612004-10-12 21:51:32 +0000997
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000998# context manager
999class _SuppressCoreFiles(object):
1000 """Try to prevent core files from being created."""
1001 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001002
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001003 def __enter__(self):
1004 """Try to save previous ulimit, then set it to (0, 0)."""
Benjamin Peterson964561b2011-12-10 12:31:42 -05001005 if resource is not None:
1006 try:
1007 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
1008 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
1009 except (ValueError, resource.error):
1010 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001011
Ronald Oussoren102d11a2010-07-23 09:50:05 +00001012 if sys.platform == 'darwin':
1013 # Check if the 'Crash Reporter' on OSX was configured
1014 # in 'Developer' mode and warn that it will get triggered
1015 # when it is.
1016 #
1017 # This assumes that this context manager is used in tests
1018 # that might trigger the next manager.
1019 value = subprocess.Popen(['/usr/bin/defaults', 'read',
1020 'com.apple.CrashReporter', 'DialogType'],
1021 stdout=subprocess.PIPE).communicate()[0]
1022 if value.strip() == b'developer':
1023 print("this tests triggers the Crash Reporter, "
1024 "that is intentional", end='')
1025 sys.stdout.flush()
1026
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001027 def __exit__(self, *args):
1028 """Return core file behavior to default."""
1029 if self.old_limit is None:
1030 return
Benjamin Peterson964561b2011-12-10 12:31:42 -05001031 if resource is not None:
1032 try:
1033 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
1034 except (ValueError, resource.error):
1035 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001036
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001037
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001038@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001039class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001040
Gregory P. Smith5591b022012-10-10 03:34:47 -07001041 def setUp(self):
1042 super().setUp()
1043 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1044
1045 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001046 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001047 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001048 except OSError as e:
1049 # This avoids hard coding the errno value or the OS perror()
1050 # string and instead capture the exception that we want to see
1051 # below for comparison.
1052 desired_exception = e
Gregory P. Smith5591b022012-10-10 03:34:47 -07001053 desired_exception.strerror += ': ' + repr(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001054 else:
1055 self.fail("chdir to nonexistant directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001056 self._nonexistent_dir)
1057 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001058
Gregory P. Smith5591b022012-10-10 03:34:47 -07001059 def test_exception_cwd(self):
1060 """Test error in the child raised in the parent for a bad cwd."""
1061 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001062 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001063 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001064 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001065 except OSError as e:
1066 # Test that the child process chdir failure actually makes
1067 # it up to the parent process as the correct exception.
1068 self.assertEqual(desired_exception.errno, e.errno)
1069 self.assertEqual(desired_exception.strerror, e.strerror)
1070 else:
1071 self.fail("Expected OSError: %s" % desired_exception)
1072
Gregory P. Smith5591b022012-10-10 03:34:47 -07001073 def test_exception_bad_executable(self):
1074 """Test error in the child raised in the parent for a bad executable."""
1075 desired_exception = self._get_chdir_exception()
1076 try:
1077 p = subprocess.Popen([sys.executable, "-c", ""],
1078 executable=self._nonexistent_dir)
1079 except OSError as e:
1080 # Test that the child process exec failure actually makes
1081 # it up to the parent process as the correct exception.
1082 self.assertEqual(desired_exception.errno, e.errno)
1083 self.assertEqual(desired_exception.strerror, e.strerror)
1084 else:
1085 self.fail("Expected OSError: %s" % desired_exception)
1086
1087 def test_exception_bad_args_0(self):
1088 """Test error in the child raised in the parent for a bad args[0]."""
1089 desired_exception = self._get_chdir_exception()
1090 try:
1091 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1092 except OSError as e:
1093 # Test that the child process exec failure actually makes
1094 # it up to the parent process as the correct exception.
1095 self.assertEqual(desired_exception.errno, e.errno)
1096 self.assertEqual(desired_exception.strerror, e.strerror)
1097 else:
1098 self.fail("Expected OSError: %s" % desired_exception)
1099
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001100 def test_restore_signals(self):
1101 # Code coverage for both values of restore_signals to make sure it
1102 # at least does not blow up.
1103 # A test for behavior would be complex. Contributions welcome.
1104 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1105 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1106
1107 def test_start_new_session(self):
1108 # For code coverage of calling setsid(). We don't care if we get an
1109 # EPERM error from it depending on the test execution environment, that
1110 # still indicates that it was called.
1111 try:
1112 output = subprocess.check_output(
1113 [sys.executable, "-c",
1114 "import os; print(os.getpgid(os.getpid()))"],
1115 start_new_session=True)
1116 except OSError as e:
1117 if e.errno != errno.EPERM:
1118 raise
1119 else:
1120 parent_pgid = os.getpgid(os.getpid())
1121 child_pgid = int(output)
1122 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001123
1124 def test_run_abort(self):
1125 # returncode handles signal termination
1126 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001127 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001128 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001129 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001130 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001131
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001132 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001133 # DISCLAIMER: Setting environment variables is *not* a good use
1134 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001135 p = subprocess.Popen([sys.executable, "-c",
1136 'import sys,os;'
1137 'sys.stdout.write(os.getenv("FRUIT"))'],
1138 stdout=subprocess.PIPE,
1139 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +00001140 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001141 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001142
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001143 def test_preexec_exception(self):
1144 def raise_it():
1145 raise ValueError("What if two swallows carried a coconut?")
1146 try:
1147 p = subprocess.Popen([sys.executable, "-c", ""],
1148 preexec_fn=raise_it)
1149 except RuntimeError as e:
1150 self.assertTrue(
1151 subprocess._posixsubprocess,
1152 "Expected a ValueError from the preexec_fn")
1153 except ValueError as e:
1154 self.assertIn("coconut", e.args[0])
1155 else:
1156 self.fail("Exception raised by preexec_fn did not make it "
1157 "to the parent process.")
1158
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001159 def test_preexec_gc_module_failure(self):
1160 # This tests the code that disables garbage collection if the child
1161 # process will execute any Python.
1162 def raise_runtime_error():
1163 raise RuntimeError("this shouldn't escape")
1164 enabled = gc.isenabled()
1165 orig_gc_disable = gc.disable
1166 orig_gc_isenabled = gc.isenabled
1167 try:
1168 gc.disable()
1169 self.assertFalse(gc.isenabled())
1170 subprocess.call([sys.executable, '-c', ''],
1171 preexec_fn=lambda: None)
1172 self.assertFalse(gc.isenabled(),
1173 "Popen enabled gc when it shouldn't.")
1174
1175 gc.enable()
1176 self.assertTrue(gc.isenabled())
1177 subprocess.call([sys.executable, '-c', ''],
1178 preexec_fn=lambda: None)
1179 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1180
1181 gc.disable = raise_runtime_error
1182 self.assertRaises(RuntimeError, subprocess.Popen,
1183 [sys.executable, '-c', ''],
1184 preexec_fn=lambda: None)
1185
1186 del gc.isenabled # force an AttributeError
1187 self.assertRaises(AttributeError, subprocess.Popen,
1188 [sys.executable, '-c', ''],
1189 preexec_fn=lambda: None)
1190 finally:
1191 gc.disable = orig_gc_disable
1192 gc.isenabled = orig_gc_isenabled
1193 if not enabled:
1194 gc.disable()
1195
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001196 def test_args_string(self):
1197 # args is a string
1198 fd, fname = mkstemp()
1199 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001200 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001201 fobj.write("#!/bin/sh\n")
1202 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1203 sys.executable)
1204 os.chmod(fname, 0o700)
1205 p = subprocess.Popen(fname)
1206 p.wait()
1207 os.remove(fname)
1208 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001209
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001210 def test_invalid_args(self):
1211 # invalid arguments should raise ValueError
1212 self.assertRaises(ValueError, subprocess.call,
1213 [sys.executable, "-c",
1214 "import sys; sys.exit(47)"],
1215 startupinfo=47)
1216 self.assertRaises(ValueError, subprocess.call,
1217 [sys.executable, "-c",
1218 "import sys; sys.exit(47)"],
1219 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001220
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001221 def test_shell_sequence(self):
1222 # Run command through the shell (sequence)
1223 newenv = os.environ.copy()
1224 newenv["FRUIT"] = "apple"
1225 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1226 stdout=subprocess.PIPE,
1227 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001228 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001229 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001230
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001231 def test_shell_string(self):
1232 # Run command through the shell (string)
1233 newenv = os.environ.copy()
1234 newenv["FRUIT"] = "apple"
1235 p = subprocess.Popen("echo $FRUIT", shell=1,
1236 stdout=subprocess.PIPE,
1237 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001238 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001239 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001240
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001241 def test_call_string(self):
1242 # call() function with string argument on UNIX
1243 fd, fname = mkstemp()
1244 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001245 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001246 fobj.write("#!/bin/sh\n")
1247 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1248 sys.executable)
1249 os.chmod(fname, 0o700)
1250 rc = subprocess.call(fname)
1251 os.remove(fname)
1252 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001253
Stefan Krah9542cc62010-07-19 14:20:53 +00001254 def test_specific_shell(self):
1255 # Issue #9265: Incorrect name passed as arg[0].
1256 shells = []
1257 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1258 for name in ['bash', 'ksh']:
1259 sh = os.path.join(prefix, name)
1260 if os.path.isfile(sh):
1261 shells.append(sh)
1262 if not shells: # Will probably work for any shell but csh.
1263 self.skipTest("bash or ksh required for this test")
1264 sh = '/bin/sh'
1265 if os.path.isfile(sh) and not os.path.islink(sh):
1266 # Test will fail if /bin/sh is a symlink to csh.
1267 shells.append(sh)
1268 for sh in shells:
1269 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1270 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001271 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001272 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1273
Florent Xicluna4886d242010-03-08 13:27:26 +00001274 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001275 # Do not inherit file handles from the parent.
1276 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001277 p = subprocess.Popen([sys.executable, "-c", """if 1:
1278 import sys, time
1279 sys.stdout.write('x\\n')
1280 sys.stdout.flush()
1281 time.sleep(30)
1282 """],
1283 close_fds=True,
1284 stdin=subprocess.PIPE,
1285 stdout=subprocess.PIPE,
1286 stderr=subprocess.PIPE)
1287 # Wait for the interpreter to be completely initialized before
1288 # sending any signal.
1289 p.stdout.read(1)
1290 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001291 return p
1292
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001293 def _kill_dead_process(self, method, *args):
1294 # Do not inherit file handles from the parent.
1295 # It should fix failures on some platforms.
1296 p = subprocess.Popen([sys.executable, "-c", """if 1:
1297 import sys, time
1298 sys.stdout.write('x\\n')
1299 sys.stdout.flush()
1300 """],
1301 close_fds=True,
1302 stdin=subprocess.PIPE,
1303 stdout=subprocess.PIPE,
1304 stderr=subprocess.PIPE)
1305 # Wait for the interpreter to be completely initialized before
1306 # sending any signal.
1307 p.stdout.read(1)
1308 # The process should end after this
1309 time.sleep(1)
1310 # This shouldn't raise even though the child is now dead
1311 getattr(p, method)(*args)
1312 p.communicate()
1313
Florent Xicluna4886d242010-03-08 13:27:26 +00001314 def test_send_signal(self):
1315 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001316 _, stderr = p.communicate()
1317 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001318 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001319
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001320 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001321 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001322 _, stderr = p.communicate()
1323 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001324 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001325
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001326 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001327 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001328 _, stderr = p.communicate()
1329 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001330 self.assertEqual(p.wait(), -signal.SIGTERM)
1331
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001332 def test_send_signal_dead(self):
1333 # Sending a signal to a dead process
1334 self._kill_dead_process('send_signal', signal.SIGINT)
1335
1336 def test_kill_dead(self):
1337 # Killing a dead process
1338 self._kill_dead_process('kill')
1339
1340 def test_terminate_dead(self):
1341 # Terminating a dead process
1342 self._kill_dead_process('terminate')
1343
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001344 def check_close_std_fds(self, fds):
1345 # Issue #9905: test that subprocess pipes still work properly with
1346 # some standard fds closed
1347 stdin = 0
1348 newfds = []
1349 for a in fds:
1350 b = os.dup(a)
1351 newfds.append(b)
1352 if a == 0:
1353 stdin = b
1354 try:
1355 for fd in fds:
1356 os.close(fd)
1357 out, err = subprocess.Popen([sys.executable, "-c",
1358 'import sys;'
1359 'sys.stdout.write("apple");'
1360 'sys.stdout.flush();'
1361 'sys.stderr.write("orange")'],
1362 stdin=stdin,
1363 stdout=subprocess.PIPE,
1364 stderr=subprocess.PIPE).communicate()
1365 err = support.strip_python_stderr(err)
1366 self.assertEqual((out, err), (b'apple', b'orange'))
1367 finally:
1368 for b, a in zip(newfds, fds):
1369 os.dup2(b, a)
1370 for b in newfds:
1371 os.close(b)
1372
1373 def test_close_fd_0(self):
1374 self.check_close_std_fds([0])
1375
1376 def test_close_fd_1(self):
1377 self.check_close_std_fds([1])
1378
1379 def test_close_fd_2(self):
1380 self.check_close_std_fds([2])
1381
1382 def test_close_fds_0_1(self):
1383 self.check_close_std_fds([0, 1])
1384
1385 def test_close_fds_0_2(self):
1386 self.check_close_std_fds([0, 2])
1387
1388 def test_close_fds_1_2(self):
1389 self.check_close_std_fds([1, 2])
1390
1391 def test_close_fds_0_1_2(self):
1392 # Issue #10806: test that subprocess pipes still work properly with
1393 # all standard fds closed.
1394 self.check_close_std_fds([0, 1, 2])
1395
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001396 def test_remapping_std_fds(self):
1397 # open up some temporary files
1398 temps = [mkstemp() for i in range(3)]
1399 try:
1400 temp_fds = [fd for fd, fname in temps]
1401
1402 # unlink the files -- we won't need to reopen them
1403 for fd, fname in temps:
1404 os.unlink(fname)
1405
1406 # write some data to what will become stdin, and rewind
1407 os.write(temp_fds[1], b"STDIN")
1408 os.lseek(temp_fds[1], 0, 0)
1409
1410 # move the standard file descriptors out of the way
1411 saved_fds = [os.dup(fd) for fd in range(3)]
1412 try:
1413 # duplicate the file objects over the standard fd's
1414 for fd, temp_fd in enumerate(temp_fds):
1415 os.dup2(temp_fd, fd)
1416
1417 # now use those files in the "wrong" order, so that subprocess
1418 # has to rearrange them in the child
1419 p = subprocess.Popen([sys.executable, "-c",
1420 'import sys; got = sys.stdin.read();'
1421 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1422 stdin=temp_fds[1],
1423 stdout=temp_fds[2],
1424 stderr=temp_fds[0])
1425 p.wait()
1426 finally:
1427 # restore the original fd's underneath sys.stdin, etc.
1428 for std, saved in enumerate(saved_fds):
1429 os.dup2(saved, std)
1430 os.close(saved)
1431
1432 for fd in temp_fds:
1433 os.lseek(fd, 0, 0)
1434
1435 out = os.read(temp_fds[2], 1024)
1436 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1437 self.assertEqual(out, b"got STDIN")
1438 self.assertEqual(err, b"err")
1439
1440 finally:
1441 for fd in temp_fds:
1442 os.close(fd)
1443
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001444 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1445 # open up some temporary files
1446 temps = [mkstemp() for i in range(3)]
1447 temp_fds = [fd for fd, fname in temps]
1448 try:
1449 # unlink the files -- we won't need to reopen them
1450 for fd, fname in temps:
1451 os.unlink(fname)
1452
1453 # save a copy of the standard file descriptors
1454 saved_fds = [os.dup(fd) for fd in range(3)]
1455 try:
1456 # duplicate the temp files over the standard fd's 0, 1, 2
1457 for fd, temp_fd in enumerate(temp_fds):
1458 os.dup2(temp_fd, fd)
1459
1460 # write some data to what will become stdin, and rewind
1461 os.write(stdin_no, b"STDIN")
1462 os.lseek(stdin_no, 0, 0)
1463
1464 # now use those files in the given order, so that subprocess
1465 # has to rearrange them in the child
1466 p = subprocess.Popen([sys.executable, "-c",
1467 'import sys; got = sys.stdin.read();'
1468 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1469 stdin=stdin_no,
1470 stdout=stdout_no,
1471 stderr=stderr_no)
1472 p.wait()
1473
1474 for fd in temp_fds:
1475 os.lseek(fd, 0, 0)
1476
1477 out = os.read(stdout_no, 1024)
1478 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1479 finally:
1480 for std, saved in enumerate(saved_fds):
1481 os.dup2(saved, std)
1482 os.close(saved)
1483
1484 self.assertEqual(out, b"got STDIN")
1485 self.assertEqual(err, b"err")
1486
1487 finally:
1488 for fd in temp_fds:
1489 os.close(fd)
1490
1491 # When duping fds, if there arises a situation where one of the fds is
1492 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1493 # This tests all combinations of this.
1494 def test_swap_fds(self):
1495 self.check_swap_fds(0, 1, 2)
1496 self.check_swap_fds(0, 2, 1)
1497 self.check_swap_fds(1, 0, 2)
1498 self.check_swap_fds(1, 2, 0)
1499 self.check_swap_fds(2, 0, 1)
1500 self.check_swap_fds(2, 1, 0)
1501
Victor Stinner13bb71c2010-04-23 21:41:56 +00001502 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001503 def prepare():
1504 raise ValueError("surrogate:\uDCff")
1505
1506 try:
1507 subprocess.call(
1508 [sys.executable, "-c", "pass"],
1509 preexec_fn=prepare)
1510 except ValueError as err:
1511 # Pure Python implementations keeps the message
1512 self.assertIsNone(subprocess._posixsubprocess)
1513 self.assertEqual(str(err), "surrogate:\uDCff")
1514 except RuntimeError as err:
1515 # _posixsubprocess uses a default message
1516 self.assertIsNotNone(subprocess._posixsubprocess)
1517 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1518 else:
1519 self.fail("Expected ValueError or RuntimeError")
1520
Victor Stinner13bb71c2010-04-23 21:41:56 +00001521 def test_undecodable_env(self):
1522 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001523 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001524 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001525 env = os.environ.copy()
1526 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001527 # Use C locale to get ascii for the locale encoding to force
1528 # surrogate-escaping of \xFF in the child process; otherwise it can
1529 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001530 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001531 stdout = subprocess.check_output(
1532 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001533 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001534 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001535 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001536
1537 # test bytes
1538 key = key.encode("ascii", "surrogateescape")
1539 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001540 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001541 env = os.environ.copy()
1542 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001543 stdout = subprocess.check_output(
1544 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001545 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001546 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001547 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001548
Victor Stinnerb745a742010-05-18 17:17:23 +00001549 def test_bytes_program(self):
1550 abs_program = os.fsencode(sys.executable)
1551 path, program = os.path.split(sys.executable)
1552 program = os.fsencode(program)
1553
1554 # absolute bytes path
1555 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001556 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001557
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001558 # absolute bytes path as a string
1559 cmd = b"'" + abs_program + b"' -c pass"
1560 exitcode = subprocess.call(cmd, shell=True)
1561 self.assertEqual(exitcode, 0)
1562
Victor Stinnerb745a742010-05-18 17:17:23 +00001563 # bytes program, unicode PATH
1564 env = os.environ.copy()
1565 env["PATH"] = path
1566 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001567 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001568
1569 # bytes program, bytes PATH
1570 envb = os.environb.copy()
1571 envb[b"PATH"] = os.fsencode(path)
1572 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001573 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001574
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001575 def test_pipe_cloexec(self):
1576 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1577 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1578
1579 p1 = subprocess.Popen([sys.executable, sleeper],
1580 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1581 stderr=subprocess.PIPE, close_fds=False)
1582
1583 self.addCleanup(p1.communicate, b'')
1584
1585 p2 = subprocess.Popen([sys.executable, fd_status],
1586 stdout=subprocess.PIPE, close_fds=False)
1587
1588 output, error = p2.communicate()
1589 result_fds = set(map(int, output.split(b',')))
1590 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1591 p1.stderr.fileno()])
1592
1593 self.assertFalse(result_fds & unwanted_fds,
1594 "Expected no fds from %r to be open in child, "
1595 "found %r" %
1596 (unwanted_fds, result_fds & unwanted_fds))
1597
1598 def test_pipe_cloexec_real_tools(self):
1599 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1600 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1601
1602 subdata = b'zxcvbn'
1603 data = subdata * 4 + b'\n'
1604
1605 p1 = subprocess.Popen([sys.executable, qcat],
1606 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1607 close_fds=False)
1608
1609 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1610 stdin=p1.stdout, stdout=subprocess.PIPE,
1611 close_fds=False)
1612
1613 self.addCleanup(p1.wait)
1614 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001615 def kill_p1():
1616 try:
1617 p1.terminate()
1618 except ProcessLookupError:
1619 pass
1620 def kill_p2():
1621 try:
1622 p2.terminate()
1623 except ProcessLookupError:
1624 pass
1625 self.addCleanup(kill_p1)
1626 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001627
1628 p1.stdin.write(data)
1629 p1.stdin.close()
1630
1631 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1632
1633 self.assertTrue(readfiles, "The child hung")
1634 self.assertEqual(p2.stdout.read(), data)
1635
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001636 p1.stdout.close()
1637 p2.stdout.close()
1638
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001639 def test_close_fds(self):
1640 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1641
1642 fds = os.pipe()
1643 self.addCleanup(os.close, fds[0])
1644 self.addCleanup(os.close, fds[1])
1645
1646 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001647 # add a bunch more fds
1648 for _ in range(9):
1649 fd = os.open("/dev/null", os.O_RDONLY)
1650 self.addCleanup(os.close, fd)
1651 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001652
1653 p = subprocess.Popen([sys.executable, fd_status],
1654 stdout=subprocess.PIPE, close_fds=False)
1655 output, ignored = p.communicate()
1656 remaining_fds = set(map(int, output.split(b',')))
1657
1658 self.assertEqual(remaining_fds & open_fds, open_fds,
1659 "Some fds were closed")
1660
1661 p = subprocess.Popen([sys.executable, fd_status],
1662 stdout=subprocess.PIPE, close_fds=True)
1663 output, ignored = p.communicate()
1664 remaining_fds = set(map(int, output.split(b',')))
1665
1666 self.assertFalse(remaining_fds & open_fds,
1667 "Some fds were left open")
1668 self.assertIn(1, remaining_fds, "Subprocess failed")
1669
Gregory P. Smith8facece2012-01-21 14:01:08 -08001670 # Keep some of the fd's we opened open in the subprocess.
1671 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1672 fds_to_keep = set(open_fds.pop() for _ in range(8))
1673 p = subprocess.Popen([sys.executable, fd_status],
1674 stdout=subprocess.PIPE, close_fds=True,
1675 pass_fds=())
1676 output, ignored = p.communicate()
1677 remaining_fds = set(map(int, output.split(b',')))
1678
1679 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1680 "Some fds not in pass_fds were left open")
1681 self.assertIn(1, remaining_fds, "Subprocess failed")
1682
Victor Stinner88701e22011-06-01 13:13:04 +02001683 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1684 # descriptor of a pipe closed in the parent process is valid in the
1685 # child process according to fstat(), but the mode of the file
1686 # descriptor is invalid, and read or write raise an error.
1687 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001688 def test_pass_fds(self):
1689 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1690
1691 open_fds = set()
1692
1693 for x in range(5):
1694 fds = os.pipe()
1695 self.addCleanup(os.close, fds[0])
1696 self.addCleanup(os.close, fds[1])
1697 open_fds.update(fds)
1698
1699 for fd in open_fds:
1700 p = subprocess.Popen([sys.executable, fd_status],
1701 stdout=subprocess.PIPE, close_fds=True,
1702 pass_fds=(fd, ))
1703 output, ignored = p.communicate()
1704
1705 remaining_fds = set(map(int, output.split(b',')))
1706 to_be_closed = open_fds - {fd}
1707
1708 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1709 self.assertFalse(remaining_fds & to_be_closed,
1710 "fd to be closed passed")
1711
1712 # pass_fds overrides close_fds with a warning.
1713 with self.assertWarns(RuntimeWarning) as context:
1714 self.assertFalse(subprocess.call(
1715 [sys.executable, "-c", "import sys; sys.exit(0)"],
1716 close_fds=False, pass_fds=(fd, )))
1717 self.assertIn('overriding close_fds', str(context.warning))
1718
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001719 def test_stdout_stdin_are_single_inout_fd(self):
1720 with io.open(os.devnull, "r+") as inout:
1721 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1722 stdout=inout, stdin=inout)
1723 p.wait()
1724
1725 def test_stdout_stderr_are_single_inout_fd(self):
1726 with io.open(os.devnull, "r+") as inout:
1727 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1728 stdout=inout, stderr=inout)
1729 p.wait()
1730
1731 def test_stderr_stdin_are_single_inout_fd(self):
1732 with io.open(os.devnull, "r+") as inout:
1733 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1734 stderr=inout, stdin=inout)
1735 p.wait()
1736
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001737 def test_wait_when_sigchild_ignored(self):
1738 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1739 sigchild_ignore = support.findfile("sigchild_ignore.py",
1740 subdir="subprocessdata")
1741 p = subprocess.Popen([sys.executable, sigchild_ignore],
1742 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1743 stdout, stderr = p.communicate()
1744 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001745 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001746 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001747
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001748 def test_select_unbuffered(self):
1749 # Issue #11459: bufsize=0 should really set the pipes as
1750 # unbuffered (and therefore let select() work properly).
1751 select = support.import_module("select")
1752 p = subprocess.Popen([sys.executable, "-c",
1753 'import sys;'
1754 'sys.stdout.write("apple")'],
1755 stdout=subprocess.PIPE,
1756 bufsize=0)
1757 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001758 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001759 try:
1760 self.assertEqual(f.read(4), b"appl")
1761 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1762 finally:
1763 p.wait()
1764
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001765 def test_zombie_fast_process_del(self):
1766 # Issue #12650: on Unix, if Popen.__del__() was called before the
1767 # process exited, it wouldn't be added to subprocess._active, and would
1768 # remain a zombie.
1769 # spawn a Popen, and delete its reference before it exits
1770 p = subprocess.Popen([sys.executable, "-c",
1771 'import sys, time;'
1772 'time.sleep(0.2)'],
1773 stdout=subprocess.PIPE,
1774 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001775 self.addCleanup(p.stdout.close)
1776 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001777 ident = id(p)
1778 pid = p.pid
1779 del p
1780 # check that p is in the active processes list
1781 self.assertIn(ident, [id(o) for o in subprocess._active])
1782
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001783 def test_leak_fast_process_del_killed(self):
1784 # Issue #12650: on Unix, if Popen.__del__() was called before the
1785 # process exited, and the process got killed by a signal, it would never
1786 # be removed from subprocess._active, which triggered a FD and memory
1787 # leak.
1788 # spawn a Popen, delete its reference and kill it
1789 p = subprocess.Popen([sys.executable, "-c",
1790 'import time;'
1791 'time.sleep(3)'],
1792 stdout=subprocess.PIPE,
1793 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001794 self.addCleanup(p.stdout.close)
1795 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001796 ident = id(p)
1797 pid = p.pid
1798 del p
1799 os.kill(pid, signal.SIGKILL)
1800 # check that p is in the active processes list
1801 self.assertIn(ident, [id(o) for o in subprocess._active])
1802
1803 # let some time for the process to exit, and create a new Popen: this
1804 # should trigger the wait() of p
1805 time.sleep(0.2)
1806 with self.assertRaises(EnvironmentError) as c:
1807 with subprocess.Popen(['nonexisting_i_hope'],
1808 stdout=subprocess.PIPE,
1809 stderr=subprocess.PIPE) as proc:
1810 pass
1811 # p should have been wait()ed on, and removed from the _active list
1812 self.assertRaises(OSError, os.waitpid, pid, 0)
1813 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1814
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001815
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001816@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001817class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001818
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001819 def test_startupinfo(self):
1820 # startupinfo argument
1821 # We uses hardcoded constants, because we do not want to
1822 # depend on win32all.
1823 STARTF_USESHOWWINDOW = 1
1824 SW_MAXIMIZE = 3
1825 startupinfo = subprocess.STARTUPINFO()
1826 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1827 startupinfo.wShowWindow = SW_MAXIMIZE
1828 # Since Python is a console process, it won't be affected
1829 # by wShowWindow, but the argument should be silently
1830 # ignored
1831 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001832 startupinfo=startupinfo)
1833
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001834 def test_creationflags(self):
1835 # creationflags argument
1836 CREATE_NEW_CONSOLE = 16
1837 sys.stderr.write(" a DOS box should flash briefly ...\n")
1838 subprocess.call(sys.executable +
1839 ' -c "import time; time.sleep(0.25)"',
1840 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001841
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001842 def test_invalid_args(self):
1843 # invalid arguments should raise ValueError
1844 self.assertRaises(ValueError, subprocess.call,
1845 [sys.executable, "-c",
1846 "import sys; sys.exit(47)"],
1847 preexec_fn=lambda: 1)
1848 self.assertRaises(ValueError, subprocess.call,
1849 [sys.executable, "-c",
1850 "import sys; sys.exit(47)"],
1851 stdout=subprocess.PIPE,
1852 close_fds=True)
1853
1854 def test_close_fds(self):
1855 # close file descriptors
1856 rc = subprocess.call([sys.executable, "-c",
1857 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001858 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001859 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001860
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001861 def test_shell_sequence(self):
1862 # Run command through the shell (sequence)
1863 newenv = os.environ.copy()
1864 newenv["FRUIT"] = "physalis"
1865 p = subprocess.Popen(["set"], shell=1,
1866 stdout=subprocess.PIPE,
1867 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001868 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001869 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001870
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001871 def test_shell_string(self):
1872 # Run command through the shell (string)
1873 newenv = os.environ.copy()
1874 newenv["FRUIT"] = "physalis"
1875 p = subprocess.Popen("set", shell=1,
1876 stdout=subprocess.PIPE,
1877 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001878 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001879 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001880
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001881 def test_call_string(self):
1882 # call() function with string argument on Windows
1883 rc = subprocess.call(sys.executable +
1884 ' -c "import sys; sys.exit(47)"')
1885 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001886
Florent Xicluna4886d242010-03-08 13:27:26 +00001887 def _kill_process(self, method, *args):
1888 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001889 p = subprocess.Popen([sys.executable, "-c", """if 1:
1890 import sys, time
1891 sys.stdout.write('x\\n')
1892 sys.stdout.flush()
1893 time.sleep(30)
1894 """],
1895 stdin=subprocess.PIPE,
1896 stdout=subprocess.PIPE,
1897 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001898 self.addCleanup(p.stdout.close)
1899 self.addCleanup(p.stderr.close)
1900 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001901 # Wait for the interpreter to be completely initialized before
1902 # sending any signal.
1903 p.stdout.read(1)
1904 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001905 _, stderr = p.communicate()
1906 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001907 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001908 self.assertNotEqual(returncode, 0)
1909
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001910 def _kill_dead_process(self, method, *args):
1911 p = subprocess.Popen([sys.executable, "-c", """if 1:
1912 import sys, time
1913 sys.stdout.write('x\\n')
1914 sys.stdout.flush()
1915 sys.exit(42)
1916 """],
1917 stdin=subprocess.PIPE,
1918 stdout=subprocess.PIPE,
1919 stderr=subprocess.PIPE)
1920 self.addCleanup(p.stdout.close)
1921 self.addCleanup(p.stderr.close)
1922 self.addCleanup(p.stdin.close)
1923 # Wait for the interpreter to be completely initialized before
1924 # sending any signal.
1925 p.stdout.read(1)
1926 # The process should end after this
1927 time.sleep(1)
1928 # This shouldn't raise even though the child is now dead
1929 getattr(p, method)(*args)
1930 _, stderr = p.communicate()
1931 self.assertStderrEqual(stderr, b'')
1932 rc = p.wait()
1933 self.assertEqual(rc, 42)
1934
Florent Xicluna4886d242010-03-08 13:27:26 +00001935 def test_send_signal(self):
1936 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001937
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001938 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001939 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001940
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001941 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001942 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001943
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001944 def test_send_signal_dead(self):
1945 self._kill_dead_process('send_signal', signal.SIGTERM)
1946
1947 def test_kill_dead(self):
1948 self._kill_dead_process('kill')
1949
1950 def test_terminate_dead(self):
1951 self._kill_dead_process('terminate')
1952
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001953
Brett Cannona23810f2008-05-26 19:04:21 +00001954# The module says:
1955# "NB This only works (and is only relevant) for UNIX."
1956#
1957# Actually, getoutput should work on any platform with an os.popen, but
1958# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001959@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001960class CommandTests(unittest.TestCase):
1961 def test_getoutput(self):
1962 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1963 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1964 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001965
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001966 # we use mkdtemp in the next line to create an empty directory
1967 # under our exclusive control; from that, we can invent a pathname
1968 # that we _know_ won't exist. This is guaranteed to fail.
1969 dir = None
1970 try:
1971 dir = tempfile.mkdtemp()
1972 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001973
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001974 status, output = subprocess.getstatusoutput('cat ' + name)
1975 self.assertNotEqual(status, 0)
1976 finally:
1977 if dir is not None:
1978 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001979
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001980
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001981@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1982 "poll system call not supported")
1983class ProcessTestCaseNoPoll(ProcessTestCase):
1984 def setUp(self):
1985 subprocess._has_poll = False
1986 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001987
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001988 def tearDown(self):
1989 subprocess._has_poll = True
1990 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001991
1992
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001993class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001994 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001995 def test_eintr_retry_call(self):
1996 record_calls = []
1997 def fake_os_func(*args):
1998 record_calls.append(args)
1999 if len(record_calls) == 2:
2000 raise OSError(errno.EINTR, "fake interrupted system call")
2001 return tuple(reversed(args))
2002
2003 self.assertEqual((999, 256),
2004 subprocess._eintr_retry_call(fake_os_func, 256, 999))
2005 self.assertEqual([(256, 999)], record_calls)
2006 # This time there will be an EINTR so it will loop once.
2007 self.assertEqual((666,),
2008 subprocess._eintr_retry_call(fake_os_func, 666))
2009 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
2010
2011
Tim Golden126c2962010-08-11 14:20:40 +00002012@unittest.skipUnless(mswindows, "Windows-specific tests")
2013class CommandsWithSpaces (BaseTestCase):
2014
2015 def setUp(self):
2016 super().setUp()
2017 f, fname = mkstemp(".py", "te st")
2018 self.fname = fname.lower ()
2019 os.write(f, b"import sys;"
2020 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
2021 )
2022 os.close(f)
2023
2024 def tearDown(self):
2025 os.remove(self.fname)
2026 super().tearDown()
2027
2028 def with_spaces(self, *args, **kwargs):
2029 kwargs['stdout'] = subprocess.PIPE
2030 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00002031 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00002032 self.assertEqual(
2033 p.stdout.read ().decode("mbcs"),
2034 "2 [%r, 'ab cd']" % self.fname
2035 )
2036
2037 def test_shell_string_with_spaces(self):
2038 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002039 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2040 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002041
2042 def test_shell_sequence_with_spaces(self):
2043 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002044 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002045
2046 def test_noshell_string_with_spaces(self):
2047 # call() function with string argument with spaces on Windows
2048 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2049 "ab cd"))
2050
2051 def test_noshell_sequence_with_spaces(self):
2052 # call() function with sequence argument with spaces on Windows
2053 self.with_spaces([sys.executable, self.fname, "ab cd"])
2054
Brian Curtin79cdb662010-12-03 02:46:02 +00002055
Georg Brandla86b2622012-02-20 21:34:57 +01002056class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00002057
2058 def test_pipe(self):
2059 with subprocess.Popen([sys.executable, "-c",
2060 "import sys;"
2061 "sys.stdout.write('stdout');"
2062 "sys.stderr.write('stderr');"],
2063 stdout=subprocess.PIPE,
2064 stderr=subprocess.PIPE) as proc:
2065 self.assertEqual(proc.stdout.read(), b"stdout")
2066 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2067
2068 self.assertTrue(proc.stdout.closed)
2069 self.assertTrue(proc.stderr.closed)
2070
2071 def test_returncode(self):
2072 with subprocess.Popen([sys.executable, "-c",
2073 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002074 pass
2075 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002076 self.assertEqual(proc.returncode, 100)
2077
2078 def test_communicate_stdin(self):
2079 with subprocess.Popen([sys.executable, "-c",
2080 "import sys;"
2081 "sys.exit(sys.stdin.read() == 'context')"],
2082 stdin=subprocess.PIPE) as proc:
2083 proc.communicate(b"context")
2084 self.assertEqual(proc.returncode, 1)
2085
2086 def test_invalid_args(self):
2087 with self.assertRaises(EnvironmentError) as c:
2088 with subprocess.Popen(['nonexisting_i_hope'],
2089 stdout=subprocess.PIPE,
2090 stderr=subprocess.PIPE) as proc:
2091 pass
2092
2093 if c.exception.errno != errno.ENOENT: # ignore "no such file"
2094 raise c.exception
2095
2096
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002097def test_main():
2098 unit_tests = (ProcessTestCase,
2099 POSIXProcessTestCase,
2100 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002101 CommandTests,
2102 ProcessTestCaseNoPoll,
2103 HelperFunctionTests,
2104 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02002105 ContextManagerTests,
2106 )
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002107
2108 support.run_unittest(*unit_tests)
2109 support.reap_children()
2110
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002111if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002112 unittest.main()