blob: d18784caa3dc5c8e7957c12772563d05851652e3 [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
Gregory P. Smith3d8e7762012-11-10 22:32:22 -080071class PopenTestException(Exception):
72 pass
73
74
75class PopenExecuteChildRaises(subprocess.Popen):
76 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
77 _execute_child fails.
78 """
79 def _execute_child(self, *args, **kwargs):
80 raise PopenTestException("Forced Exception for Test")
81
82
Florent Xiclunac049d872010-03-27 22:47:23 +000083class ProcessTestCase(BaseTestCase):
84
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000085 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000086 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000087 rc = subprocess.call([sys.executable, "-c",
88 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000089 self.assertEqual(rc, 47)
90
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040091 def test_call_timeout(self):
92 # call() function with timeout argument; we want to test that the child
93 # process gets killed when the timeout expires. If the child isn't
94 # killed, this call will deadlock since subprocess.call waits for the
95 # child.
96 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
97 [sys.executable, "-c", "while True: pass"],
98 timeout=0.1)
99
Peter Astrand454f7672005-01-01 09:36:35 +0000100 def test_check_call_zero(self):
101 # check_call() function with zero return code
102 rc = subprocess.check_call([sys.executable, "-c",
103 "import sys; sys.exit(0)"])
104 self.assertEqual(rc, 0)
105
106 def test_check_call_nonzero(self):
107 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000108 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +0000109 subprocess.check_call([sys.executable, "-c",
110 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000111 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000112
Georg Brandlf9734072008-12-07 15:30:06 +0000113 def test_check_output(self):
114 # check_output() function with zero return code
115 output = subprocess.check_output(
116 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000117 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000118
119 def test_check_output_nonzero(self):
120 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000121 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000122 subprocess.check_output(
123 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000124 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000125
126 def test_check_output_stderr(self):
127 # check_output() function stderr redirected to stdout
128 output = subprocess.check_output(
129 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
130 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000131 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000132
133 def test_check_output_stdout_arg(self):
134 # check_output() function stderr redirected to stdout
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000135 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000136 output = subprocess.check_output(
137 [sys.executable, "-c", "print('will not be run')"],
138 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000139 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000140 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000141
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400142 def test_check_output_timeout(self):
143 # check_output() function with timeout arg
144 with self.assertRaises(subprocess.TimeoutExpired) as c:
145 output = subprocess.check_output(
146 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200147 "import sys, time\n"
148 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400149 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200150 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400151 # Some heavily loaded buildbots (sparc Debian 3.x) require
152 # this much time to start and print.
153 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400154 self.fail("Expected TimeoutExpired.")
155 self.assertEqual(c.exception.output, b'BDFL')
156
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000157 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000158 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000159 newenv = os.environ.copy()
160 newenv["FRUIT"] = "banana"
161 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000162 'import sys, os;'
163 'sys.exit(os.getenv("FRUIT")=="banana")'],
164 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000165 self.assertEqual(rc, 1)
166
Victor Stinner87b9bc32011-06-01 00:57:47 +0200167 def test_invalid_args(self):
168 # Popen() called with invalid arguments should raise TypeError
169 # but Popen.__del__ should not complain (issue #12085)
170 with support.captured_stderr() as s:
171 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
172 argcount = subprocess.Popen.__init__.__code__.co_argcount
173 too_many_args = [0] * (argcount + 1)
174 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
175 self.assertEqual(s.getvalue(), '')
176
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000177 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000178 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000179 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000180 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000181 self.addCleanup(p.stdout.close)
182 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000183 p.wait()
184 self.assertEqual(p.stdin, None)
185
186 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000187 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000188 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000189 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000190 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000191 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000192 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000193 self.addCleanup(p.stdin.close)
194 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000195 p.wait()
196 self.assertEqual(p.stdout, None)
197
198 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000199 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000200 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000201 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000202 self.addCleanup(p.stdout.close)
203 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000204 p.wait()
205 self.assertEqual(p.stderr, None)
206
Chris Jerdonek776cb192012-10-08 15:56:43 -0700207 def _assert_python(self, pre_args, **kwargs):
208 # We include sys.exit() to prevent the test runner from hanging
209 # whenever python is found.
210 args = pre_args + ["import sys; sys.exit(47)"]
211 p = subprocess.Popen(args, **kwargs)
212 p.wait()
213 self.assertEqual(47, p.returncode)
214
215 def test_executable(self):
216 # Check that the executable argument works.
Chris Jerdonek86b0fb22012-10-09 13:17:49 -0700217 #
218 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
219 # determine where its standard library is, so we need the directory
220 # of args[0] to be valid for the Popen() call to Python to succeed.
221 # See also issue #16170 and issue #7774.
222 doesnotexist = os.path.join(os.path.dirname(sys.executable),
223 "doesnotexist")
224 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
Chris Jerdonek776cb192012-10-08 15:56:43 -0700225
226 def test_executable_takes_precedence(self):
227 # Check that the executable argument takes precedence over args[0].
228 #
229 # Verify first that the call succeeds without the executable arg.
230 pre_args = [sys.executable, "-c"]
231 self._assert_python(pre_args)
232 self.assertRaises(FileNotFoundError, self._assert_python, pre_args,
233 executable="doesnotexist")
234
235 @unittest.skipIf(mswindows, "executable argument replaces shell")
236 def test_executable_replaces_shell(self):
237 # Check that the executable argument replaces the default shell
238 # when shell=True.
239 self._assert_python([], executable=sys.executable, shell=True)
240
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700241 # For use in the test_cwd* tests below.
242 def _normalize_cwd(self, cwd):
243 # Normalize an expected cwd (for Tru64 support).
244 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
245 # strings. See bug #1063571.
246 original_cwd = os.getcwd()
247 os.chdir(cwd)
248 cwd = os.getcwd()
249 os.chdir(original_cwd)
250 return cwd
251
252 # For use in the test_cwd* tests below.
253 def _split_python_path(self):
254 # Return normalized (python_dir, python_base).
255 python_path = os.path.realpath(sys.executable)
256 return os.path.split(python_path)
257
258 # For use in the test_cwd* tests below.
259 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
260 # Invoke Python via Popen, and assert that (1) the call succeeds,
261 # and that (2) the current working directory of the child process
262 # matches *expected_cwd*.
263 p = subprocess.Popen([python_arg, "-c",
264 "import os, sys; "
265 "sys.stdout.write(os.getcwd()); "
266 "sys.exit(47)"],
267 stdout=subprocess.PIPE,
268 **kwargs)
269 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000270 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700271 self.assertEqual(47, p.returncode)
272 normcase = os.path.normcase
273 self.assertEqual(normcase(expected_cwd),
274 normcase(p.stdout.read().decode("utf-8")))
275
276 def test_cwd(self):
277 # Check that cwd changes the cwd for the child process.
278 temp_dir = tempfile.gettempdir()
279 temp_dir = self._normalize_cwd(temp_dir)
280 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
281
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700282 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700283 def test_cwd_with_relative_arg(self):
284 # Check that Popen looks for args[0] relative to cwd if args[0]
285 # is relative.
286 python_dir, python_base = self._split_python_path()
287 rel_python = os.path.join(os.curdir, python_base)
288 with support.temp_cwd() as wrong_dir:
289 # Before calling with the correct cwd, confirm that the call fails
290 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700291 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700292 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700293 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700294 [rel_python], cwd=wrong_dir)
295 python_dir = self._normalize_cwd(python_dir)
296 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
297
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700298 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700299 def test_cwd_with_relative_executable(self):
300 # Check that Popen looks for executable relative to cwd if executable
301 # is relative (and that executable takes precedence over args[0]).
302 python_dir, python_base = self._split_python_path()
303 rel_python = os.path.join(os.curdir, python_base)
304 doesntexist = "somethingyoudonthave"
305 with support.temp_cwd() as wrong_dir:
306 # Before calling with the correct cwd, confirm that the call fails
307 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700308 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700309 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700310 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700311 [doesntexist], executable=rel_python,
312 cwd=wrong_dir)
313 python_dir = self._normalize_cwd(python_dir)
314 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
315 cwd=python_dir)
316
317 def test_cwd_with_absolute_arg(self):
318 # Check that Popen can find the executable when the cwd is wrong
319 # if args[0] is an absolute path.
320 python_dir, python_base = self._split_python_path()
321 abs_python = os.path.join(python_dir, python_base)
322 rel_python = os.path.join(os.curdir, python_base)
323 with script_helper.temp_dir() as wrong_dir:
324 # Before calling with an absolute path, confirm that using a
325 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700326 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700327 [rel_python], cwd=wrong_dir)
328 wrong_dir = self._normalize_cwd(wrong_dir)
329 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
330
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100331 @unittest.skipIf(sys.base_prefix != sys.prefix,
332 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000333 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700334 python_dir, python_base = self._split_python_path()
335 python_dir = self._normalize_cwd(python_dir)
336 self._assert_cwd(python_dir, "somethingyoudonthave",
337 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000338
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100339 @unittest.skipIf(sys.base_prefix != sys.prefix,
340 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000341 @unittest.skipIf(sysconfig.is_python_build(),
342 "need an installed Python. See #7774")
343 def test_executable_without_cwd(self):
344 # For a normal installation, it should work without 'cwd'
345 # argument. For test runs in the build directory, see #7774.
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700346 self._assert_cwd('', "somethingyoudonthave", executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000347
348 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000349 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000350 p = subprocess.Popen([sys.executable, "-c",
351 'import sys; sys.exit(sys.stdin.read() == "pear")'],
352 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000353 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000354 p.stdin.close()
355 p.wait()
356 self.assertEqual(p.returncode, 1)
357
358 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000359 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000360 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000361 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000362 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000363 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000364 os.lseek(d, 0, 0)
365 p = subprocess.Popen([sys.executable, "-c",
366 'import sys; sys.exit(sys.stdin.read() == "pear")'],
367 stdin=d)
368 p.wait()
369 self.assertEqual(p.returncode, 1)
370
371 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000372 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000373 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000374 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000375 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000376 tf.seek(0)
377 p = subprocess.Popen([sys.executable, "-c",
378 'import sys; sys.exit(sys.stdin.read() == "pear")'],
379 stdin=tf)
380 p.wait()
381 self.assertEqual(p.returncode, 1)
382
383 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000384 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000385 p = subprocess.Popen([sys.executable, "-c",
386 'import sys; sys.stdout.write("orange")'],
387 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000388 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000389 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000390
391 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000392 # stdout is set to open file descriptor
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 d = tf.fileno()
396 p = subprocess.Popen([sys.executable, "-c",
397 'import sys; sys.stdout.write("orange")'],
398 stdout=d)
399 p.wait()
400 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000401 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000402
403 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000404 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000405 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000406 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000407 p = subprocess.Popen([sys.executable, "-c",
408 'import sys; sys.stdout.write("orange")'],
409 stdout=tf)
410 p.wait()
411 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000412 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000413
414 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000415 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000416 p = subprocess.Popen([sys.executable, "-c",
417 'import sys; sys.stderr.write("strawberry")'],
418 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000419 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000420 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000421
422 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000423 # stderr is set to open file descriptor
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 d = tf.fileno()
427 p = subprocess.Popen([sys.executable, "-c",
428 'import sys; sys.stderr.write("strawberry")'],
429 stderr=d)
430 p.wait()
431 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000432 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000433
434 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000435 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000436 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000437 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000438 p = subprocess.Popen([sys.executable, "-c",
439 'import sys; sys.stderr.write("strawberry")'],
440 stderr=tf)
441 p.wait()
442 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000443 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000444
445 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000446 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000447 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000448 'import sys;'
449 'sys.stdout.write("apple");'
450 'sys.stdout.flush();'
451 'sys.stderr.write("orange")'],
452 stdout=subprocess.PIPE,
453 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000454 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000455 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000456
457 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000458 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000459 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000460 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000461 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000462 'import sys;'
463 'sys.stdout.write("apple");'
464 'sys.stdout.flush();'
465 'sys.stderr.write("orange")'],
466 stdout=tf,
467 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000468 p.wait()
469 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000470 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000471
Thomas Wouters89f507f2006-12-13 04:49:30 +0000472 def test_stdout_filedes_of_stdout(self):
473 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000474 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000475 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000476 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000477
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200478 def test_stdout_devnull(self):
479 p = subprocess.Popen([sys.executable, "-c",
480 'for i in range(10240):'
481 'print("x" * 1024)'],
482 stdout=subprocess.DEVNULL)
483 p.wait()
484 self.assertEqual(p.stdout, None)
485
486 def test_stderr_devnull(self):
487 p = subprocess.Popen([sys.executable, "-c",
488 'import sys\n'
489 'for i in range(10240):'
490 'sys.stderr.write("x" * 1024)'],
491 stderr=subprocess.DEVNULL)
492 p.wait()
493 self.assertEqual(p.stderr, None)
494
495 def test_stdin_devnull(self):
496 p = subprocess.Popen([sys.executable, "-c",
497 'import sys;'
498 'sys.stdin.read(1)'],
499 stdin=subprocess.DEVNULL)
500 p.wait()
501 self.assertEqual(p.stdin, None)
502
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000503 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000504 newenv = os.environ.copy()
505 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200506 with subprocess.Popen([sys.executable, "-c",
507 'import sys,os;'
508 'sys.stdout.write(os.getenv("FRUIT"))'],
509 stdout=subprocess.PIPE,
510 env=newenv) as p:
511 stdout, stderr = p.communicate()
512 self.assertEqual(stdout, b"orange")
513
Victor Stinner62d51182011-06-23 01:02:25 +0200514 # Windows requires at least the SYSTEMROOT environment variable to start
515 # Python
516 @unittest.skipIf(sys.platform == 'win32',
517 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200518 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200519 'the python library cannot be loaded '
520 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200521 def test_empty_env(self):
522 with subprocess.Popen([sys.executable, "-c",
523 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200524 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200525 stdout=subprocess.PIPE,
526 env={}) as p:
527 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200528 self.assertIn(stdout.strip(),
529 (b"[]",
530 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
531 # environment
532 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000533
Peter Astrandcbac93c2005-03-03 20:24:28 +0000534 def test_communicate_stdin(self):
535 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000536 'import sys;'
537 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000538 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000539 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000540 self.assertEqual(p.returncode, 1)
541
542 def test_communicate_stdout(self):
543 p = subprocess.Popen([sys.executable, "-c",
544 'import sys; sys.stdout.write("pineapple")'],
545 stdout=subprocess.PIPE)
546 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000547 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000548 self.assertEqual(stderr, None)
549
550 def test_communicate_stderr(self):
551 p = subprocess.Popen([sys.executable, "-c",
552 'import sys; sys.stderr.write("pineapple")'],
553 stderr=subprocess.PIPE)
554 (stdout, stderr) = p.communicate()
555 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000556 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000557
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000558 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000559 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000560 'import sys,os;'
561 'sys.stderr.write("pineapple");'
562 'sys.stdout.write(sys.stdin.read())'],
563 stdin=subprocess.PIPE,
564 stdout=subprocess.PIPE,
565 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000566 self.addCleanup(p.stdout.close)
567 self.addCleanup(p.stderr.close)
568 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000569 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000570 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000571 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000572
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400573 def test_communicate_timeout(self):
574 p = subprocess.Popen([sys.executable, "-c",
575 'import sys,os,time;'
576 'sys.stderr.write("pineapple\\n");'
577 'time.sleep(1);'
578 'sys.stderr.write("pear\\n");'
579 'sys.stdout.write(sys.stdin.read())'],
580 universal_newlines=True,
581 stdin=subprocess.PIPE,
582 stdout=subprocess.PIPE,
583 stderr=subprocess.PIPE)
584 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
585 timeout=0.3)
586 # Make sure we can keep waiting for it, and that we get the whole output
587 # after it completes.
588 (stdout, stderr) = p.communicate()
589 self.assertEqual(stdout, "banana")
590 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
591
592 def test_communicate_timeout_large_ouput(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200593 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400594 p = subprocess.Popen([sys.executable, "-c",
595 'import sys,os,time;'
596 'sys.stdout.write("a" * (64 * 1024));'
597 'time.sleep(0.2);'
598 'sys.stdout.write("a" * (64 * 1024));'
599 'time.sleep(0.2);'
600 'sys.stdout.write("a" * (64 * 1024));'
601 'time.sleep(0.2);'
602 'sys.stdout.write("a" * (64 * 1024));'],
603 stdout=subprocess.PIPE)
604 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
605 (stdout, _) = p.communicate()
606 self.assertEqual(len(stdout), 4 * 64 * 1024)
607
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000608 # Test for the fd leak reported in http://bugs.python.org/issue2791.
609 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000610 for stdin_pipe in (False, True):
611 for stdout_pipe in (False, True):
612 for stderr_pipe in (False, True):
613 options = {}
614 if stdin_pipe:
615 options['stdin'] = subprocess.PIPE
616 if stdout_pipe:
617 options['stdout'] = subprocess.PIPE
618 if stderr_pipe:
619 options['stderr'] = subprocess.PIPE
620 if not options:
621 continue
622 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
623 p.communicate()
624 if p.stdin is not None:
625 self.assertTrue(p.stdin.closed)
626 if p.stdout is not None:
627 self.assertTrue(p.stdout.closed)
628 if p.stderr is not None:
629 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000630
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000631 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000632 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000633 p = subprocess.Popen([sys.executable, "-c",
634 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000635 (stdout, stderr) = p.communicate()
636 self.assertEqual(stdout, None)
637 self.assertEqual(stderr, None)
638
639 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000640 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000641 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000642 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000643 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000644 os.close(x)
645 os.close(y)
646 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000647 'import sys,os;'
648 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200649 'sys.stderr.write("x" * %d);'
650 'sys.stdout.write(sys.stdin.read())' %
651 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000652 stdin=subprocess.PIPE,
653 stdout=subprocess.PIPE,
654 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000655 self.addCleanup(p.stdout.close)
656 self.addCleanup(p.stderr.close)
657 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200658 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000659 (stdout, stderr) = p.communicate(string_to_write)
660 self.assertEqual(stdout, string_to_write)
661
662 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000663 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000664 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000665 'import sys,os;'
666 'sys.stdout.write(sys.stdin.read())'],
667 stdin=subprocess.PIPE,
668 stdout=subprocess.PIPE,
669 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000670 self.addCleanup(p.stdout.close)
671 self.addCleanup(p.stderr.close)
672 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000673 p.stdin.write(b"banana")
674 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000675 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000676 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000677
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000678 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000679 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000680 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200681 'buf = sys.stdout.buffer;'
682 'buf.write(sys.stdin.readline().encode());'
683 'buf.flush();'
684 'buf.write(b"line2\\n");'
685 'buf.flush();'
686 'buf.write(sys.stdin.read().encode());'
687 'buf.flush();'
688 'buf.write(b"line4\\n");'
689 'buf.flush();'
690 'buf.write(b"line5\\r\\n");'
691 'buf.flush();'
692 'buf.write(b"line6\\r");'
693 'buf.flush();'
694 'buf.write(b"\\nline7");'
695 'buf.flush();'
696 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200697 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000698 stdout=subprocess.PIPE,
699 universal_newlines=1)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200700 p.stdin.write("line1\n")
701 self.assertEqual(p.stdout.readline(), "line1\n")
702 p.stdin.write("line3\n")
703 p.stdin.close()
Brian Curtin3c6a9512010-11-05 03:58:52 +0000704 self.addCleanup(p.stdout.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200705 self.assertEqual(p.stdout.readline(),
706 "line2\n")
707 self.assertEqual(p.stdout.read(6),
708 "line3\n")
709 self.assertEqual(p.stdout.read(),
710 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000711
712 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000713 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000714 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000715 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200716 'buf = sys.stdout.buffer;'
717 'buf.write(b"line2\\n");'
718 'buf.flush();'
719 'buf.write(b"line4\\n");'
720 'buf.flush();'
721 'buf.write(b"line5\\r\\n");'
722 'buf.flush();'
723 'buf.write(b"line6\\r");'
724 'buf.flush();'
725 'buf.write(b"\\nline7");'
726 'buf.flush();'
727 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200728 stderr=subprocess.PIPE,
729 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000730 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000731 self.addCleanup(p.stdout.close)
732 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000733 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200734 self.assertEqual(stdout,
735 "line2\nline4\nline5\nline6\nline7\nline8")
736
737 def test_universal_newlines_communicate_stdin(self):
738 # universal newlines through communicate(), with only stdin
739 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300740 'import sys,os;' + SETBINARY + textwrap.dedent('''
741 s = sys.stdin.readline()
742 assert s == "line1\\n", repr(s)
743 s = sys.stdin.read()
744 assert s == "line3\\n", repr(s)
745 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200746 stdin=subprocess.PIPE,
747 universal_newlines=1)
748 (stdout, stderr) = p.communicate("line1\nline3\n")
749 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000750
Andrew Svetlovf3765072012-08-14 18:35:17 +0300751 def test_universal_newlines_communicate_input_none(self):
752 # Test communicate(input=None) with universal newlines.
753 #
754 # We set stdout to PIPE because, as of this writing, a different
755 # code path is tested when the number of pipes is zero or one.
756 p = subprocess.Popen([sys.executable, "-c", "pass"],
757 stdin=subprocess.PIPE,
758 stdout=subprocess.PIPE,
759 universal_newlines=True)
760 p.communicate()
761 self.assertEqual(p.returncode, 0)
762
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300763 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300764 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300765 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300766 'import sys,os;' + SETBINARY + textwrap.dedent('''
767 s = sys.stdin.buffer.readline()
768 sys.stdout.buffer.write(s)
769 sys.stdout.buffer.write(b"line2\\r")
770 sys.stderr.buffer.write(b"eline2\\n")
771 s = sys.stdin.buffer.read()
772 sys.stdout.buffer.write(s)
773 sys.stdout.buffer.write(b"line4\\n")
774 sys.stdout.buffer.write(b"line5\\r\\n")
775 sys.stderr.buffer.write(b"eline6\\r")
776 sys.stderr.buffer.write(b"eline7\\r\\nz")
777 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300778 stdin=subprocess.PIPE,
779 stderr=subprocess.PIPE,
780 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300781 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300782 self.addCleanup(p.stdout.close)
783 self.addCleanup(p.stderr.close)
784 (stdout, stderr) = p.communicate("line1\nline3\n")
785 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300786 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300787 # Python debug build push something like "[42442 refs]\n"
788 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300789 # Don't use assertStderrEqual because it strips CR and LF from output.
790 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300791
Andrew Svetlov82860712012-08-19 22:13:41 +0300792 def test_universal_newlines_communicate_encodings(self):
793 # Check that universal newlines mode works for various encodings,
794 # in particular for encodings in the UTF-16 and UTF-32 families.
795 # See issue #15595.
796 #
797 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
798 # without, and UTF-16 and UTF-32.
799 for encoding in ['utf-16', 'utf-32-be']:
800 old_getpreferredencoding = locale.getpreferredencoding
801 # Indirectly via io.TextIOWrapper, Popen() defaults to
802 # locale.getpreferredencoding(False) and earlier in Python 3.2 to
803 # locale.getpreferredencoding().
804 def getpreferredencoding(do_setlocale=True):
805 return encoding
806 code = ("import sys; "
807 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
808 encoding)
809 args = [sys.executable, '-c', code]
810 try:
811 locale.getpreferredencoding = getpreferredencoding
812 # We set stdin to be non-None because, as of this writing,
813 # a different code path is used when the number of pipes is
814 # zero or one.
815 popen = subprocess.Popen(args, universal_newlines=True,
816 stdin=subprocess.PIPE,
817 stdout=subprocess.PIPE)
818 stdout, stderr = popen.communicate(input='')
819 finally:
820 locale.getpreferredencoding = old_getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300821 self.assertEqual(stdout, '1\n2\n3\n4')
822
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000823 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000824 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000825 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000826 max_handles = 1026 # too much for most UNIX systems
827 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000828 max_handles = 2050 # too much for (at least some) Windows setups
829 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400830 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000831 try:
832 for i in range(max_handles):
833 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400834 tmpfile = os.path.join(tmpdir, support.TESTFN)
835 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000836 except OSError as e:
837 if e.errno != errno.EMFILE:
838 raise
839 break
840 else:
841 self.skipTest("failed to reach the file descriptor limit "
842 "(tried %d)" % max_handles)
843 # Close a couple of them (should be enough for a subprocess)
844 for i in range(10):
845 os.close(handles.pop())
846 # Loop creating some subprocesses. If one of them leaks some fds,
847 # the next loop iteration will fail by reaching the max fd limit.
848 for i in range(15):
849 p = subprocess.Popen([sys.executable, "-c",
850 "import sys;"
851 "sys.stdout.write(sys.stdin.read())"],
852 stdin=subprocess.PIPE,
853 stdout=subprocess.PIPE,
854 stderr=subprocess.PIPE)
855 data = p.communicate(b"lime")[0]
856 self.assertEqual(data, b"lime")
857 finally:
858 for h in handles:
859 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400860 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000861
862 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000863 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
864 '"a b c" d e')
865 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
866 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000867 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
868 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000869 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
870 'a\\\\\\b "de fg" h')
871 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
872 'a\\\\\\"b c d')
873 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
874 '"a\\\\b c" d e')
875 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
876 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000877 self.assertEqual(subprocess.list2cmdline(['ab', '']),
878 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000879
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000880 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200881 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +0200882 "import os; os.read(0, 1)"],
883 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200884 self.addCleanup(p.stdin.close)
885 self.assertIsNone(p.poll())
886 os.write(p.stdin.fileno(), b'A')
887 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000888 # Subsequent invocations should just return the returncode
889 self.assertEqual(p.poll(), 0)
890
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000891 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200892 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000893 self.assertEqual(p.wait(), 0)
894 # Subsequent invocations should just return the returncode
895 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000896
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400897 def test_wait_timeout(self):
898 p = subprocess.Popen([sys.executable,
Reid Kleckner93479cc2011-03-14 19:32:41 -0400899 "-c", "import time; time.sleep(0.1)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -0400900 with self.assertRaises(subprocess.TimeoutExpired) as c:
901 p.wait(timeout=0.01)
902 self.assertIn("0.01", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -0400903 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
904 # time to start.
905 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400906
Peter Astrand738131d2004-11-30 21:04:45 +0000907 def test_invalid_bufsize(self):
908 # an invalid type of the bufsize argument should raise
909 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000910 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000911 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000912
Guido van Rossum46a05a72007-06-07 21:56:45 +0000913 def test_bufsize_is_none(self):
914 # bufsize=None should be the same as bufsize=0.
915 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
916 self.assertEqual(p.wait(), 0)
917 # Again with keyword arg
918 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
919 self.assertEqual(p.wait(), 0)
920
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000921 def test_leaking_fds_on_error(self):
922 # see bug #5179: Popen leaks file descriptors to PIPEs if
923 # the child fails to execute; this will eventually exhaust
924 # the maximum number of open fds. 1024 seems a very common
925 # value for that limit, but Windows has 2048, so we loop
926 # 1024 times (each call leaked two fds).
927 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000928 # Windows raises IOError. Others raise OSError.
929 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000930 subprocess.Popen(['nonexisting_i_hope'],
931 stdout=subprocess.PIPE,
932 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400933 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400934 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000935 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000936
Victor Stinnerb3693582010-05-21 20:13:12 +0000937 def test_issue8780(self):
938 # Ensure that stdout is inherited from the parent
939 # if stdout=PIPE is not used
940 code = ';'.join((
941 'import subprocess, sys',
942 'retcode = subprocess.call('
943 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
944 'assert retcode == 0'))
945 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000946 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000947
Tim Goldenaf5ac392010-08-06 13:03:56 +0000948 def test_handles_closed_on_exception(self):
949 # If CreateProcess exits with an error, ensure the
950 # duplicate output handles are released
951 ifhandle, ifname = mkstemp()
952 ofhandle, ofname = mkstemp()
953 efhandle, efname = mkstemp()
954 try:
955 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
956 stderr=efhandle)
957 except OSError:
958 os.close(ifhandle)
959 os.remove(ifname)
960 os.close(ofhandle)
961 os.remove(ofname)
962 os.close(efhandle)
963 os.remove(efname)
964 self.assertFalse(os.path.exists(ifname))
965 self.assertFalse(os.path.exists(ofname))
966 self.assertFalse(os.path.exists(efname))
967
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200968 def test_communicate_epipe(self):
969 # Issue 10963: communicate() should hide EPIPE
970 p = subprocess.Popen([sys.executable, "-c", 'pass'],
971 stdin=subprocess.PIPE,
972 stdout=subprocess.PIPE,
973 stderr=subprocess.PIPE)
974 self.addCleanup(p.stdout.close)
975 self.addCleanup(p.stderr.close)
976 self.addCleanup(p.stdin.close)
977 p.communicate(b"x" * 2**20)
978
979 def test_communicate_epipe_only_stdin(self):
980 # Issue 10963: communicate() should hide EPIPE
981 p = subprocess.Popen([sys.executable, "-c", 'pass'],
982 stdin=subprocess.PIPE)
983 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200984 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200985 p.communicate(b"x" * 2**20)
986
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200987 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
988 "Requires signal.SIGUSR1")
989 @unittest.skipUnless(hasattr(os, 'kill'),
990 "Requires os.kill")
991 @unittest.skipUnless(hasattr(os, 'getppid'),
992 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200993 def test_communicate_eintr(self):
994 # Issue #12493: communicate() should handle EINTR
995 def handler(signum, frame):
996 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200997 old_handler = signal.signal(signal.SIGUSR1, handler)
998 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200999
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001000 args = [sys.executable, "-c",
1001 'import os, signal;'
1002 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001003 for stream in ('stdout', 'stderr'):
1004 kw = {stream: subprocess.PIPE}
1005 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +02001006 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +02001007 process.communicate()
1008
Tim Peterse718f612004-10-12 21:51:32 +00001009
Gregory P. Smith3d8e7762012-11-10 22:32:22 -08001010 # This test is Linux-ish specific for simplicity to at least have
1011 # some coverage. It is not a platform specific bug.
1012 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1013 "Linux specific")
1014 def test_failed_child_execute_fd_leak(self):
1015 """Test for the fork() failure fd leak reported in issue16327."""
1016 fd_directory = '/proc/%d/fd' % os.getpid()
1017 fds_before_popen = os.listdir(fd_directory)
1018 with self.assertRaises(PopenTestException):
1019 PopenExecuteChildRaises(
1020 [sys.executable, '-c', 'pass'], stdin=subprocess.PIPE,
1021 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1022
1023 # NOTE: This test doesn't verify that the real _execute_child
1024 # does not close the file descriptors itself on the way out
1025 # during an exception. Code inspection has confirmed that.
1026
1027 fds_after_exception = os.listdir(fd_directory)
1028 self.assertEqual(fds_before_popen, fds_after_exception)
1029
1030
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001031# context manager
1032class _SuppressCoreFiles(object):
1033 """Try to prevent core files from being created."""
1034 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001035
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001036 def __enter__(self):
1037 """Try to save previous ulimit, then set it to (0, 0)."""
Benjamin Peterson964561b2011-12-10 12:31:42 -05001038 if resource is not None:
1039 try:
1040 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
1041 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
1042 except (ValueError, resource.error):
1043 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001044
Ronald Oussoren102d11a2010-07-23 09:50:05 +00001045 if sys.platform == 'darwin':
1046 # Check if the 'Crash Reporter' on OSX was configured
1047 # in 'Developer' mode and warn that it will get triggered
1048 # when it is.
1049 #
1050 # This assumes that this context manager is used in tests
1051 # that might trigger the next manager.
1052 value = subprocess.Popen(['/usr/bin/defaults', 'read',
1053 'com.apple.CrashReporter', 'DialogType'],
1054 stdout=subprocess.PIPE).communicate()[0]
1055 if value.strip() == b'developer':
1056 print("this tests triggers the Crash Reporter, "
1057 "that is intentional", end='')
1058 sys.stdout.flush()
1059
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001060 def __exit__(self, *args):
1061 """Return core file behavior to default."""
1062 if self.old_limit is None:
1063 return
Benjamin Peterson964561b2011-12-10 12:31:42 -05001064 if resource is not None:
1065 try:
1066 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
1067 except (ValueError, resource.error):
1068 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001069
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001070
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001071@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001072class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001073
Gregory P. Smith5591b022012-10-10 03:34:47 -07001074 def setUp(self):
1075 super().setUp()
1076 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
1077
1078 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001079 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -07001080 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001081 except OSError as e:
1082 # This avoids hard coding the errno value or the OS perror()
1083 # string and instead capture the exception that we want to see
1084 # below for comparison.
1085 desired_exception = e
Gregory P. Smith5591b022012-10-10 03:34:47 -07001086 desired_exception.strerror += ': ' + repr(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001087 else:
1088 self.fail("chdir to nonexistant directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -07001089 self._nonexistent_dir)
1090 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001091
Gregory P. Smith5591b022012-10-10 03:34:47 -07001092 def test_exception_cwd(self):
1093 """Test error in the child raised in the parent for a bad cwd."""
1094 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001095 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001096 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -07001097 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001098 except OSError as e:
1099 # Test that the child process chdir failure actually makes
1100 # it up to the parent process as the correct exception.
1101 self.assertEqual(desired_exception.errno, e.errno)
1102 self.assertEqual(desired_exception.strerror, e.strerror)
1103 else:
1104 self.fail("Expected OSError: %s" % desired_exception)
1105
Gregory P. Smith5591b022012-10-10 03:34:47 -07001106 def test_exception_bad_executable(self):
1107 """Test error in the child raised in the parent for a bad executable."""
1108 desired_exception = self._get_chdir_exception()
1109 try:
1110 p = subprocess.Popen([sys.executable, "-c", ""],
1111 executable=self._nonexistent_dir)
1112 except OSError as e:
1113 # Test that the child process exec failure actually makes
1114 # it up to the parent process as the correct exception.
1115 self.assertEqual(desired_exception.errno, e.errno)
1116 self.assertEqual(desired_exception.strerror, e.strerror)
1117 else:
1118 self.fail("Expected OSError: %s" % desired_exception)
1119
1120 def test_exception_bad_args_0(self):
1121 """Test error in the child raised in the parent for a bad args[0]."""
1122 desired_exception = self._get_chdir_exception()
1123 try:
1124 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
1125 except OSError as e:
1126 # Test that the child process exec failure actually makes
1127 # it up to the parent process as the correct exception.
1128 self.assertEqual(desired_exception.errno, e.errno)
1129 self.assertEqual(desired_exception.strerror, e.strerror)
1130 else:
1131 self.fail("Expected OSError: %s" % desired_exception)
1132
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001133 def test_restore_signals(self):
1134 # Code coverage for both values of restore_signals to make sure it
1135 # at least does not blow up.
1136 # A test for behavior would be complex. Contributions welcome.
1137 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1138 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1139
1140 def test_start_new_session(self):
1141 # For code coverage of calling setsid(). We don't care if we get an
1142 # EPERM error from it depending on the test execution environment, that
1143 # still indicates that it was called.
1144 try:
1145 output = subprocess.check_output(
1146 [sys.executable, "-c",
1147 "import os; print(os.getpgid(os.getpid()))"],
1148 start_new_session=True)
1149 except OSError as e:
1150 if e.errno != errno.EPERM:
1151 raise
1152 else:
1153 parent_pgid = os.getpgid(os.getpid())
1154 child_pgid = int(output)
1155 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001156
1157 def test_run_abort(self):
1158 # returncode handles signal termination
1159 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001160 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001161 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001162 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001163 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001164
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001165 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001166 # DISCLAIMER: Setting environment variables is *not* a good use
1167 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001168 p = subprocess.Popen([sys.executable, "-c",
1169 'import sys,os;'
1170 'sys.stdout.write(os.getenv("FRUIT"))'],
1171 stdout=subprocess.PIPE,
1172 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +00001173 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001174 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001175
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001176 def test_preexec_exception(self):
1177 def raise_it():
1178 raise ValueError("What if two swallows carried a coconut?")
1179 try:
1180 p = subprocess.Popen([sys.executable, "-c", ""],
1181 preexec_fn=raise_it)
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001182 except subprocess.SubprocessError as e:
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001183 self.assertTrue(
1184 subprocess._posixsubprocess,
1185 "Expected a ValueError from the preexec_fn")
1186 except ValueError as e:
1187 self.assertIn("coconut", e.args[0])
1188 else:
1189 self.fail("Exception raised by preexec_fn did not make it "
1190 "to the parent process.")
1191
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001192 class _TestExecuteChildPopen(subprocess.Popen):
1193 """Used to test behavior at the end of _execute_child."""
1194 def __init__(self, testcase, *args, **kwargs):
1195 self._testcase = testcase
1196 subprocess.Popen.__init__(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001197
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001198 def _execute_child(self, *args, **kwargs):
Gregory P. Smith12489d92012-11-11 01:37:02 -08001199 try:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001200 subprocess.Popen._execute_child(self, *args, **kwargs)
Gregory P. Smith12489d92012-11-11 01:37:02 -08001201 finally:
1202 # Open a bunch of file descriptors and verify that
1203 # none of them are the same as the ones the Popen
1204 # instance is using for stdin/stdout/stderr.
1205 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
1206 for _ in range(8)]
1207 try:
1208 for fd in devzero_fds:
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001209 self._testcase.assertNotIn(
1210 fd, (self.stdin.fileno(), self.stdout.fileno(),
1211 self.stderr.fileno()),
Gregory P. Smith12489d92012-11-11 01:37:02 -08001212 msg="At least one fd was closed early.")
1213 finally:
1214 map(os.close, devzero_fds)
1215
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001216 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
1217 def test_preexec_errpipe_does_not_double_close_pipes(self):
1218 """Issue16140: Don't double close pipes on preexec error."""
1219
1220 def raise_it():
Gregory P. Smith65ee6ec2012-11-11 10:12:40 -08001221 raise subprocess.SubprocessError(
1222 "force the _execute_child() errpipe_data path.")
Gregory P. Smith12489d92012-11-11 01:37:02 -08001223
Gregory P. Smithc2c4cb62012-11-11 01:41:49 -08001224 with self.assertRaises(subprocess.SubprocessError):
Gregory P. Smithe27faac2012-11-11 09:59:27 -08001225 self._TestExecuteChildPopen(
1226 self, [sys.executable, "-c", "pass"],
Gregory P. Smith12489d92012-11-11 01:37:02 -08001227 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1228 stderr=subprocess.PIPE, preexec_fn=raise_it)
1229
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001230 def test_preexec_gc_module_failure(self):
1231 # This tests the code that disables garbage collection if the child
1232 # process will execute any Python.
1233 def raise_runtime_error():
1234 raise RuntimeError("this shouldn't escape")
1235 enabled = gc.isenabled()
1236 orig_gc_disable = gc.disable
1237 orig_gc_isenabled = gc.isenabled
1238 try:
1239 gc.disable()
1240 self.assertFalse(gc.isenabled())
1241 subprocess.call([sys.executable, '-c', ''],
1242 preexec_fn=lambda: None)
1243 self.assertFalse(gc.isenabled(),
1244 "Popen enabled gc when it shouldn't.")
1245
1246 gc.enable()
1247 self.assertTrue(gc.isenabled())
1248 subprocess.call([sys.executable, '-c', ''],
1249 preexec_fn=lambda: None)
1250 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1251
1252 gc.disable = raise_runtime_error
1253 self.assertRaises(RuntimeError, subprocess.Popen,
1254 [sys.executable, '-c', ''],
1255 preexec_fn=lambda: None)
1256
1257 del gc.isenabled # force an AttributeError
1258 self.assertRaises(AttributeError, subprocess.Popen,
1259 [sys.executable, '-c', ''],
1260 preexec_fn=lambda: None)
1261 finally:
1262 gc.disable = orig_gc_disable
1263 gc.isenabled = orig_gc_isenabled
1264 if not enabled:
1265 gc.disable()
1266
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001267 def test_args_string(self):
1268 # args is a string
1269 fd, fname = mkstemp()
1270 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001271 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001272 fobj.write("#!/bin/sh\n")
1273 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1274 sys.executable)
1275 os.chmod(fname, 0o700)
1276 p = subprocess.Popen(fname)
1277 p.wait()
1278 os.remove(fname)
1279 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001280
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001281 def test_invalid_args(self):
1282 # invalid arguments should raise ValueError
1283 self.assertRaises(ValueError, subprocess.call,
1284 [sys.executable, "-c",
1285 "import sys; sys.exit(47)"],
1286 startupinfo=47)
1287 self.assertRaises(ValueError, subprocess.call,
1288 [sys.executable, "-c",
1289 "import sys; sys.exit(47)"],
1290 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001291
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001292 def test_shell_sequence(self):
1293 # Run command through the shell (sequence)
1294 newenv = os.environ.copy()
1295 newenv["FRUIT"] = "apple"
1296 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1297 stdout=subprocess.PIPE,
1298 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001299 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001300 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001301
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001302 def test_shell_string(self):
1303 # Run command through the shell (string)
1304 newenv = os.environ.copy()
1305 newenv["FRUIT"] = "apple"
1306 p = subprocess.Popen("echo $FRUIT", shell=1,
1307 stdout=subprocess.PIPE,
1308 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001309 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001310 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001311
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001312 def test_call_string(self):
1313 # call() function with string argument on UNIX
1314 fd, fname = mkstemp()
1315 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001316 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001317 fobj.write("#!/bin/sh\n")
1318 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1319 sys.executable)
1320 os.chmod(fname, 0o700)
1321 rc = subprocess.call(fname)
1322 os.remove(fname)
1323 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001324
Stefan Krah9542cc62010-07-19 14:20:53 +00001325 def test_specific_shell(self):
1326 # Issue #9265: Incorrect name passed as arg[0].
1327 shells = []
1328 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1329 for name in ['bash', 'ksh']:
1330 sh = os.path.join(prefix, name)
1331 if os.path.isfile(sh):
1332 shells.append(sh)
1333 if not shells: # Will probably work for any shell but csh.
1334 self.skipTest("bash or ksh required for this test")
1335 sh = '/bin/sh'
1336 if os.path.isfile(sh) and not os.path.islink(sh):
1337 # Test will fail if /bin/sh is a symlink to csh.
1338 shells.append(sh)
1339 for sh in shells:
1340 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1341 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001342 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001343 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1344
Florent Xicluna4886d242010-03-08 13:27:26 +00001345 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001346 # Do not inherit file handles from the parent.
1347 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001348 p = subprocess.Popen([sys.executable, "-c", """if 1:
1349 import sys, time
1350 sys.stdout.write('x\\n')
1351 sys.stdout.flush()
1352 time.sleep(30)
1353 """],
1354 close_fds=True,
1355 stdin=subprocess.PIPE,
1356 stdout=subprocess.PIPE,
1357 stderr=subprocess.PIPE)
1358 # Wait for the interpreter to be completely initialized before
1359 # sending any signal.
1360 p.stdout.read(1)
1361 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001362 return p
1363
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001364 def _kill_dead_process(self, method, *args):
1365 # Do not inherit file handles from the parent.
1366 # It should fix failures on some platforms.
1367 p = subprocess.Popen([sys.executable, "-c", """if 1:
1368 import sys, time
1369 sys.stdout.write('x\\n')
1370 sys.stdout.flush()
1371 """],
1372 close_fds=True,
1373 stdin=subprocess.PIPE,
1374 stdout=subprocess.PIPE,
1375 stderr=subprocess.PIPE)
1376 # Wait for the interpreter to be completely initialized before
1377 # sending any signal.
1378 p.stdout.read(1)
1379 # The process should end after this
1380 time.sleep(1)
1381 # This shouldn't raise even though the child is now dead
1382 getattr(p, method)(*args)
1383 p.communicate()
1384
Florent Xicluna4886d242010-03-08 13:27:26 +00001385 def test_send_signal(self):
1386 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001387 _, stderr = p.communicate()
1388 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001389 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001390
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001391 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001392 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001393 _, stderr = p.communicate()
1394 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001395 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001396
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001397 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001398 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001399 _, stderr = p.communicate()
1400 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001401 self.assertEqual(p.wait(), -signal.SIGTERM)
1402
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001403 def test_send_signal_dead(self):
1404 # Sending a signal to a dead process
1405 self._kill_dead_process('send_signal', signal.SIGINT)
1406
1407 def test_kill_dead(self):
1408 # Killing a dead process
1409 self._kill_dead_process('kill')
1410
1411 def test_terminate_dead(self):
1412 # Terminating a dead process
1413 self._kill_dead_process('terminate')
1414
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001415 def check_close_std_fds(self, fds):
1416 # Issue #9905: test that subprocess pipes still work properly with
1417 # some standard fds closed
1418 stdin = 0
1419 newfds = []
1420 for a in fds:
1421 b = os.dup(a)
1422 newfds.append(b)
1423 if a == 0:
1424 stdin = b
1425 try:
1426 for fd in fds:
1427 os.close(fd)
1428 out, err = subprocess.Popen([sys.executable, "-c",
1429 'import sys;'
1430 'sys.stdout.write("apple");'
1431 'sys.stdout.flush();'
1432 'sys.stderr.write("orange")'],
1433 stdin=stdin,
1434 stdout=subprocess.PIPE,
1435 stderr=subprocess.PIPE).communicate()
1436 err = support.strip_python_stderr(err)
1437 self.assertEqual((out, err), (b'apple', b'orange'))
1438 finally:
1439 for b, a in zip(newfds, fds):
1440 os.dup2(b, a)
1441 for b in newfds:
1442 os.close(b)
1443
1444 def test_close_fd_0(self):
1445 self.check_close_std_fds([0])
1446
1447 def test_close_fd_1(self):
1448 self.check_close_std_fds([1])
1449
1450 def test_close_fd_2(self):
1451 self.check_close_std_fds([2])
1452
1453 def test_close_fds_0_1(self):
1454 self.check_close_std_fds([0, 1])
1455
1456 def test_close_fds_0_2(self):
1457 self.check_close_std_fds([0, 2])
1458
1459 def test_close_fds_1_2(self):
1460 self.check_close_std_fds([1, 2])
1461
1462 def test_close_fds_0_1_2(self):
1463 # Issue #10806: test that subprocess pipes still work properly with
1464 # all standard fds closed.
1465 self.check_close_std_fds([0, 1, 2])
1466
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001467 def test_remapping_std_fds(self):
1468 # open up some temporary files
1469 temps = [mkstemp() for i in range(3)]
1470 try:
1471 temp_fds = [fd for fd, fname in temps]
1472
1473 # unlink the files -- we won't need to reopen them
1474 for fd, fname in temps:
1475 os.unlink(fname)
1476
1477 # write some data to what will become stdin, and rewind
1478 os.write(temp_fds[1], b"STDIN")
1479 os.lseek(temp_fds[1], 0, 0)
1480
1481 # move the standard file descriptors out of the way
1482 saved_fds = [os.dup(fd) for fd in range(3)]
1483 try:
1484 # duplicate the file objects over the standard fd's
1485 for fd, temp_fd in enumerate(temp_fds):
1486 os.dup2(temp_fd, fd)
1487
1488 # now use those files in the "wrong" order, so that subprocess
1489 # has to rearrange them in the child
1490 p = subprocess.Popen([sys.executable, "-c",
1491 'import sys; got = sys.stdin.read();'
1492 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1493 stdin=temp_fds[1],
1494 stdout=temp_fds[2],
1495 stderr=temp_fds[0])
1496 p.wait()
1497 finally:
1498 # restore the original fd's underneath sys.stdin, etc.
1499 for std, saved in enumerate(saved_fds):
1500 os.dup2(saved, std)
1501 os.close(saved)
1502
1503 for fd in temp_fds:
1504 os.lseek(fd, 0, 0)
1505
1506 out = os.read(temp_fds[2], 1024)
1507 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1508 self.assertEqual(out, b"got STDIN")
1509 self.assertEqual(err, b"err")
1510
1511 finally:
1512 for fd in temp_fds:
1513 os.close(fd)
1514
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001515 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1516 # open up some temporary files
1517 temps = [mkstemp() for i in range(3)]
1518 temp_fds = [fd for fd, fname in temps]
1519 try:
1520 # unlink the files -- we won't need to reopen them
1521 for fd, fname in temps:
1522 os.unlink(fname)
1523
1524 # save a copy of the standard file descriptors
1525 saved_fds = [os.dup(fd) for fd in range(3)]
1526 try:
1527 # duplicate the temp files over the standard fd's 0, 1, 2
1528 for fd, temp_fd in enumerate(temp_fds):
1529 os.dup2(temp_fd, fd)
1530
1531 # write some data to what will become stdin, and rewind
1532 os.write(stdin_no, b"STDIN")
1533 os.lseek(stdin_no, 0, 0)
1534
1535 # now use those files in the given order, so that subprocess
1536 # has to rearrange them in the child
1537 p = subprocess.Popen([sys.executable, "-c",
1538 'import sys; got = sys.stdin.read();'
1539 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1540 stdin=stdin_no,
1541 stdout=stdout_no,
1542 stderr=stderr_no)
1543 p.wait()
1544
1545 for fd in temp_fds:
1546 os.lseek(fd, 0, 0)
1547
1548 out = os.read(stdout_no, 1024)
1549 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1550 finally:
1551 for std, saved in enumerate(saved_fds):
1552 os.dup2(saved, std)
1553 os.close(saved)
1554
1555 self.assertEqual(out, b"got STDIN")
1556 self.assertEqual(err, b"err")
1557
1558 finally:
1559 for fd in temp_fds:
1560 os.close(fd)
1561
1562 # When duping fds, if there arises a situation where one of the fds is
1563 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1564 # This tests all combinations of this.
1565 def test_swap_fds(self):
1566 self.check_swap_fds(0, 1, 2)
1567 self.check_swap_fds(0, 2, 1)
1568 self.check_swap_fds(1, 0, 2)
1569 self.check_swap_fds(1, 2, 0)
1570 self.check_swap_fds(2, 0, 1)
1571 self.check_swap_fds(2, 1, 0)
1572
Victor Stinner13bb71c2010-04-23 21:41:56 +00001573 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001574 def prepare():
1575 raise ValueError("surrogate:\uDCff")
1576
1577 try:
1578 subprocess.call(
1579 [sys.executable, "-c", "pass"],
1580 preexec_fn=prepare)
1581 except ValueError as err:
1582 # Pure Python implementations keeps the message
1583 self.assertIsNone(subprocess._posixsubprocess)
1584 self.assertEqual(str(err), "surrogate:\uDCff")
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001585 except subprocess.SubprocessError as err:
Victor Stinner4d078042010-04-23 19:28:32 +00001586 # _posixsubprocess uses a default message
1587 self.assertIsNotNone(subprocess._posixsubprocess)
1588 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1589 else:
Gregory P. Smith8d07c262012-11-10 23:53:47 -08001590 self.fail("Expected ValueError or subprocess.SubprocessError")
Victor Stinner4d078042010-04-23 19:28:32 +00001591
Victor Stinner13bb71c2010-04-23 21:41:56 +00001592 def test_undecodable_env(self):
1593 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001594 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001595 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001596 env = os.environ.copy()
1597 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001598 # Use C locale to get ascii for the locale encoding to force
1599 # surrogate-escaping of \xFF in the child process; otherwise it can
1600 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001601 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001602 stdout = subprocess.check_output(
1603 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001604 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001605 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001606 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001607
1608 # test bytes
1609 key = key.encode("ascii", "surrogateescape")
1610 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001611 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001612 env = os.environ.copy()
1613 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001614 stdout = subprocess.check_output(
1615 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001616 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001617 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001618 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001619
Victor Stinnerb745a742010-05-18 17:17:23 +00001620 def test_bytes_program(self):
1621 abs_program = os.fsencode(sys.executable)
1622 path, program = os.path.split(sys.executable)
1623 program = os.fsencode(program)
1624
1625 # absolute bytes path
1626 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001627 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001628
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001629 # absolute bytes path as a string
1630 cmd = b"'" + abs_program + b"' -c pass"
1631 exitcode = subprocess.call(cmd, shell=True)
1632 self.assertEqual(exitcode, 0)
1633
Victor Stinnerb745a742010-05-18 17:17:23 +00001634 # bytes program, unicode PATH
1635 env = os.environ.copy()
1636 env["PATH"] = path
1637 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001638 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001639
1640 # bytes program, bytes PATH
1641 envb = os.environb.copy()
1642 envb[b"PATH"] = os.fsencode(path)
1643 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001644 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001645
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001646 def test_pipe_cloexec(self):
1647 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1648 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1649
1650 p1 = subprocess.Popen([sys.executable, sleeper],
1651 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1652 stderr=subprocess.PIPE, close_fds=False)
1653
1654 self.addCleanup(p1.communicate, b'')
1655
1656 p2 = subprocess.Popen([sys.executable, fd_status],
1657 stdout=subprocess.PIPE, close_fds=False)
1658
1659 output, error = p2.communicate()
1660 result_fds = set(map(int, output.split(b',')))
1661 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1662 p1.stderr.fileno()])
1663
1664 self.assertFalse(result_fds & unwanted_fds,
1665 "Expected no fds from %r to be open in child, "
1666 "found %r" %
1667 (unwanted_fds, result_fds & unwanted_fds))
1668
1669 def test_pipe_cloexec_real_tools(self):
1670 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1671 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1672
1673 subdata = b'zxcvbn'
1674 data = subdata * 4 + b'\n'
1675
1676 p1 = subprocess.Popen([sys.executable, qcat],
1677 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1678 close_fds=False)
1679
1680 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1681 stdin=p1.stdout, stdout=subprocess.PIPE,
1682 close_fds=False)
1683
1684 self.addCleanup(p1.wait)
1685 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001686 def kill_p1():
1687 try:
1688 p1.terminate()
1689 except ProcessLookupError:
1690 pass
1691 def kill_p2():
1692 try:
1693 p2.terminate()
1694 except ProcessLookupError:
1695 pass
1696 self.addCleanup(kill_p1)
1697 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001698
1699 p1.stdin.write(data)
1700 p1.stdin.close()
1701
1702 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1703
1704 self.assertTrue(readfiles, "The child hung")
1705 self.assertEqual(p2.stdout.read(), data)
1706
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001707 p1.stdout.close()
1708 p2.stdout.close()
1709
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001710 def test_close_fds(self):
1711 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1712
1713 fds = os.pipe()
1714 self.addCleanup(os.close, fds[0])
1715 self.addCleanup(os.close, fds[1])
1716
1717 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001718 # add a bunch more fds
1719 for _ in range(9):
1720 fd = os.open("/dev/null", os.O_RDONLY)
1721 self.addCleanup(os.close, fd)
1722 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001723
1724 p = subprocess.Popen([sys.executable, fd_status],
1725 stdout=subprocess.PIPE, close_fds=False)
1726 output, ignored = p.communicate()
1727 remaining_fds = set(map(int, output.split(b',')))
1728
1729 self.assertEqual(remaining_fds & open_fds, open_fds,
1730 "Some fds were closed")
1731
1732 p = subprocess.Popen([sys.executable, fd_status],
1733 stdout=subprocess.PIPE, close_fds=True)
1734 output, ignored = p.communicate()
1735 remaining_fds = set(map(int, output.split(b',')))
1736
1737 self.assertFalse(remaining_fds & open_fds,
1738 "Some fds were left open")
1739 self.assertIn(1, remaining_fds, "Subprocess failed")
1740
Gregory P. Smith8facece2012-01-21 14:01:08 -08001741 # Keep some of the fd's we opened open in the subprocess.
1742 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1743 fds_to_keep = set(open_fds.pop() for _ in range(8))
1744 p = subprocess.Popen([sys.executable, fd_status],
1745 stdout=subprocess.PIPE, close_fds=True,
1746 pass_fds=())
1747 output, ignored = p.communicate()
1748 remaining_fds = set(map(int, output.split(b',')))
1749
1750 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1751 "Some fds not in pass_fds were left open")
1752 self.assertIn(1, remaining_fds, "Subprocess failed")
1753
Victor Stinner88701e22011-06-01 13:13:04 +02001754 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1755 # descriptor of a pipe closed in the parent process is valid in the
1756 # child process according to fstat(), but the mode of the file
1757 # descriptor is invalid, and read or write raise an error.
1758 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001759 def test_pass_fds(self):
1760 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1761
1762 open_fds = set()
1763
1764 for x in range(5):
1765 fds = os.pipe()
1766 self.addCleanup(os.close, fds[0])
1767 self.addCleanup(os.close, fds[1])
1768 open_fds.update(fds)
1769
1770 for fd in open_fds:
1771 p = subprocess.Popen([sys.executable, fd_status],
1772 stdout=subprocess.PIPE, close_fds=True,
1773 pass_fds=(fd, ))
1774 output, ignored = p.communicate()
1775
1776 remaining_fds = set(map(int, output.split(b',')))
1777 to_be_closed = open_fds - {fd}
1778
1779 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1780 self.assertFalse(remaining_fds & to_be_closed,
1781 "fd to be closed passed")
1782
1783 # pass_fds overrides close_fds with a warning.
1784 with self.assertWarns(RuntimeWarning) as context:
1785 self.assertFalse(subprocess.call(
1786 [sys.executable, "-c", "import sys; sys.exit(0)"],
1787 close_fds=False, pass_fds=(fd, )))
1788 self.assertIn('overriding close_fds', str(context.warning))
1789
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001790 def test_stdout_stdin_are_single_inout_fd(self):
1791 with io.open(os.devnull, "r+") as inout:
1792 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1793 stdout=inout, stdin=inout)
1794 p.wait()
1795
1796 def test_stdout_stderr_are_single_inout_fd(self):
1797 with io.open(os.devnull, "r+") as inout:
1798 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1799 stdout=inout, stderr=inout)
1800 p.wait()
1801
1802 def test_stderr_stdin_are_single_inout_fd(self):
1803 with io.open(os.devnull, "r+") as inout:
1804 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1805 stderr=inout, stdin=inout)
1806 p.wait()
1807
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001808 def test_wait_when_sigchild_ignored(self):
1809 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1810 sigchild_ignore = support.findfile("sigchild_ignore.py",
1811 subdir="subprocessdata")
1812 p = subprocess.Popen([sys.executable, sigchild_ignore],
1813 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1814 stdout, stderr = p.communicate()
1815 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001816 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001817 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001818
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001819 def test_select_unbuffered(self):
1820 # Issue #11459: bufsize=0 should really set the pipes as
1821 # unbuffered (and therefore let select() work properly).
1822 select = support.import_module("select")
1823 p = subprocess.Popen([sys.executable, "-c",
1824 'import sys;'
1825 'sys.stdout.write("apple")'],
1826 stdout=subprocess.PIPE,
1827 bufsize=0)
1828 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001829 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001830 try:
1831 self.assertEqual(f.read(4), b"appl")
1832 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1833 finally:
1834 p.wait()
1835
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001836 def test_zombie_fast_process_del(self):
1837 # Issue #12650: on Unix, if Popen.__del__() was called before the
1838 # process exited, it wouldn't be added to subprocess._active, and would
1839 # remain a zombie.
1840 # spawn a Popen, and delete its reference before it exits
1841 p = subprocess.Popen([sys.executable, "-c",
1842 'import sys, time;'
1843 'time.sleep(0.2)'],
1844 stdout=subprocess.PIPE,
1845 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001846 self.addCleanup(p.stdout.close)
1847 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001848 ident = id(p)
1849 pid = p.pid
1850 del p
1851 # check that p is in the active processes list
1852 self.assertIn(ident, [id(o) for o in subprocess._active])
1853
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001854 def test_leak_fast_process_del_killed(self):
1855 # Issue #12650: on Unix, if Popen.__del__() was called before the
1856 # process exited, and the process got killed by a signal, it would never
1857 # be removed from subprocess._active, which triggered a FD and memory
1858 # leak.
1859 # spawn a Popen, delete its reference and kill it
1860 p = subprocess.Popen([sys.executable, "-c",
1861 'import time;'
1862 'time.sleep(3)'],
1863 stdout=subprocess.PIPE,
1864 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001865 self.addCleanup(p.stdout.close)
1866 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001867 ident = id(p)
1868 pid = p.pid
1869 del p
1870 os.kill(pid, signal.SIGKILL)
1871 # check that p is in the active processes list
1872 self.assertIn(ident, [id(o) for o in subprocess._active])
1873
1874 # let some time for the process to exit, and create a new Popen: this
1875 # should trigger the wait() of p
1876 time.sleep(0.2)
1877 with self.assertRaises(EnvironmentError) as c:
1878 with subprocess.Popen(['nonexisting_i_hope'],
1879 stdout=subprocess.PIPE,
1880 stderr=subprocess.PIPE) as proc:
1881 pass
1882 # p should have been wait()ed on, and removed from the _active list
1883 self.assertRaises(OSError, os.waitpid, pid, 0)
1884 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1885
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001886
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001887@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001888class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001889
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001890 def test_startupinfo(self):
1891 # startupinfo argument
1892 # We uses hardcoded constants, because we do not want to
1893 # depend on win32all.
1894 STARTF_USESHOWWINDOW = 1
1895 SW_MAXIMIZE = 3
1896 startupinfo = subprocess.STARTUPINFO()
1897 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1898 startupinfo.wShowWindow = SW_MAXIMIZE
1899 # Since Python is a console process, it won't be affected
1900 # by wShowWindow, but the argument should be silently
1901 # ignored
1902 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001903 startupinfo=startupinfo)
1904
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001905 def test_creationflags(self):
1906 # creationflags argument
1907 CREATE_NEW_CONSOLE = 16
1908 sys.stderr.write(" a DOS box should flash briefly ...\n")
1909 subprocess.call(sys.executable +
1910 ' -c "import time; time.sleep(0.25)"',
1911 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001912
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001913 def test_invalid_args(self):
1914 # invalid arguments should raise ValueError
1915 self.assertRaises(ValueError, subprocess.call,
1916 [sys.executable, "-c",
1917 "import sys; sys.exit(47)"],
1918 preexec_fn=lambda: 1)
1919 self.assertRaises(ValueError, subprocess.call,
1920 [sys.executable, "-c",
1921 "import sys; sys.exit(47)"],
1922 stdout=subprocess.PIPE,
1923 close_fds=True)
1924
1925 def test_close_fds(self):
1926 # close file descriptors
1927 rc = subprocess.call([sys.executable, "-c",
1928 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001929 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001930 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001931
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001932 def test_shell_sequence(self):
1933 # Run command through the shell (sequence)
1934 newenv = os.environ.copy()
1935 newenv["FRUIT"] = "physalis"
1936 p = subprocess.Popen(["set"], shell=1,
1937 stdout=subprocess.PIPE,
1938 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001939 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001940 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001941
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001942 def test_shell_string(self):
1943 # Run command through the shell (string)
1944 newenv = os.environ.copy()
1945 newenv["FRUIT"] = "physalis"
1946 p = subprocess.Popen("set", shell=1,
1947 stdout=subprocess.PIPE,
1948 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001949 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001950 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001951
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001952 def test_call_string(self):
1953 # call() function with string argument on Windows
1954 rc = subprocess.call(sys.executable +
1955 ' -c "import sys; sys.exit(47)"')
1956 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001957
Florent Xicluna4886d242010-03-08 13:27:26 +00001958 def _kill_process(self, method, *args):
1959 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001960 p = subprocess.Popen([sys.executable, "-c", """if 1:
1961 import sys, time
1962 sys.stdout.write('x\\n')
1963 sys.stdout.flush()
1964 time.sleep(30)
1965 """],
1966 stdin=subprocess.PIPE,
1967 stdout=subprocess.PIPE,
1968 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001969 self.addCleanup(p.stdout.close)
1970 self.addCleanup(p.stderr.close)
1971 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001972 # Wait for the interpreter to be completely initialized before
1973 # sending any signal.
1974 p.stdout.read(1)
1975 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001976 _, stderr = p.communicate()
1977 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001978 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001979 self.assertNotEqual(returncode, 0)
1980
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001981 def _kill_dead_process(self, method, *args):
1982 p = subprocess.Popen([sys.executable, "-c", """if 1:
1983 import sys, time
1984 sys.stdout.write('x\\n')
1985 sys.stdout.flush()
1986 sys.exit(42)
1987 """],
1988 stdin=subprocess.PIPE,
1989 stdout=subprocess.PIPE,
1990 stderr=subprocess.PIPE)
1991 self.addCleanup(p.stdout.close)
1992 self.addCleanup(p.stderr.close)
1993 self.addCleanup(p.stdin.close)
1994 # Wait for the interpreter to be completely initialized before
1995 # sending any signal.
1996 p.stdout.read(1)
1997 # The process should end after this
1998 time.sleep(1)
1999 # This shouldn't raise even though the child is now dead
2000 getattr(p, method)(*args)
2001 _, stderr = p.communicate()
2002 self.assertStderrEqual(stderr, b'')
2003 rc = p.wait()
2004 self.assertEqual(rc, 42)
2005
Florent Xicluna4886d242010-03-08 13:27:26 +00002006 def test_send_signal(self):
2007 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00002008
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002009 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002010 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00002011
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002012 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00002013 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00002014
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01002015 def test_send_signal_dead(self):
2016 self._kill_dead_process('send_signal', signal.SIGTERM)
2017
2018 def test_kill_dead(self):
2019 self._kill_dead_process('kill')
2020
2021 def test_terminate_dead(self):
2022 self._kill_dead_process('terminate')
2023
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002024
Brett Cannona23810f2008-05-26 19:04:21 +00002025# The module says:
2026# "NB This only works (and is only relevant) for UNIX."
2027#
2028# Actually, getoutput should work on any platform with an os.popen, but
2029# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00002030@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002031class CommandTests(unittest.TestCase):
2032 def test_getoutput(self):
2033 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
2034 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
2035 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00002036
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002037 # we use mkdtemp in the next line to create an empty directory
2038 # under our exclusive control; from that, we can invent a pathname
2039 # that we _know_ won't exist. This is guaranteed to fail.
2040 dir = None
2041 try:
2042 dir = tempfile.mkdtemp()
2043 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00002044
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002045 status, output = subprocess.getstatusoutput('cat ' + name)
2046 self.assertNotEqual(status, 0)
2047 finally:
2048 if dir is not None:
2049 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00002050
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002051
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002052@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
2053 "poll system call not supported")
2054class ProcessTestCaseNoPoll(ProcessTestCase):
2055 def setUp(self):
2056 subprocess._has_poll = False
2057 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002058
Florent Xiclunab1e94e82010-02-27 22:12:37 +00002059 def tearDown(self):
2060 subprocess._has_poll = True
2061 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00002062
2063
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00002064class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00002065 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00002066 def test_eintr_retry_call(self):
2067 record_calls = []
2068 def fake_os_func(*args):
2069 record_calls.append(args)
2070 if len(record_calls) == 2:
2071 raise OSError(errno.EINTR, "fake interrupted system call")
2072 return tuple(reversed(args))
2073
2074 self.assertEqual((999, 256),
2075 subprocess._eintr_retry_call(fake_os_func, 256, 999))
2076 self.assertEqual([(256, 999)], record_calls)
2077 # This time there will be an EINTR so it will loop once.
2078 self.assertEqual((666,),
2079 subprocess._eintr_retry_call(fake_os_func, 666))
2080 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
2081
2082
Tim Golden126c2962010-08-11 14:20:40 +00002083@unittest.skipUnless(mswindows, "Windows-specific tests")
2084class CommandsWithSpaces (BaseTestCase):
2085
2086 def setUp(self):
2087 super().setUp()
2088 f, fname = mkstemp(".py", "te st")
2089 self.fname = fname.lower ()
2090 os.write(f, b"import sys;"
2091 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
2092 )
2093 os.close(f)
2094
2095 def tearDown(self):
2096 os.remove(self.fname)
2097 super().tearDown()
2098
2099 def with_spaces(self, *args, **kwargs):
2100 kwargs['stdout'] = subprocess.PIPE
2101 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00002102 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00002103 self.assertEqual(
2104 p.stdout.read ().decode("mbcs"),
2105 "2 [%r, 'ab cd']" % self.fname
2106 )
2107
2108 def test_shell_string_with_spaces(self):
2109 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002110 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2111 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002112
2113 def test_shell_sequence_with_spaces(self):
2114 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00002115 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00002116
2117 def test_noshell_string_with_spaces(self):
2118 # call() function with string argument with spaces on Windows
2119 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
2120 "ab cd"))
2121
2122 def test_noshell_sequence_with_spaces(self):
2123 # call() function with sequence argument with spaces on Windows
2124 self.with_spaces([sys.executable, self.fname, "ab cd"])
2125
Brian Curtin79cdb662010-12-03 02:46:02 +00002126
Georg Brandla86b2622012-02-20 21:34:57 +01002127class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00002128
2129 def test_pipe(self):
2130 with subprocess.Popen([sys.executable, "-c",
2131 "import sys;"
2132 "sys.stdout.write('stdout');"
2133 "sys.stderr.write('stderr');"],
2134 stdout=subprocess.PIPE,
2135 stderr=subprocess.PIPE) as proc:
2136 self.assertEqual(proc.stdout.read(), b"stdout")
2137 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2138
2139 self.assertTrue(proc.stdout.closed)
2140 self.assertTrue(proc.stderr.closed)
2141
2142 def test_returncode(self):
2143 with subprocess.Popen([sys.executable, "-c",
2144 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002145 pass
2146 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002147 self.assertEqual(proc.returncode, 100)
2148
2149 def test_communicate_stdin(self):
2150 with subprocess.Popen([sys.executable, "-c",
2151 "import sys;"
2152 "sys.exit(sys.stdin.read() == 'context')"],
2153 stdin=subprocess.PIPE) as proc:
2154 proc.communicate(b"context")
2155 self.assertEqual(proc.returncode, 1)
2156
2157 def test_invalid_args(self):
2158 with self.assertRaises(EnvironmentError) as c:
2159 with subprocess.Popen(['nonexisting_i_hope'],
2160 stdout=subprocess.PIPE,
2161 stderr=subprocess.PIPE) as proc:
2162 pass
2163
2164 if c.exception.errno != errno.ENOENT: # ignore "no such file"
2165 raise c.exception
2166
2167
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002168def test_main():
2169 unit_tests = (ProcessTestCase,
2170 POSIXProcessTestCase,
2171 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002172 CommandTests,
2173 ProcessTestCaseNoPoll,
2174 HelperFunctionTests,
2175 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02002176 ContextManagerTests,
2177 )
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002178
2179 support.run_unittest(*unit_tests)
2180 support.reap_children()
2181
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002182if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002183 unittest.main()