blob: 8f5a58c68b93e47fb714df708f0cbe348a3ebd97 [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
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001041 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001042 nonexistent_dir = "/_this/pa.th/does/not/exist"
1043 try:
1044 os.chdir(nonexistent_dir)
1045 except OSError as e:
1046 # This avoids hard coding the errno value or the OS perror()
1047 # string and instead capture the exception that we want to see
1048 # below for comparison.
1049 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +00001050 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001051 else:
1052 self.fail("chdir to nonexistant directory %s succeeded." %
1053 nonexistent_dir)
1054
1055 # Error in the child re-raised in the parent.
1056 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001057 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001058 cwd=nonexistent_dir)
1059 except OSError as e:
1060 # Test that the child process chdir failure actually makes
1061 # it up to the parent process as the correct exception.
1062 self.assertEqual(desired_exception.errno, e.errno)
1063 self.assertEqual(desired_exception.strerror, e.strerror)
1064 else:
1065 self.fail("Expected OSError: %s" % desired_exception)
1066
1067 def test_restore_signals(self):
1068 # Code coverage for both values of restore_signals to make sure it
1069 # at least does not blow up.
1070 # A test for behavior would be complex. Contributions welcome.
1071 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1072 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1073
1074 def test_start_new_session(self):
1075 # For code coverage of calling setsid(). We don't care if we get an
1076 # EPERM error from it depending on the test execution environment, that
1077 # still indicates that it was called.
1078 try:
1079 output = subprocess.check_output(
1080 [sys.executable, "-c",
1081 "import os; print(os.getpgid(os.getpid()))"],
1082 start_new_session=True)
1083 except OSError as e:
1084 if e.errno != errno.EPERM:
1085 raise
1086 else:
1087 parent_pgid = os.getpgid(os.getpid())
1088 child_pgid = int(output)
1089 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001090
1091 def test_run_abort(self):
1092 # returncode handles signal termination
1093 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001094 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001095 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001096 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001097 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001098
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001099 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001100 # DISCLAIMER: Setting environment variables is *not* a good use
1101 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001102 p = subprocess.Popen([sys.executable, "-c",
1103 'import sys,os;'
1104 'sys.stdout.write(os.getenv("FRUIT"))'],
1105 stdout=subprocess.PIPE,
1106 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +00001107 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001108 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001109
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001110 def test_preexec_exception(self):
1111 def raise_it():
1112 raise ValueError("What if two swallows carried a coconut?")
1113 try:
1114 p = subprocess.Popen([sys.executable, "-c", ""],
1115 preexec_fn=raise_it)
1116 except RuntimeError as e:
1117 self.assertTrue(
1118 subprocess._posixsubprocess,
1119 "Expected a ValueError from the preexec_fn")
1120 except ValueError as e:
1121 self.assertIn("coconut", e.args[0])
1122 else:
1123 self.fail("Exception raised by preexec_fn did not make it "
1124 "to the parent process.")
1125
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001126 def test_preexec_gc_module_failure(self):
1127 # This tests the code that disables garbage collection if the child
1128 # process will execute any Python.
1129 def raise_runtime_error():
1130 raise RuntimeError("this shouldn't escape")
1131 enabled = gc.isenabled()
1132 orig_gc_disable = gc.disable
1133 orig_gc_isenabled = gc.isenabled
1134 try:
1135 gc.disable()
1136 self.assertFalse(gc.isenabled())
1137 subprocess.call([sys.executable, '-c', ''],
1138 preexec_fn=lambda: None)
1139 self.assertFalse(gc.isenabled(),
1140 "Popen enabled gc when it shouldn't.")
1141
1142 gc.enable()
1143 self.assertTrue(gc.isenabled())
1144 subprocess.call([sys.executable, '-c', ''],
1145 preexec_fn=lambda: None)
1146 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1147
1148 gc.disable = raise_runtime_error
1149 self.assertRaises(RuntimeError, subprocess.Popen,
1150 [sys.executable, '-c', ''],
1151 preexec_fn=lambda: None)
1152
1153 del gc.isenabled # force an AttributeError
1154 self.assertRaises(AttributeError, subprocess.Popen,
1155 [sys.executable, '-c', ''],
1156 preexec_fn=lambda: None)
1157 finally:
1158 gc.disable = orig_gc_disable
1159 gc.isenabled = orig_gc_isenabled
1160 if not enabled:
1161 gc.disable()
1162
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001163 def test_args_string(self):
1164 # args is a string
1165 fd, fname = mkstemp()
1166 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001167 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001168 fobj.write("#!/bin/sh\n")
1169 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1170 sys.executable)
1171 os.chmod(fname, 0o700)
1172 p = subprocess.Popen(fname)
1173 p.wait()
1174 os.remove(fname)
1175 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001176
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001177 def test_invalid_args(self):
1178 # invalid arguments should raise ValueError
1179 self.assertRaises(ValueError, subprocess.call,
1180 [sys.executable, "-c",
1181 "import sys; sys.exit(47)"],
1182 startupinfo=47)
1183 self.assertRaises(ValueError, subprocess.call,
1184 [sys.executable, "-c",
1185 "import sys; sys.exit(47)"],
1186 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001187
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001188 def test_shell_sequence(self):
1189 # Run command through the shell (sequence)
1190 newenv = os.environ.copy()
1191 newenv["FRUIT"] = "apple"
1192 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1193 stdout=subprocess.PIPE,
1194 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001195 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001196 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001197
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001198 def test_shell_string(self):
1199 # Run command through the shell (string)
1200 newenv = os.environ.copy()
1201 newenv["FRUIT"] = "apple"
1202 p = subprocess.Popen("echo $FRUIT", shell=1,
1203 stdout=subprocess.PIPE,
1204 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001205 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001206 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001207
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001208 def test_call_string(self):
1209 # call() function with string argument on UNIX
1210 fd, fname = mkstemp()
1211 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001212 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001213 fobj.write("#!/bin/sh\n")
1214 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1215 sys.executable)
1216 os.chmod(fname, 0o700)
1217 rc = subprocess.call(fname)
1218 os.remove(fname)
1219 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001220
Stefan Krah9542cc62010-07-19 14:20:53 +00001221 def test_specific_shell(self):
1222 # Issue #9265: Incorrect name passed as arg[0].
1223 shells = []
1224 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1225 for name in ['bash', 'ksh']:
1226 sh = os.path.join(prefix, name)
1227 if os.path.isfile(sh):
1228 shells.append(sh)
1229 if not shells: # Will probably work for any shell but csh.
1230 self.skipTest("bash or ksh required for this test")
1231 sh = '/bin/sh'
1232 if os.path.isfile(sh) and not os.path.islink(sh):
1233 # Test will fail if /bin/sh is a symlink to csh.
1234 shells.append(sh)
1235 for sh in shells:
1236 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1237 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001238 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001239 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1240
Florent Xicluna4886d242010-03-08 13:27:26 +00001241 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001242 # Do not inherit file handles from the parent.
1243 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001244 p = subprocess.Popen([sys.executable, "-c", """if 1:
1245 import sys, time
1246 sys.stdout.write('x\\n')
1247 sys.stdout.flush()
1248 time.sleep(30)
1249 """],
1250 close_fds=True,
1251 stdin=subprocess.PIPE,
1252 stdout=subprocess.PIPE,
1253 stderr=subprocess.PIPE)
1254 # Wait for the interpreter to be completely initialized before
1255 # sending any signal.
1256 p.stdout.read(1)
1257 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001258 return p
1259
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001260 def _kill_dead_process(self, method, *args):
1261 # Do not inherit file handles from the parent.
1262 # It should fix failures on some platforms.
1263 p = subprocess.Popen([sys.executable, "-c", """if 1:
1264 import sys, time
1265 sys.stdout.write('x\\n')
1266 sys.stdout.flush()
1267 """],
1268 close_fds=True,
1269 stdin=subprocess.PIPE,
1270 stdout=subprocess.PIPE,
1271 stderr=subprocess.PIPE)
1272 # Wait for the interpreter to be completely initialized before
1273 # sending any signal.
1274 p.stdout.read(1)
1275 # The process should end after this
1276 time.sleep(1)
1277 # This shouldn't raise even though the child is now dead
1278 getattr(p, method)(*args)
1279 p.communicate()
1280
Florent Xicluna4886d242010-03-08 13:27:26 +00001281 def test_send_signal(self):
1282 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001283 _, stderr = p.communicate()
1284 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001285 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001286
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001287 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001288 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001289 _, stderr = p.communicate()
1290 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001291 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001292
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001293 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001294 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001295 _, stderr = p.communicate()
1296 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001297 self.assertEqual(p.wait(), -signal.SIGTERM)
1298
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001299 def test_send_signal_dead(self):
1300 # Sending a signal to a dead process
1301 self._kill_dead_process('send_signal', signal.SIGINT)
1302
1303 def test_kill_dead(self):
1304 # Killing a dead process
1305 self._kill_dead_process('kill')
1306
1307 def test_terminate_dead(self):
1308 # Terminating a dead process
1309 self._kill_dead_process('terminate')
1310
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001311 def check_close_std_fds(self, fds):
1312 # Issue #9905: test that subprocess pipes still work properly with
1313 # some standard fds closed
1314 stdin = 0
1315 newfds = []
1316 for a in fds:
1317 b = os.dup(a)
1318 newfds.append(b)
1319 if a == 0:
1320 stdin = b
1321 try:
1322 for fd in fds:
1323 os.close(fd)
1324 out, err = subprocess.Popen([sys.executable, "-c",
1325 'import sys;'
1326 'sys.stdout.write("apple");'
1327 'sys.stdout.flush();'
1328 'sys.stderr.write("orange")'],
1329 stdin=stdin,
1330 stdout=subprocess.PIPE,
1331 stderr=subprocess.PIPE).communicate()
1332 err = support.strip_python_stderr(err)
1333 self.assertEqual((out, err), (b'apple', b'orange'))
1334 finally:
1335 for b, a in zip(newfds, fds):
1336 os.dup2(b, a)
1337 for b in newfds:
1338 os.close(b)
1339
1340 def test_close_fd_0(self):
1341 self.check_close_std_fds([0])
1342
1343 def test_close_fd_1(self):
1344 self.check_close_std_fds([1])
1345
1346 def test_close_fd_2(self):
1347 self.check_close_std_fds([2])
1348
1349 def test_close_fds_0_1(self):
1350 self.check_close_std_fds([0, 1])
1351
1352 def test_close_fds_0_2(self):
1353 self.check_close_std_fds([0, 2])
1354
1355 def test_close_fds_1_2(self):
1356 self.check_close_std_fds([1, 2])
1357
1358 def test_close_fds_0_1_2(self):
1359 # Issue #10806: test that subprocess pipes still work properly with
1360 # all standard fds closed.
1361 self.check_close_std_fds([0, 1, 2])
1362
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001363 def test_remapping_std_fds(self):
1364 # open up some temporary files
1365 temps = [mkstemp() for i in range(3)]
1366 try:
1367 temp_fds = [fd for fd, fname in temps]
1368
1369 # unlink the files -- we won't need to reopen them
1370 for fd, fname in temps:
1371 os.unlink(fname)
1372
1373 # write some data to what will become stdin, and rewind
1374 os.write(temp_fds[1], b"STDIN")
1375 os.lseek(temp_fds[1], 0, 0)
1376
1377 # move the standard file descriptors out of the way
1378 saved_fds = [os.dup(fd) for fd in range(3)]
1379 try:
1380 # duplicate the file objects over the standard fd's
1381 for fd, temp_fd in enumerate(temp_fds):
1382 os.dup2(temp_fd, fd)
1383
1384 # now use those files in the "wrong" order, so that subprocess
1385 # has to rearrange them in the child
1386 p = subprocess.Popen([sys.executable, "-c",
1387 'import sys; got = sys.stdin.read();'
1388 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1389 stdin=temp_fds[1],
1390 stdout=temp_fds[2],
1391 stderr=temp_fds[0])
1392 p.wait()
1393 finally:
1394 # restore the original fd's underneath sys.stdin, etc.
1395 for std, saved in enumerate(saved_fds):
1396 os.dup2(saved, std)
1397 os.close(saved)
1398
1399 for fd in temp_fds:
1400 os.lseek(fd, 0, 0)
1401
1402 out = os.read(temp_fds[2], 1024)
1403 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1404 self.assertEqual(out, b"got STDIN")
1405 self.assertEqual(err, b"err")
1406
1407 finally:
1408 for fd in temp_fds:
1409 os.close(fd)
1410
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001411 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1412 # open up some temporary files
1413 temps = [mkstemp() for i in range(3)]
1414 temp_fds = [fd for fd, fname in temps]
1415 try:
1416 # unlink the files -- we won't need to reopen them
1417 for fd, fname in temps:
1418 os.unlink(fname)
1419
1420 # save a copy of the standard file descriptors
1421 saved_fds = [os.dup(fd) for fd in range(3)]
1422 try:
1423 # duplicate the temp files over the standard fd's 0, 1, 2
1424 for fd, temp_fd in enumerate(temp_fds):
1425 os.dup2(temp_fd, fd)
1426
1427 # write some data to what will become stdin, and rewind
1428 os.write(stdin_no, b"STDIN")
1429 os.lseek(stdin_no, 0, 0)
1430
1431 # now use those files in the given order, so that subprocess
1432 # has to rearrange them in the child
1433 p = subprocess.Popen([sys.executable, "-c",
1434 'import sys; got = sys.stdin.read();'
1435 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1436 stdin=stdin_no,
1437 stdout=stdout_no,
1438 stderr=stderr_no)
1439 p.wait()
1440
1441 for fd in temp_fds:
1442 os.lseek(fd, 0, 0)
1443
1444 out = os.read(stdout_no, 1024)
1445 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1446 finally:
1447 for std, saved in enumerate(saved_fds):
1448 os.dup2(saved, std)
1449 os.close(saved)
1450
1451 self.assertEqual(out, b"got STDIN")
1452 self.assertEqual(err, b"err")
1453
1454 finally:
1455 for fd in temp_fds:
1456 os.close(fd)
1457
1458 # When duping fds, if there arises a situation where one of the fds is
1459 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1460 # This tests all combinations of this.
1461 def test_swap_fds(self):
1462 self.check_swap_fds(0, 1, 2)
1463 self.check_swap_fds(0, 2, 1)
1464 self.check_swap_fds(1, 0, 2)
1465 self.check_swap_fds(1, 2, 0)
1466 self.check_swap_fds(2, 0, 1)
1467 self.check_swap_fds(2, 1, 0)
1468
Victor Stinner13bb71c2010-04-23 21:41:56 +00001469 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001470 def prepare():
1471 raise ValueError("surrogate:\uDCff")
1472
1473 try:
1474 subprocess.call(
1475 [sys.executable, "-c", "pass"],
1476 preexec_fn=prepare)
1477 except ValueError as err:
1478 # Pure Python implementations keeps the message
1479 self.assertIsNone(subprocess._posixsubprocess)
1480 self.assertEqual(str(err), "surrogate:\uDCff")
1481 except RuntimeError as err:
1482 # _posixsubprocess uses a default message
1483 self.assertIsNotNone(subprocess._posixsubprocess)
1484 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1485 else:
1486 self.fail("Expected ValueError or RuntimeError")
1487
Victor Stinner13bb71c2010-04-23 21:41:56 +00001488 def test_undecodable_env(self):
1489 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001490 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001491 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001492 env = os.environ.copy()
1493 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001494 # Use C locale to get ascii for the locale encoding to force
1495 # surrogate-escaping of \xFF in the child process; otherwise it can
1496 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001497 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001498 stdout = subprocess.check_output(
1499 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001500 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001501 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001502 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001503
1504 # test bytes
1505 key = key.encode("ascii", "surrogateescape")
1506 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001507 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001508 env = os.environ.copy()
1509 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001510 stdout = subprocess.check_output(
1511 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001512 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001513 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001514 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001515
Victor Stinnerb745a742010-05-18 17:17:23 +00001516 def test_bytes_program(self):
1517 abs_program = os.fsencode(sys.executable)
1518 path, program = os.path.split(sys.executable)
1519 program = os.fsencode(program)
1520
1521 # absolute bytes path
1522 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001523 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001524
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001525 # absolute bytes path as a string
1526 cmd = b"'" + abs_program + b"' -c pass"
1527 exitcode = subprocess.call(cmd, shell=True)
1528 self.assertEqual(exitcode, 0)
1529
Victor Stinnerb745a742010-05-18 17:17:23 +00001530 # bytes program, unicode PATH
1531 env = os.environ.copy()
1532 env["PATH"] = path
1533 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001534 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001535
1536 # bytes program, bytes PATH
1537 envb = os.environb.copy()
1538 envb[b"PATH"] = os.fsencode(path)
1539 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001540 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001541
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001542 def test_pipe_cloexec(self):
1543 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1544 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1545
1546 p1 = subprocess.Popen([sys.executable, sleeper],
1547 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1548 stderr=subprocess.PIPE, close_fds=False)
1549
1550 self.addCleanup(p1.communicate, b'')
1551
1552 p2 = subprocess.Popen([sys.executable, fd_status],
1553 stdout=subprocess.PIPE, close_fds=False)
1554
1555 output, error = p2.communicate()
1556 result_fds = set(map(int, output.split(b',')))
1557 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1558 p1.stderr.fileno()])
1559
1560 self.assertFalse(result_fds & unwanted_fds,
1561 "Expected no fds from %r to be open in child, "
1562 "found %r" %
1563 (unwanted_fds, result_fds & unwanted_fds))
1564
1565 def test_pipe_cloexec_real_tools(self):
1566 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1567 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1568
1569 subdata = b'zxcvbn'
1570 data = subdata * 4 + b'\n'
1571
1572 p1 = subprocess.Popen([sys.executable, qcat],
1573 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1574 close_fds=False)
1575
1576 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1577 stdin=p1.stdout, stdout=subprocess.PIPE,
1578 close_fds=False)
1579
1580 self.addCleanup(p1.wait)
1581 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001582 def kill_p1():
1583 try:
1584 p1.terminate()
1585 except ProcessLookupError:
1586 pass
1587 def kill_p2():
1588 try:
1589 p2.terminate()
1590 except ProcessLookupError:
1591 pass
1592 self.addCleanup(kill_p1)
1593 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001594
1595 p1.stdin.write(data)
1596 p1.stdin.close()
1597
1598 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1599
1600 self.assertTrue(readfiles, "The child hung")
1601 self.assertEqual(p2.stdout.read(), data)
1602
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001603 p1.stdout.close()
1604 p2.stdout.close()
1605
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001606 def test_close_fds(self):
1607 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1608
1609 fds = os.pipe()
1610 self.addCleanup(os.close, fds[0])
1611 self.addCleanup(os.close, fds[1])
1612
1613 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001614 # add a bunch more fds
1615 for _ in range(9):
1616 fd = os.open("/dev/null", os.O_RDONLY)
1617 self.addCleanup(os.close, fd)
1618 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001619
1620 p = subprocess.Popen([sys.executable, fd_status],
1621 stdout=subprocess.PIPE, close_fds=False)
1622 output, ignored = p.communicate()
1623 remaining_fds = set(map(int, output.split(b',')))
1624
1625 self.assertEqual(remaining_fds & open_fds, open_fds,
1626 "Some fds were closed")
1627
1628 p = subprocess.Popen([sys.executable, fd_status],
1629 stdout=subprocess.PIPE, close_fds=True)
1630 output, ignored = p.communicate()
1631 remaining_fds = set(map(int, output.split(b',')))
1632
1633 self.assertFalse(remaining_fds & open_fds,
1634 "Some fds were left open")
1635 self.assertIn(1, remaining_fds, "Subprocess failed")
1636
Gregory P. Smith8facece2012-01-21 14:01:08 -08001637 # Keep some of the fd's we opened open in the subprocess.
1638 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1639 fds_to_keep = set(open_fds.pop() for _ in range(8))
1640 p = subprocess.Popen([sys.executable, fd_status],
1641 stdout=subprocess.PIPE, close_fds=True,
1642 pass_fds=())
1643 output, ignored = p.communicate()
1644 remaining_fds = set(map(int, output.split(b',')))
1645
1646 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1647 "Some fds not in pass_fds were left open")
1648 self.assertIn(1, remaining_fds, "Subprocess failed")
1649
Victor Stinner88701e22011-06-01 13:13:04 +02001650 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1651 # descriptor of a pipe closed in the parent process is valid in the
1652 # child process according to fstat(), but the mode of the file
1653 # descriptor is invalid, and read or write raise an error.
1654 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001655 def test_pass_fds(self):
1656 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1657
1658 open_fds = set()
1659
1660 for x in range(5):
1661 fds = os.pipe()
1662 self.addCleanup(os.close, fds[0])
1663 self.addCleanup(os.close, fds[1])
1664 open_fds.update(fds)
1665
1666 for fd in open_fds:
1667 p = subprocess.Popen([sys.executable, fd_status],
1668 stdout=subprocess.PIPE, close_fds=True,
1669 pass_fds=(fd, ))
1670 output, ignored = p.communicate()
1671
1672 remaining_fds = set(map(int, output.split(b',')))
1673 to_be_closed = open_fds - {fd}
1674
1675 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1676 self.assertFalse(remaining_fds & to_be_closed,
1677 "fd to be closed passed")
1678
1679 # pass_fds overrides close_fds with a warning.
1680 with self.assertWarns(RuntimeWarning) as context:
1681 self.assertFalse(subprocess.call(
1682 [sys.executable, "-c", "import sys; sys.exit(0)"],
1683 close_fds=False, pass_fds=(fd, )))
1684 self.assertIn('overriding close_fds', str(context.warning))
1685
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001686 def test_stdout_stdin_are_single_inout_fd(self):
1687 with io.open(os.devnull, "r+") as inout:
1688 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1689 stdout=inout, stdin=inout)
1690 p.wait()
1691
1692 def test_stdout_stderr_are_single_inout_fd(self):
1693 with io.open(os.devnull, "r+") as inout:
1694 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1695 stdout=inout, stderr=inout)
1696 p.wait()
1697
1698 def test_stderr_stdin_are_single_inout_fd(self):
1699 with io.open(os.devnull, "r+") as inout:
1700 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1701 stderr=inout, stdin=inout)
1702 p.wait()
1703
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001704 def test_wait_when_sigchild_ignored(self):
1705 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1706 sigchild_ignore = support.findfile("sigchild_ignore.py",
1707 subdir="subprocessdata")
1708 p = subprocess.Popen([sys.executable, sigchild_ignore],
1709 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1710 stdout, stderr = p.communicate()
1711 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001712 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001713 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001714
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001715 def test_select_unbuffered(self):
1716 # Issue #11459: bufsize=0 should really set the pipes as
1717 # unbuffered (and therefore let select() work properly).
1718 select = support.import_module("select")
1719 p = subprocess.Popen([sys.executable, "-c",
1720 'import sys;'
1721 'sys.stdout.write("apple")'],
1722 stdout=subprocess.PIPE,
1723 bufsize=0)
1724 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001725 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001726 try:
1727 self.assertEqual(f.read(4), b"appl")
1728 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1729 finally:
1730 p.wait()
1731
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001732 def test_zombie_fast_process_del(self):
1733 # Issue #12650: on Unix, if Popen.__del__() was called before the
1734 # process exited, it wouldn't be added to subprocess._active, and would
1735 # remain a zombie.
1736 # spawn a Popen, and delete its reference before it exits
1737 p = subprocess.Popen([sys.executable, "-c",
1738 'import sys, time;'
1739 'time.sleep(0.2)'],
1740 stdout=subprocess.PIPE,
1741 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001742 self.addCleanup(p.stdout.close)
1743 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001744 ident = id(p)
1745 pid = p.pid
1746 del p
1747 # check that p is in the active processes list
1748 self.assertIn(ident, [id(o) for o in subprocess._active])
1749
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001750 def test_leak_fast_process_del_killed(self):
1751 # Issue #12650: on Unix, if Popen.__del__() was called before the
1752 # process exited, and the process got killed by a signal, it would never
1753 # be removed from subprocess._active, which triggered a FD and memory
1754 # leak.
1755 # spawn a Popen, delete its reference and kill it
1756 p = subprocess.Popen([sys.executable, "-c",
1757 'import time;'
1758 'time.sleep(3)'],
1759 stdout=subprocess.PIPE,
1760 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001761 self.addCleanup(p.stdout.close)
1762 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001763 ident = id(p)
1764 pid = p.pid
1765 del p
1766 os.kill(pid, signal.SIGKILL)
1767 # check that p is in the active processes list
1768 self.assertIn(ident, [id(o) for o in subprocess._active])
1769
1770 # let some time for the process to exit, and create a new Popen: this
1771 # should trigger the wait() of p
1772 time.sleep(0.2)
1773 with self.assertRaises(EnvironmentError) as c:
1774 with subprocess.Popen(['nonexisting_i_hope'],
1775 stdout=subprocess.PIPE,
1776 stderr=subprocess.PIPE) as proc:
1777 pass
1778 # p should have been wait()ed on, and removed from the _active list
1779 self.assertRaises(OSError, os.waitpid, pid, 0)
1780 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1781
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001782
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001783@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001784class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001785
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001786 def test_startupinfo(self):
1787 # startupinfo argument
1788 # We uses hardcoded constants, because we do not want to
1789 # depend on win32all.
1790 STARTF_USESHOWWINDOW = 1
1791 SW_MAXIMIZE = 3
1792 startupinfo = subprocess.STARTUPINFO()
1793 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1794 startupinfo.wShowWindow = SW_MAXIMIZE
1795 # Since Python is a console process, it won't be affected
1796 # by wShowWindow, but the argument should be silently
1797 # ignored
1798 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001799 startupinfo=startupinfo)
1800
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001801 def test_creationflags(self):
1802 # creationflags argument
1803 CREATE_NEW_CONSOLE = 16
1804 sys.stderr.write(" a DOS box should flash briefly ...\n")
1805 subprocess.call(sys.executable +
1806 ' -c "import time; time.sleep(0.25)"',
1807 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001808
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001809 def test_invalid_args(self):
1810 # invalid arguments should raise ValueError
1811 self.assertRaises(ValueError, subprocess.call,
1812 [sys.executable, "-c",
1813 "import sys; sys.exit(47)"],
1814 preexec_fn=lambda: 1)
1815 self.assertRaises(ValueError, subprocess.call,
1816 [sys.executable, "-c",
1817 "import sys; sys.exit(47)"],
1818 stdout=subprocess.PIPE,
1819 close_fds=True)
1820
1821 def test_close_fds(self):
1822 # close file descriptors
1823 rc = subprocess.call([sys.executable, "-c",
1824 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001825 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001826 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001827
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001828 def test_shell_sequence(self):
1829 # Run command through the shell (sequence)
1830 newenv = os.environ.copy()
1831 newenv["FRUIT"] = "physalis"
1832 p = subprocess.Popen(["set"], shell=1,
1833 stdout=subprocess.PIPE,
1834 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001835 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001836 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001837
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001838 def test_shell_string(self):
1839 # Run command through the shell (string)
1840 newenv = os.environ.copy()
1841 newenv["FRUIT"] = "physalis"
1842 p = subprocess.Popen("set", shell=1,
1843 stdout=subprocess.PIPE,
1844 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001845 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001846 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001847
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001848 def test_call_string(self):
1849 # call() function with string argument on Windows
1850 rc = subprocess.call(sys.executable +
1851 ' -c "import sys; sys.exit(47)"')
1852 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001853
Florent Xicluna4886d242010-03-08 13:27:26 +00001854 def _kill_process(self, method, *args):
1855 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001856 p = subprocess.Popen([sys.executable, "-c", """if 1:
1857 import sys, time
1858 sys.stdout.write('x\\n')
1859 sys.stdout.flush()
1860 time.sleep(30)
1861 """],
1862 stdin=subprocess.PIPE,
1863 stdout=subprocess.PIPE,
1864 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001865 self.addCleanup(p.stdout.close)
1866 self.addCleanup(p.stderr.close)
1867 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001868 # Wait for the interpreter to be completely initialized before
1869 # sending any signal.
1870 p.stdout.read(1)
1871 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001872 _, stderr = p.communicate()
1873 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001874 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001875 self.assertNotEqual(returncode, 0)
1876
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001877 def _kill_dead_process(self, method, *args):
1878 p = subprocess.Popen([sys.executable, "-c", """if 1:
1879 import sys, time
1880 sys.stdout.write('x\\n')
1881 sys.stdout.flush()
1882 sys.exit(42)
1883 """],
1884 stdin=subprocess.PIPE,
1885 stdout=subprocess.PIPE,
1886 stderr=subprocess.PIPE)
1887 self.addCleanup(p.stdout.close)
1888 self.addCleanup(p.stderr.close)
1889 self.addCleanup(p.stdin.close)
1890 # Wait for the interpreter to be completely initialized before
1891 # sending any signal.
1892 p.stdout.read(1)
1893 # The process should end after this
1894 time.sleep(1)
1895 # This shouldn't raise even though the child is now dead
1896 getattr(p, method)(*args)
1897 _, stderr = p.communicate()
1898 self.assertStderrEqual(stderr, b'')
1899 rc = p.wait()
1900 self.assertEqual(rc, 42)
1901
Florent Xicluna4886d242010-03-08 13:27:26 +00001902 def test_send_signal(self):
1903 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001904
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001905 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001906 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001907
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001908 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001909 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001910
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001911 def test_send_signal_dead(self):
1912 self._kill_dead_process('send_signal', signal.SIGTERM)
1913
1914 def test_kill_dead(self):
1915 self._kill_dead_process('kill')
1916
1917 def test_terminate_dead(self):
1918 self._kill_dead_process('terminate')
1919
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001920
Brett Cannona23810f2008-05-26 19:04:21 +00001921# The module says:
1922# "NB This only works (and is only relevant) for UNIX."
1923#
1924# Actually, getoutput should work on any platform with an os.popen, but
1925# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001926@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001927class CommandTests(unittest.TestCase):
1928 def test_getoutput(self):
1929 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1930 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1931 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001932
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001933 # we use mkdtemp in the next line to create an empty directory
1934 # under our exclusive control; from that, we can invent a pathname
1935 # that we _know_ won't exist. This is guaranteed to fail.
1936 dir = None
1937 try:
1938 dir = tempfile.mkdtemp()
1939 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001940
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001941 status, output = subprocess.getstatusoutput('cat ' + name)
1942 self.assertNotEqual(status, 0)
1943 finally:
1944 if dir is not None:
1945 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001946
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001947
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001948@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1949 "poll system call not supported")
1950class ProcessTestCaseNoPoll(ProcessTestCase):
1951 def setUp(self):
1952 subprocess._has_poll = False
1953 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001954
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001955 def tearDown(self):
1956 subprocess._has_poll = True
1957 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001958
1959
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001960class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001961 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001962 def test_eintr_retry_call(self):
1963 record_calls = []
1964 def fake_os_func(*args):
1965 record_calls.append(args)
1966 if len(record_calls) == 2:
1967 raise OSError(errno.EINTR, "fake interrupted system call")
1968 return tuple(reversed(args))
1969
1970 self.assertEqual((999, 256),
1971 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1972 self.assertEqual([(256, 999)], record_calls)
1973 # This time there will be an EINTR so it will loop once.
1974 self.assertEqual((666,),
1975 subprocess._eintr_retry_call(fake_os_func, 666))
1976 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1977
1978
Tim Golden126c2962010-08-11 14:20:40 +00001979@unittest.skipUnless(mswindows, "Windows-specific tests")
1980class CommandsWithSpaces (BaseTestCase):
1981
1982 def setUp(self):
1983 super().setUp()
1984 f, fname = mkstemp(".py", "te st")
1985 self.fname = fname.lower ()
1986 os.write(f, b"import sys;"
1987 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1988 )
1989 os.close(f)
1990
1991 def tearDown(self):
1992 os.remove(self.fname)
1993 super().tearDown()
1994
1995 def with_spaces(self, *args, **kwargs):
1996 kwargs['stdout'] = subprocess.PIPE
1997 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001998 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001999 self.assertEqual(
2000 p.stdout.read ().decode("mbcs"),
2001 "2 [%r, 'ab cd']" % self.fname
2002 )
2003
2004 def test_shell_string_with_spaces(self):
2005 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002006 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2007 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002008
2009 def test_shell_sequence_with_spaces(self):
2010 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002011 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002012
2013 def test_noshell_string_with_spaces(self):
2014 # call() function with string argument with spaces on Windows
2015 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2016 "ab cd"))
2017
2018 def test_noshell_sequence_with_spaces(self):
2019 # call() function with sequence argument with spaces on Windows
2020 self.with_spaces([sys.executable, self.fname, "ab cd"])
2021
Brian Curtin79cdb662010-12-03 02:46:02 +00002022
Georg Brandla86b2622012-02-20 21:34:57 +01002023class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00002024
2025 def test_pipe(self):
2026 with subprocess.Popen([sys.executable, "-c",
2027 "import sys;"
2028 "sys.stdout.write('stdout');"
2029 "sys.stderr.write('stderr');"],
2030 stdout=subprocess.PIPE,
2031 stderr=subprocess.PIPE) as proc:
2032 self.assertEqual(proc.stdout.read(), b"stdout")
2033 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2034
2035 self.assertTrue(proc.stdout.closed)
2036 self.assertTrue(proc.stderr.closed)
2037
2038 def test_returncode(self):
2039 with subprocess.Popen([sys.executable, "-c",
2040 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002041 pass
2042 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002043 self.assertEqual(proc.returncode, 100)
2044
2045 def test_communicate_stdin(self):
2046 with subprocess.Popen([sys.executable, "-c",
2047 "import sys;"
2048 "sys.exit(sys.stdin.read() == 'context')"],
2049 stdin=subprocess.PIPE) as proc:
2050 proc.communicate(b"context")
2051 self.assertEqual(proc.returncode, 1)
2052
2053 def test_invalid_args(self):
2054 with self.assertRaises(EnvironmentError) as c:
2055 with subprocess.Popen(['nonexisting_i_hope'],
2056 stdout=subprocess.PIPE,
2057 stderr=subprocess.PIPE) as proc:
2058 pass
2059
2060 if c.exception.errno != errno.ENOENT: # ignore "no such file"
2061 raise c.exception
2062
2063
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002064def test_main():
2065 unit_tests = (ProcessTestCase,
2066 POSIXProcessTestCase,
2067 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002068 CommandTests,
2069 ProcessTestCaseNoPoll,
2070 HelperFunctionTests,
2071 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02002072 ContextManagerTests,
2073 )
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002074
2075 support.run_unittest(*unit_tests)
2076 support.reap_children()
2077
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002078if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002079 unittest.main()