blob: 6fc61088b8f9d2c63c4b790deef91e11405d7b71 [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
Chris Jerdonekec3ea942012-09-30 00:10:28 -07002from test import script_helper
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003from test import support
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00004import subprocess
5import sys
6import signal
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04007import io
Andrew Svetlov82860712012-08-19 22:13:41 +03008import locale
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00009import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +000010import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000011import tempfile
12import time
Tim Peters3761e8d2004-10-13 04:07:12 +000013import re
Ezio Melotti184bdfb2010-02-18 09:37:05 +000014import sysconfig
Gregory P. Smithd23047b2010-12-04 09:10:44 +000015import warnings
Gregory P. Smith51ee2702010-12-13 07:59:39 +000016import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040017import shutil
Benjamin Petersonb870aa12011-12-10 12:44:25 -050018import gc
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030019import textwrap
Benjamin Peterson964561b2011-12-10 12:31:42 -050020
21try:
22 import resource
23except ImportError:
24 resource = None
25
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000026mswindows = (sys.platform == "win32")
27
28#
29# Depends on the following external programs: Python
30#
31
32if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000033 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
34 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000035else:
36 SETBINARY = ''
37
Florent Xiclunab1e94e82010-02-27 22:12:37 +000038
39try:
40 mkstemp = tempfile.mkstemp
41except AttributeError:
42 # tempfile.mkstemp is not available
43 def mkstemp():
44 """Replacement for mkstemp, calling mktemp."""
45 fname = tempfile.mktemp()
46 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
47
Tim Peters3761e8d2004-10-13 04:07:12 +000048
Florent Xiclunac049d872010-03-27 22:47:23 +000049class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000050 def setUp(self):
51 # Try to minimize the number of children we have so this test
52 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000053 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000054
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000055 def tearDown(self):
56 for inst in subprocess._active:
57 inst.wait()
58 subprocess._cleanup()
59 self.assertFalse(subprocess._active, "subprocess._active not empty")
60
Florent Xiclunab1e94e82010-02-27 22:12:37 +000061 def assertStderrEqual(self, stderr, expected, msg=None):
62 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
63 # shutdown time. That frustrates tests trying to check stderr produced
64 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000065 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040066 # strip_python_stderr also strips whitespace, so we do too.
67 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000068 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000069
Florent Xiclunac049d872010-03-27 22:47:23 +000070
71class ProcessTestCase(BaseTestCase):
72
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000073 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000074 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000075 rc = subprocess.call([sys.executable, "-c",
76 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000077 self.assertEqual(rc, 47)
78
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040079 def test_call_timeout(self):
80 # call() function with timeout argument; we want to test that the child
81 # process gets killed when the timeout expires. If the child isn't
82 # killed, this call will deadlock since subprocess.call waits for the
83 # child.
84 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
85 [sys.executable, "-c", "while True: pass"],
86 timeout=0.1)
87
Peter Astrand454f7672005-01-01 09:36:35 +000088 def test_check_call_zero(self):
89 # check_call() function with zero return code
90 rc = subprocess.check_call([sys.executable, "-c",
91 "import sys; sys.exit(0)"])
92 self.assertEqual(rc, 0)
93
94 def test_check_call_nonzero(self):
95 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000096 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +000097 subprocess.check_call([sys.executable, "-c",
98 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000099 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +0000100
Georg Brandlf9734072008-12-07 15:30:06 +0000101 def test_check_output(self):
102 # check_output() function with zero return code
103 output = subprocess.check_output(
104 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000105 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000106
107 def test_check_output_nonzero(self):
108 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000109 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000110 subprocess.check_output(
111 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000112 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000113
114 def test_check_output_stderr(self):
115 # check_output() function stderr redirected to stdout
116 output = subprocess.check_output(
117 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
118 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000119 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000120
121 def test_check_output_stdout_arg(self):
122 # check_output() function stderr redirected to stdout
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000123 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000124 output = subprocess.check_output(
125 [sys.executable, "-c", "print('will not be run')"],
126 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000127 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000128 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000129
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400130 def test_check_output_timeout(self):
131 # check_output() function with timeout arg
132 with self.assertRaises(subprocess.TimeoutExpired) as c:
133 output = subprocess.check_output(
134 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200135 "import sys, time\n"
136 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400137 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200138 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400139 # Some heavily loaded buildbots (sparc Debian 3.x) require
140 # this much time to start and print.
141 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400142 self.fail("Expected TimeoutExpired.")
143 self.assertEqual(c.exception.output, b'BDFL')
144
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000145 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000146 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000147 newenv = os.environ.copy()
148 newenv["FRUIT"] = "banana"
149 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000150 'import sys, os;'
151 'sys.exit(os.getenv("FRUIT")=="banana")'],
152 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000153 self.assertEqual(rc, 1)
154
Victor Stinner87b9bc32011-06-01 00:57:47 +0200155 def test_invalid_args(self):
156 # Popen() called with invalid arguments should raise TypeError
157 # but Popen.__del__ should not complain (issue #12085)
158 with support.captured_stderr() as s:
159 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
160 argcount = subprocess.Popen.__init__.__code__.co_argcount
161 too_many_args = [0] * (argcount + 1)
162 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
163 self.assertEqual(s.getvalue(), '')
164
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000165 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000166 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000167 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000168 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000169 self.addCleanup(p.stdout.close)
170 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000171 p.wait()
172 self.assertEqual(p.stdin, None)
173
174 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000175 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000176 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000177 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000178 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000179 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000180 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000181 self.addCleanup(p.stdin.close)
182 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000183 p.wait()
184 self.assertEqual(p.stdout, None)
185
186 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000187 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000188 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000189 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000190 self.addCleanup(p.stdout.close)
191 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000192 p.wait()
193 self.assertEqual(p.stderr, None)
194
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700195 # For use in the test_cwd* tests below.
196 def _normalize_cwd(self, cwd):
197 # Normalize an expected cwd (for Tru64 support).
198 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
199 # strings. See bug #1063571.
200 original_cwd = os.getcwd()
201 os.chdir(cwd)
202 cwd = os.getcwd()
203 os.chdir(original_cwd)
204 return cwd
205
206 # For use in the test_cwd* tests below.
207 def _split_python_path(self):
208 # Return normalized (python_dir, python_base).
209 python_path = os.path.realpath(sys.executable)
210 return os.path.split(python_path)
211
212 # For use in the test_cwd* tests below.
213 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
214 # Invoke Python via Popen, and assert that (1) the call succeeds,
215 # and that (2) the current working directory of the child process
216 # matches *expected_cwd*.
217 p = subprocess.Popen([python_arg, "-c",
218 "import os, sys; "
219 "sys.stdout.write(os.getcwd()); "
220 "sys.exit(47)"],
221 stdout=subprocess.PIPE,
222 **kwargs)
223 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000224 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700225 self.assertEqual(47, p.returncode)
226 normcase = os.path.normcase
227 self.assertEqual(normcase(expected_cwd),
228 normcase(p.stdout.read().decode("utf-8")))
229
230 def test_cwd(self):
231 # Check that cwd changes the cwd for the child process.
232 temp_dir = tempfile.gettempdir()
233 temp_dir = self._normalize_cwd(temp_dir)
234 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
235
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700236 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700237 def test_cwd_with_relative_arg(self):
238 # Check that Popen looks for args[0] relative to cwd if args[0]
239 # is relative.
240 python_dir, python_base = self._split_python_path()
241 rel_python = os.path.join(os.curdir, python_base)
242 with support.temp_cwd() as wrong_dir:
243 # Before calling with the correct cwd, confirm that the call fails
244 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700245 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700246 [rel_python])
Chris Jerdonek28714c82012-09-30 02:15:37 -0700247 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700248 [rel_python], cwd=wrong_dir)
249 python_dir = self._normalize_cwd(python_dir)
250 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
251
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700252 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700253 def test_cwd_with_relative_executable(self):
254 # Check that Popen looks for executable relative to cwd if executable
255 # is relative (and that executable takes precedence over args[0]).
256 python_dir, python_base = self._split_python_path()
257 rel_python = os.path.join(os.curdir, python_base)
258 doesntexist = "somethingyoudonthave"
259 with support.temp_cwd() as wrong_dir:
260 # Before calling with the correct cwd, confirm that the call fails
261 # without cwd and with the wrong cwd.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700262 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700263 [doesntexist], executable=rel_python)
Chris Jerdonek28714c82012-09-30 02:15:37 -0700264 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700265 [doesntexist], executable=rel_python,
266 cwd=wrong_dir)
267 python_dir = self._normalize_cwd(python_dir)
268 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
269 cwd=python_dir)
270
271 def test_cwd_with_absolute_arg(self):
272 # Check that Popen can find the executable when the cwd is wrong
273 # if args[0] is an absolute path.
274 python_dir, python_base = self._split_python_path()
275 abs_python = os.path.join(python_dir, python_base)
276 rel_python = os.path.join(os.curdir, python_base)
277 with script_helper.temp_dir() as wrong_dir:
278 # Before calling with an absolute path, confirm that using a
279 # relative path fails.
Chris Jerdonek28714c82012-09-30 02:15:37 -0700280 self.assertRaises(FileNotFoundError, subprocess.Popen,
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700281 [rel_python], cwd=wrong_dir)
282 wrong_dir = self._normalize_cwd(wrong_dir)
283 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
284
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100285 @unittest.skipIf(sys.base_prefix != sys.prefix,
286 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000287 def test_executable_with_cwd(self):
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700288 python_dir, python_base = self._split_python_path()
289 python_dir = self._normalize_cwd(python_dir)
290 self._assert_cwd(python_dir, "somethingyoudonthave",
291 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000292
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100293 @unittest.skipIf(sys.base_prefix != sys.prefix,
294 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000295 @unittest.skipIf(sysconfig.is_python_build(),
296 "need an installed Python. See #7774")
297 def test_executable_without_cwd(self):
298 # For a normal installation, it should work without 'cwd'
299 # argument. For test runs in the build directory, see #7774.
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700300 self._assert_cwd('', "somethingyoudonthave", executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000301
Andrew Svetlov1a53c0c2012-10-05 22:52:15 +0300302 def test_executable_precedence(self):
303 # To the precedence of executable argument over args[0]
304 # For a normal installation, it should work without 'cwd'
305 # argument. For test runs in the build directory, see #7774.
306 python_dir = os.path.dirname(os.path.realpath(sys.executable))
307 p = subprocess.Popen(["nonexistent","-c",'import sys; sys.exit(42)'],
308 executable=sys.executable, cwd=python_dir)
309 p.wait()
310 self.assertEqual(p.returncode, 42)
311
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000312 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000313 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000314 p = subprocess.Popen([sys.executable, "-c",
315 'import sys; sys.exit(sys.stdin.read() == "pear")'],
316 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000317 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000318 p.stdin.close()
319 p.wait()
320 self.assertEqual(p.returncode, 1)
321
322 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000323 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000324 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000325 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000326 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000327 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000328 os.lseek(d, 0, 0)
329 p = subprocess.Popen([sys.executable, "-c",
330 'import sys; sys.exit(sys.stdin.read() == "pear")'],
331 stdin=d)
332 p.wait()
333 self.assertEqual(p.returncode, 1)
334
335 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000336 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000337 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000338 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000339 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000340 tf.seek(0)
341 p = subprocess.Popen([sys.executable, "-c",
342 'import sys; sys.exit(sys.stdin.read() == "pear")'],
343 stdin=tf)
344 p.wait()
345 self.assertEqual(p.returncode, 1)
346
347 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000348 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000349 p = subprocess.Popen([sys.executable, "-c",
350 'import sys; sys.stdout.write("orange")'],
351 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000352 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000353 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000354
355 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000356 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000357 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000358 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000359 d = tf.fileno()
360 p = subprocess.Popen([sys.executable, "-c",
361 'import sys; sys.stdout.write("orange")'],
362 stdout=d)
363 p.wait()
364 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000365 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000366
367 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000368 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000369 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000370 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000371 p = subprocess.Popen([sys.executable, "-c",
372 'import sys; sys.stdout.write("orange")'],
373 stdout=tf)
374 p.wait()
375 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000376 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000377
378 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000379 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000380 p = subprocess.Popen([sys.executable, "-c",
381 'import sys; sys.stderr.write("strawberry")'],
382 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000383 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000384 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000385
386 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000387 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000388 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000389 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000390 d = tf.fileno()
391 p = subprocess.Popen([sys.executable, "-c",
392 'import sys; sys.stderr.write("strawberry")'],
393 stderr=d)
394 p.wait()
395 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000396 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000397
398 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000399 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000400 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000401 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000402 p = subprocess.Popen([sys.executable, "-c",
403 'import sys; sys.stderr.write("strawberry")'],
404 stderr=tf)
405 p.wait()
406 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000407 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000408
409 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000410 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000411 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000412 'import sys;'
413 'sys.stdout.write("apple");'
414 'sys.stdout.flush();'
415 'sys.stderr.write("orange")'],
416 stdout=subprocess.PIPE,
417 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000418 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000419 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000420
421 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000422 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000423 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000424 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000425 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000426 'import sys;'
427 'sys.stdout.write("apple");'
428 'sys.stdout.flush();'
429 'sys.stderr.write("orange")'],
430 stdout=tf,
431 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000432 p.wait()
433 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000434 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000435
Thomas Wouters89f507f2006-12-13 04:49:30 +0000436 def test_stdout_filedes_of_stdout(self):
437 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000438 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000439 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000440 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000441
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200442 def test_stdout_devnull(self):
443 p = subprocess.Popen([sys.executable, "-c",
444 'for i in range(10240):'
445 'print("x" * 1024)'],
446 stdout=subprocess.DEVNULL)
447 p.wait()
448 self.assertEqual(p.stdout, None)
449
450 def test_stderr_devnull(self):
451 p = subprocess.Popen([sys.executable, "-c",
452 'import sys\n'
453 'for i in range(10240):'
454 'sys.stderr.write("x" * 1024)'],
455 stderr=subprocess.DEVNULL)
456 p.wait()
457 self.assertEqual(p.stderr, None)
458
459 def test_stdin_devnull(self):
460 p = subprocess.Popen([sys.executable, "-c",
461 'import sys;'
462 'sys.stdin.read(1)'],
463 stdin=subprocess.DEVNULL)
464 p.wait()
465 self.assertEqual(p.stdin, None)
466
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000467 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000468 newenv = os.environ.copy()
469 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200470 with subprocess.Popen([sys.executable, "-c",
471 'import sys,os;'
472 'sys.stdout.write(os.getenv("FRUIT"))'],
473 stdout=subprocess.PIPE,
474 env=newenv) as p:
475 stdout, stderr = p.communicate()
476 self.assertEqual(stdout, b"orange")
477
Victor Stinner62d51182011-06-23 01:02:25 +0200478 # Windows requires at least the SYSTEMROOT environment variable to start
479 # Python
480 @unittest.skipIf(sys.platform == 'win32',
481 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200482 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200483 'the python library cannot be loaded '
484 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200485 def test_empty_env(self):
486 with subprocess.Popen([sys.executable, "-c",
487 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200488 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200489 stdout=subprocess.PIPE,
490 env={}) as p:
491 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200492 self.assertIn(stdout.strip(),
493 (b"[]",
494 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
495 # environment
496 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000497
Peter Astrandcbac93c2005-03-03 20:24:28 +0000498 def test_communicate_stdin(self):
499 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000500 'import sys;'
501 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000502 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000503 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000504 self.assertEqual(p.returncode, 1)
505
506 def test_communicate_stdout(self):
507 p = subprocess.Popen([sys.executable, "-c",
508 'import sys; sys.stdout.write("pineapple")'],
509 stdout=subprocess.PIPE)
510 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000511 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000512 self.assertEqual(stderr, None)
513
514 def test_communicate_stderr(self):
515 p = subprocess.Popen([sys.executable, "-c",
516 'import sys; sys.stderr.write("pineapple")'],
517 stderr=subprocess.PIPE)
518 (stdout, stderr) = p.communicate()
519 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000520 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000521
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000522 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000523 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000524 'import sys,os;'
525 'sys.stderr.write("pineapple");'
526 'sys.stdout.write(sys.stdin.read())'],
527 stdin=subprocess.PIPE,
528 stdout=subprocess.PIPE,
529 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000530 self.addCleanup(p.stdout.close)
531 self.addCleanup(p.stderr.close)
532 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000533 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000534 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000535 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000536
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400537 def test_communicate_timeout(self):
538 p = subprocess.Popen([sys.executable, "-c",
539 'import sys,os,time;'
540 'sys.stderr.write("pineapple\\n");'
541 'time.sleep(1);'
542 'sys.stderr.write("pear\\n");'
543 'sys.stdout.write(sys.stdin.read())'],
544 universal_newlines=True,
545 stdin=subprocess.PIPE,
546 stdout=subprocess.PIPE,
547 stderr=subprocess.PIPE)
548 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
549 timeout=0.3)
550 # Make sure we can keep waiting for it, and that we get the whole output
551 # after it completes.
552 (stdout, stderr) = p.communicate()
553 self.assertEqual(stdout, "banana")
554 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
555
556 def test_communicate_timeout_large_ouput(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200557 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400558 p = subprocess.Popen([sys.executable, "-c",
559 'import sys,os,time;'
560 'sys.stdout.write("a" * (64 * 1024));'
561 'time.sleep(0.2);'
562 'sys.stdout.write("a" * (64 * 1024));'
563 'time.sleep(0.2);'
564 'sys.stdout.write("a" * (64 * 1024));'
565 'time.sleep(0.2);'
566 'sys.stdout.write("a" * (64 * 1024));'],
567 stdout=subprocess.PIPE)
568 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
569 (stdout, _) = p.communicate()
570 self.assertEqual(len(stdout), 4 * 64 * 1024)
571
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000572 # Test for the fd leak reported in http://bugs.python.org/issue2791.
573 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000574 for stdin_pipe in (False, True):
575 for stdout_pipe in (False, True):
576 for stderr_pipe in (False, True):
577 options = {}
578 if stdin_pipe:
579 options['stdin'] = subprocess.PIPE
580 if stdout_pipe:
581 options['stdout'] = subprocess.PIPE
582 if stderr_pipe:
583 options['stderr'] = subprocess.PIPE
584 if not options:
585 continue
586 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
587 p.communicate()
588 if p.stdin is not None:
589 self.assertTrue(p.stdin.closed)
590 if p.stdout is not None:
591 self.assertTrue(p.stdout.closed)
592 if p.stderr is not None:
593 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000594
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000595 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000596 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000597 p = subprocess.Popen([sys.executable, "-c",
598 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000599 (stdout, stderr) = p.communicate()
600 self.assertEqual(stdout, None)
601 self.assertEqual(stderr, None)
602
603 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000604 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000605 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000606 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000607 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000608 os.close(x)
609 os.close(y)
610 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000611 'import sys,os;'
612 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200613 'sys.stderr.write("x" * %d);'
614 'sys.stdout.write(sys.stdin.read())' %
615 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000616 stdin=subprocess.PIPE,
617 stdout=subprocess.PIPE,
618 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000619 self.addCleanup(p.stdout.close)
620 self.addCleanup(p.stderr.close)
621 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200622 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000623 (stdout, stderr) = p.communicate(string_to_write)
624 self.assertEqual(stdout, string_to_write)
625
626 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000627 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000628 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000629 'import sys,os;'
630 'sys.stdout.write(sys.stdin.read())'],
631 stdin=subprocess.PIPE,
632 stdout=subprocess.PIPE,
633 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000634 self.addCleanup(p.stdout.close)
635 self.addCleanup(p.stderr.close)
636 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000637 p.stdin.write(b"banana")
638 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000639 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000640 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000641
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000642 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000643 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000644 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200645 'buf = sys.stdout.buffer;'
646 'buf.write(sys.stdin.readline().encode());'
647 'buf.flush();'
648 'buf.write(b"line2\\n");'
649 'buf.flush();'
650 'buf.write(sys.stdin.read().encode());'
651 'buf.flush();'
652 'buf.write(b"line4\\n");'
653 'buf.flush();'
654 'buf.write(b"line5\\r\\n");'
655 'buf.flush();'
656 'buf.write(b"line6\\r");'
657 'buf.flush();'
658 'buf.write(b"\\nline7");'
659 'buf.flush();'
660 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200661 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000662 stdout=subprocess.PIPE,
663 universal_newlines=1)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200664 p.stdin.write("line1\n")
665 self.assertEqual(p.stdout.readline(), "line1\n")
666 p.stdin.write("line3\n")
667 p.stdin.close()
Brian Curtin3c6a9512010-11-05 03:58:52 +0000668 self.addCleanup(p.stdout.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200669 self.assertEqual(p.stdout.readline(),
670 "line2\n")
671 self.assertEqual(p.stdout.read(6),
672 "line3\n")
673 self.assertEqual(p.stdout.read(),
674 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000675
676 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000677 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000678 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000679 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200680 'buf = sys.stdout.buffer;'
681 'buf.write(b"line2\\n");'
682 'buf.flush();'
683 'buf.write(b"line4\\n");'
684 'buf.flush();'
685 'buf.write(b"line5\\r\\n");'
686 'buf.flush();'
687 'buf.write(b"line6\\r");'
688 'buf.flush();'
689 'buf.write(b"\\nline7");'
690 'buf.flush();'
691 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200692 stderr=subprocess.PIPE,
693 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000694 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000695 self.addCleanup(p.stdout.close)
696 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000697 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200698 self.assertEqual(stdout,
699 "line2\nline4\nline5\nline6\nline7\nline8")
700
701 def test_universal_newlines_communicate_stdin(self):
702 # universal newlines through communicate(), with only stdin
703 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300704 'import sys,os;' + SETBINARY + textwrap.dedent('''
705 s = sys.stdin.readline()
706 assert s == "line1\\n", repr(s)
707 s = sys.stdin.read()
708 assert s == "line3\\n", repr(s)
709 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200710 stdin=subprocess.PIPE,
711 universal_newlines=1)
712 (stdout, stderr) = p.communicate("line1\nline3\n")
713 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000714
Andrew Svetlovf3765072012-08-14 18:35:17 +0300715 def test_universal_newlines_communicate_input_none(self):
716 # Test communicate(input=None) with universal newlines.
717 #
718 # We set stdout to PIPE because, as of this writing, a different
719 # code path is tested when the number of pipes is zero or one.
720 p = subprocess.Popen([sys.executable, "-c", "pass"],
721 stdin=subprocess.PIPE,
722 stdout=subprocess.PIPE,
723 universal_newlines=True)
724 p.communicate()
725 self.assertEqual(p.returncode, 0)
726
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300727 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300728 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300729 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300730 'import sys,os;' + SETBINARY + textwrap.dedent('''
731 s = sys.stdin.buffer.readline()
732 sys.stdout.buffer.write(s)
733 sys.stdout.buffer.write(b"line2\\r")
734 sys.stderr.buffer.write(b"eline2\\n")
735 s = sys.stdin.buffer.read()
736 sys.stdout.buffer.write(s)
737 sys.stdout.buffer.write(b"line4\\n")
738 sys.stdout.buffer.write(b"line5\\r\\n")
739 sys.stderr.buffer.write(b"eline6\\r")
740 sys.stderr.buffer.write(b"eline7\\r\\nz")
741 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300742 stdin=subprocess.PIPE,
743 stderr=subprocess.PIPE,
744 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300745 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300746 self.addCleanup(p.stdout.close)
747 self.addCleanup(p.stderr.close)
748 (stdout, stderr) = p.communicate("line1\nline3\n")
749 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300750 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300751 # Python debug build push something like "[42442 refs]\n"
752 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300753 # Don't use assertStderrEqual because it strips CR and LF from output.
754 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300755
Andrew Svetlov82860712012-08-19 22:13:41 +0300756 def test_universal_newlines_communicate_encodings(self):
757 # Check that universal newlines mode works for various encodings,
758 # in particular for encodings in the UTF-16 and UTF-32 families.
759 # See issue #15595.
760 #
761 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
762 # without, and UTF-16 and UTF-32.
763 for encoding in ['utf-16', 'utf-32-be']:
764 old_getpreferredencoding = locale.getpreferredencoding
765 # Indirectly via io.TextIOWrapper, Popen() defaults to
766 # locale.getpreferredencoding(False) and earlier in Python 3.2 to
767 # locale.getpreferredencoding().
768 def getpreferredencoding(do_setlocale=True):
769 return encoding
770 code = ("import sys; "
771 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
772 encoding)
773 args = [sys.executable, '-c', code]
774 try:
775 locale.getpreferredencoding = getpreferredencoding
776 # We set stdin to be non-None because, as of this writing,
777 # a different code path is used when the number of pipes is
778 # zero or one.
779 popen = subprocess.Popen(args, universal_newlines=True,
780 stdin=subprocess.PIPE,
781 stdout=subprocess.PIPE)
782 stdout, stderr = popen.communicate(input='')
783 finally:
784 locale.getpreferredencoding = old_getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300785 self.assertEqual(stdout, '1\n2\n3\n4')
786
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000787 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000788 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000789 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000790 max_handles = 1026 # too much for most UNIX systems
791 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000792 max_handles = 2050 # too much for (at least some) Windows setups
793 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400794 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000795 try:
796 for i in range(max_handles):
797 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400798 tmpfile = os.path.join(tmpdir, support.TESTFN)
799 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000800 except OSError as e:
801 if e.errno != errno.EMFILE:
802 raise
803 break
804 else:
805 self.skipTest("failed to reach the file descriptor limit "
806 "(tried %d)" % max_handles)
807 # Close a couple of them (should be enough for a subprocess)
808 for i in range(10):
809 os.close(handles.pop())
810 # Loop creating some subprocesses. If one of them leaks some fds,
811 # the next loop iteration will fail by reaching the max fd limit.
812 for i in range(15):
813 p = subprocess.Popen([sys.executable, "-c",
814 "import sys;"
815 "sys.stdout.write(sys.stdin.read())"],
816 stdin=subprocess.PIPE,
817 stdout=subprocess.PIPE,
818 stderr=subprocess.PIPE)
819 data = p.communicate(b"lime")[0]
820 self.assertEqual(data, b"lime")
821 finally:
822 for h in handles:
823 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400824 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000825
826 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000827 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
828 '"a b c" d e')
829 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
830 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000831 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
832 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000833 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
834 'a\\\\\\b "de fg" h')
835 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
836 'a\\\\\\"b c d')
837 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
838 '"a\\\\b c" d e')
839 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
840 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000841 self.assertEqual(subprocess.list2cmdline(['ab', '']),
842 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000843
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000844 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200845 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +0200846 "import os; os.read(0, 1)"],
847 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200848 self.addCleanup(p.stdin.close)
849 self.assertIsNone(p.poll())
850 os.write(p.stdin.fileno(), b'A')
851 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000852 # Subsequent invocations should just return the returncode
853 self.assertEqual(p.poll(), 0)
854
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000855 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200856 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000857 self.assertEqual(p.wait(), 0)
858 # Subsequent invocations should just return the returncode
859 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000860
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400861 def test_wait_timeout(self):
862 p = subprocess.Popen([sys.executable,
Reid Kleckner93479cc2011-03-14 19:32:41 -0400863 "-c", "import time; time.sleep(0.1)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -0400864 with self.assertRaises(subprocess.TimeoutExpired) as c:
865 p.wait(timeout=0.01)
866 self.assertIn("0.01", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -0400867 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
868 # time to start.
869 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400870
Peter Astrand738131d2004-11-30 21:04:45 +0000871 def test_invalid_bufsize(self):
872 # an invalid type of the bufsize argument should raise
873 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000874 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000875 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000876
Guido van Rossum46a05a72007-06-07 21:56:45 +0000877 def test_bufsize_is_none(self):
878 # bufsize=None should be the same as bufsize=0.
879 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
880 self.assertEqual(p.wait(), 0)
881 # Again with keyword arg
882 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
883 self.assertEqual(p.wait(), 0)
884
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000885 def test_leaking_fds_on_error(self):
886 # see bug #5179: Popen leaks file descriptors to PIPEs if
887 # the child fails to execute; this will eventually exhaust
888 # the maximum number of open fds. 1024 seems a very common
889 # value for that limit, but Windows has 2048, so we loop
890 # 1024 times (each call leaked two fds).
891 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000892 # Windows raises IOError. Others raise OSError.
893 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000894 subprocess.Popen(['nonexisting_i_hope'],
895 stdout=subprocess.PIPE,
896 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400897 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400898 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000899 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000900
Victor Stinnerb3693582010-05-21 20:13:12 +0000901 def test_issue8780(self):
902 # Ensure that stdout is inherited from the parent
903 # if stdout=PIPE is not used
904 code = ';'.join((
905 'import subprocess, sys',
906 'retcode = subprocess.call('
907 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
908 'assert retcode == 0'))
909 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000910 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000911
Tim Goldenaf5ac392010-08-06 13:03:56 +0000912 def test_handles_closed_on_exception(self):
913 # If CreateProcess exits with an error, ensure the
914 # duplicate output handles are released
915 ifhandle, ifname = mkstemp()
916 ofhandle, ofname = mkstemp()
917 efhandle, efname = mkstemp()
918 try:
919 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
920 stderr=efhandle)
921 except OSError:
922 os.close(ifhandle)
923 os.remove(ifname)
924 os.close(ofhandle)
925 os.remove(ofname)
926 os.close(efhandle)
927 os.remove(efname)
928 self.assertFalse(os.path.exists(ifname))
929 self.assertFalse(os.path.exists(ofname))
930 self.assertFalse(os.path.exists(efname))
931
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200932 def test_communicate_epipe(self):
933 # Issue 10963: communicate() should hide EPIPE
934 p = subprocess.Popen([sys.executable, "-c", 'pass'],
935 stdin=subprocess.PIPE,
936 stdout=subprocess.PIPE,
937 stderr=subprocess.PIPE)
938 self.addCleanup(p.stdout.close)
939 self.addCleanup(p.stderr.close)
940 self.addCleanup(p.stdin.close)
941 p.communicate(b"x" * 2**20)
942
943 def test_communicate_epipe_only_stdin(self):
944 # Issue 10963: communicate() should hide EPIPE
945 p = subprocess.Popen([sys.executable, "-c", 'pass'],
946 stdin=subprocess.PIPE)
947 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200948 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200949 p.communicate(b"x" * 2**20)
950
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200951 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
952 "Requires signal.SIGUSR1")
953 @unittest.skipUnless(hasattr(os, 'kill'),
954 "Requires os.kill")
955 @unittest.skipUnless(hasattr(os, 'getppid'),
956 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200957 def test_communicate_eintr(self):
958 # Issue #12493: communicate() should handle EINTR
959 def handler(signum, frame):
960 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200961 old_handler = signal.signal(signal.SIGUSR1, handler)
962 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200963
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200964 args = [sys.executable, "-c",
965 'import os, signal;'
966 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200967 for stream in ('stdout', 'stderr'):
968 kw = {stream: subprocess.PIPE}
969 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200970 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200971 process.communicate()
972
Tim Peterse718f612004-10-12 21:51:32 +0000973
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000974# context manager
975class _SuppressCoreFiles(object):
976 """Try to prevent core files from being created."""
977 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000978
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000979 def __enter__(self):
980 """Try to save previous ulimit, then set it to (0, 0)."""
Benjamin Peterson964561b2011-12-10 12:31:42 -0500981 if resource is not None:
982 try:
983 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
984 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
985 except (ValueError, resource.error):
986 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000987
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000988 if sys.platform == 'darwin':
989 # Check if the 'Crash Reporter' on OSX was configured
990 # in 'Developer' mode and warn that it will get triggered
991 # when it is.
992 #
993 # This assumes that this context manager is used in tests
994 # that might trigger the next manager.
995 value = subprocess.Popen(['/usr/bin/defaults', 'read',
996 'com.apple.CrashReporter', 'DialogType'],
997 stdout=subprocess.PIPE).communicate()[0]
998 if value.strip() == b'developer':
999 print("this tests triggers the Crash Reporter, "
1000 "that is intentional", end='')
1001 sys.stdout.flush()
1002
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001003 def __exit__(self, *args):
1004 """Return core file behavior to default."""
1005 if self.old_limit is None:
1006 return
Benjamin Peterson964561b2011-12-10 12:31:42 -05001007 if resource is not None:
1008 try:
1009 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
1010 except (ValueError, resource.error):
1011 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001012
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001013
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001014@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001015class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001016
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001017 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001018 nonexistent_dir = "/_this/pa.th/does/not/exist"
1019 try:
1020 os.chdir(nonexistent_dir)
1021 except OSError as e:
1022 # This avoids hard coding the errno value or the OS perror()
1023 # string and instead capture the exception that we want to see
1024 # below for comparison.
1025 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +00001026 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001027 else:
1028 self.fail("chdir to nonexistant directory %s succeeded." %
1029 nonexistent_dir)
1030
1031 # Error in the child re-raised in the parent.
1032 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001033 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001034 cwd=nonexistent_dir)
1035 except OSError as e:
1036 # Test that the child process chdir failure actually makes
1037 # it up to the parent process as the correct exception.
1038 self.assertEqual(desired_exception.errno, e.errno)
1039 self.assertEqual(desired_exception.strerror, e.strerror)
1040 else:
1041 self.fail("Expected OSError: %s" % desired_exception)
1042
1043 def test_restore_signals(self):
1044 # Code coverage for both values of restore_signals to make sure it
1045 # at least does not blow up.
1046 # A test for behavior would be complex. Contributions welcome.
1047 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1048 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1049
1050 def test_start_new_session(self):
1051 # For code coverage of calling setsid(). We don't care if we get an
1052 # EPERM error from it depending on the test execution environment, that
1053 # still indicates that it was called.
1054 try:
1055 output = subprocess.check_output(
1056 [sys.executable, "-c",
1057 "import os; print(os.getpgid(os.getpid()))"],
1058 start_new_session=True)
1059 except OSError as e:
1060 if e.errno != errno.EPERM:
1061 raise
1062 else:
1063 parent_pgid = os.getpgid(os.getpid())
1064 child_pgid = int(output)
1065 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001066
1067 def test_run_abort(self):
1068 # returncode handles signal termination
1069 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001070 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001071 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001072 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001073 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001074
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001075 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001076 # DISCLAIMER: Setting environment variables is *not* a good use
1077 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001078 p = subprocess.Popen([sys.executable, "-c",
1079 'import sys,os;'
1080 'sys.stdout.write(os.getenv("FRUIT"))'],
1081 stdout=subprocess.PIPE,
1082 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +00001083 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001084 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001085
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001086 def test_preexec_exception(self):
1087 def raise_it():
1088 raise ValueError("What if two swallows carried a coconut?")
1089 try:
1090 p = subprocess.Popen([sys.executable, "-c", ""],
1091 preexec_fn=raise_it)
1092 except RuntimeError as e:
1093 self.assertTrue(
1094 subprocess._posixsubprocess,
1095 "Expected a ValueError from the preexec_fn")
1096 except ValueError as e:
1097 self.assertIn("coconut", e.args[0])
1098 else:
1099 self.fail("Exception raised by preexec_fn did not make it "
1100 "to the parent process.")
1101
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001102 def test_preexec_gc_module_failure(self):
1103 # This tests the code that disables garbage collection if the child
1104 # process will execute any Python.
1105 def raise_runtime_error():
1106 raise RuntimeError("this shouldn't escape")
1107 enabled = gc.isenabled()
1108 orig_gc_disable = gc.disable
1109 orig_gc_isenabled = gc.isenabled
1110 try:
1111 gc.disable()
1112 self.assertFalse(gc.isenabled())
1113 subprocess.call([sys.executable, '-c', ''],
1114 preexec_fn=lambda: None)
1115 self.assertFalse(gc.isenabled(),
1116 "Popen enabled gc when it shouldn't.")
1117
1118 gc.enable()
1119 self.assertTrue(gc.isenabled())
1120 subprocess.call([sys.executable, '-c', ''],
1121 preexec_fn=lambda: None)
1122 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1123
1124 gc.disable = raise_runtime_error
1125 self.assertRaises(RuntimeError, subprocess.Popen,
1126 [sys.executable, '-c', ''],
1127 preexec_fn=lambda: None)
1128
1129 del gc.isenabled # force an AttributeError
1130 self.assertRaises(AttributeError, subprocess.Popen,
1131 [sys.executable, '-c', ''],
1132 preexec_fn=lambda: None)
1133 finally:
1134 gc.disable = orig_gc_disable
1135 gc.isenabled = orig_gc_isenabled
1136 if not enabled:
1137 gc.disable()
1138
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001139 def test_args_string(self):
1140 # args is a string
1141 fd, fname = mkstemp()
1142 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001143 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001144 fobj.write("#!/bin/sh\n")
1145 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1146 sys.executable)
1147 os.chmod(fname, 0o700)
1148 p = subprocess.Popen(fname)
1149 p.wait()
1150 os.remove(fname)
1151 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001152
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001153 def test_invalid_args(self):
1154 # invalid arguments should raise ValueError
1155 self.assertRaises(ValueError, subprocess.call,
1156 [sys.executable, "-c",
1157 "import sys; sys.exit(47)"],
1158 startupinfo=47)
1159 self.assertRaises(ValueError, subprocess.call,
1160 [sys.executable, "-c",
1161 "import sys; sys.exit(47)"],
1162 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001163
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001164 def test_shell_sequence(self):
1165 # Run command through the shell (sequence)
1166 newenv = os.environ.copy()
1167 newenv["FRUIT"] = "apple"
1168 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1169 stdout=subprocess.PIPE,
1170 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001171 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001172 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001173
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001174 def test_shell_string(self):
1175 # Run command through the shell (string)
1176 newenv = os.environ.copy()
1177 newenv["FRUIT"] = "apple"
1178 p = subprocess.Popen("echo $FRUIT", shell=1,
1179 stdout=subprocess.PIPE,
1180 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001181 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001182 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001183
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001184 def test_call_string(self):
1185 # call() function with string argument on UNIX
1186 fd, fname = mkstemp()
1187 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001188 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001189 fobj.write("#!/bin/sh\n")
1190 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1191 sys.executable)
1192 os.chmod(fname, 0o700)
1193 rc = subprocess.call(fname)
1194 os.remove(fname)
1195 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001196
Stefan Krah9542cc62010-07-19 14:20:53 +00001197 def test_specific_shell(self):
1198 # Issue #9265: Incorrect name passed as arg[0].
1199 shells = []
1200 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1201 for name in ['bash', 'ksh']:
1202 sh = os.path.join(prefix, name)
1203 if os.path.isfile(sh):
1204 shells.append(sh)
1205 if not shells: # Will probably work for any shell but csh.
1206 self.skipTest("bash or ksh required for this test")
1207 sh = '/bin/sh'
1208 if os.path.isfile(sh) and not os.path.islink(sh):
1209 # Test will fail if /bin/sh is a symlink to csh.
1210 shells.append(sh)
1211 for sh in shells:
1212 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1213 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001214 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001215 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1216
Florent Xicluna4886d242010-03-08 13:27:26 +00001217 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001218 # Do not inherit file handles from the parent.
1219 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001220 p = subprocess.Popen([sys.executable, "-c", """if 1:
1221 import sys, time
1222 sys.stdout.write('x\\n')
1223 sys.stdout.flush()
1224 time.sleep(30)
1225 """],
1226 close_fds=True,
1227 stdin=subprocess.PIPE,
1228 stdout=subprocess.PIPE,
1229 stderr=subprocess.PIPE)
1230 # Wait for the interpreter to be completely initialized before
1231 # sending any signal.
1232 p.stdout.read(1)
1233 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001234 return p
1235
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001236 def _kill_dead_process(self, method, *args):
1237 # Do not inherit file handles from the parent.
1238 # It should fix failures on some platforms.
1239 p = subprocess.Popen([sys.executable, "-c", """if 1:
1240 import sys, time
1241 sys.stdout.write('x\\n')
1242 sys.stdout.flush()
1243 """],
1244 close_fds=True,
1245 stdin=subprocess.PIPE,
1246 stdout=subprocess.PIPE,
1247 stderr=subprocess.PIPE)
1248 # Wait for the interpreter to be completely initialized before
1249 # sending any signal.
1250 p.stdout.read(1)
1251 # The process should end after this
1252 time.sleep(1)
1253 # This shouldn't raise even though the child is now dead
1254 getattr(p, method)(*args)
1255 p.communicate()
1256
Florent Xicluna4886d242010-03-08 13:27:26 +00001257 def test_send_signal(self):
1258 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001259 _, stderr = p.communicate()
1260 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001261 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001262
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001263 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001264 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001265 _, stderr = p.communicate()
1266 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001267 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001268
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001269 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001270 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001271 _, stderr = p.communicate()
1272 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001273 self.assertEqual(p.wait(), -signal.SIGTERM)
1274
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001275 def test_send_signal_dead(self):
1276 # Sending a signal to a dead process
1277 self._kill_dead_process('send_signal', signal.SIGINT)
1278
1279 def test_kill_dead(self):
1280 # Killing a dead process
1281 self._kill_dead_process('kill')
1282
1283 def test_terminate_dead(self):
1284 # Terminating a dead process
1285 self._kill_dead_process('terminate')
1286
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001287 def check_close_std_fds(self, fds):
1288 # Issue #9905: test that subprocess pipes still work properly with
1289 # some standard fds closed
1290 stdin = 0
1291 newfds = []
1292 for a in fds:
1293 b = os.dup(a)
1294 newfds.append(b)
1295 if a == 0:
1296 stdin = b
1297 try:
1298 for fd in fds:
1299 os.close(fd)
1300 out, err = subprocess.Popen([sys.executable, "-c",
1301 'import sys;'
1302 'sys.stdout.write("apple");'
1303 'sys.stdout.flush();'
1304 'sys.stderr.write("orange")'],
1305 stdin=stdin,
1306 stdout=subprocess.PIPE,
1307 stderr=subprocess.PIPE).communicate()
1308 err = support.strip_python_stderr(err)
1309 self.assertEqual((out, err), (b'apple', b'orange'))
1310 finally:
1311 for b, a in zip(newfds, fds):
1312 os.dup2(b, a)
1313 for b in newfds:
1314 os.close(b)
1315
1316 def test_close_fd_0(self):
1317 self.check_close_std_fds([0])
1318
1319 def test_close_fd_1(self):
1320 self.check_close_std_fds([1])
1321
1322 def test_close_fd_2(self):
1323 self.check_close_std_fds([2])
1324
1325 def test_close_fds_0_1(self):
1326 self.check_close_std_fds([0, 1])
1327
1328 def test_close_fds_0_2(self):
1329 self.check_close_std_fds([0, 2])
1330
1331 def test_close_fds_1_2(self):
1332 self.check_close_std_fds([1, 2])
1333
1334 def test_close_fds_0_1_2(self):
1335 # Issue #10806: test that subprocess pipes still work properly with
1336 # all standard fds closed.
1337 self.check_close_std_fds([0, 1, 2])
1338
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001339 def test_remapping_std_fds(self):
1340 # open up some temporary files
1341 temps = [mkstemp() for i in range(3)]
1342 try:
1343 temp_fds = [fd for fd, fname in temps]
1344
1345 # unlink the files -- we won't need to reopen them
1346 for fd, fname in temps:
1347 os.unlink(fname)
1348
1349 # write some data to what will become stdin, and rewind
1350 os.write(temp_fds[1], b"STDIN")
1351 os.lseek(temp_fds[1], 0, 0)
1352
1353 # move the standard file descriptors out of the way
1354 saved_fds = [os.dup(fd) for fd in range(3)]
1355 try:
1356 # duplicate the file objects over the standard fd's
1357 for fd, temp_fd in enumerate(temp_fds):
1358 os.dup2(temp_fd, fd)
1359
1360 # now use those files in the "wrong" order, so that subprocess
1361 # has to rearrange them in the child
1362 p = subprocess.Popen([sys.executable, "-c",
1363 'import sys; got = sys.stdin.read();'
1364 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1365 stdin=temp_fds[1],
1366 stdout=temp_fds[2],
1367 stderr=temp_fds[0])
1368 p.wait()
1369 finally:
1370 # restore the original fd's underneath sys.stdin, etc.
1371 for std, saved in enumerate(saved_fds):
1372 os.dup2(saved, std)
1373 os.close(saved)
1374
1375 for fd in temp_fds:
1376 os.lseek(fd, 0, 0)
1377
1378 out = os.read(temp_fds[2], 1024)
1379 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1380 self.assertEqual(out, b"got STDIN")
1381 self.assertEqual(err, b"err")
1382
1383 finally:
1384 for fd in temp_fds:
1385 os.close(fd)
1386
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001387 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1388 # open up some temporary files
1389 temps = [mkstemp() for i in range(3)]
1390 temp_fds = [fd for fd, fname in temps]
1391 try:
1392 # unlink the files -- we won't need to reopen them
1393 for fd, fname in temps:
1394 os.unlink(fname)
1395
1396 # save a copy of the standard file descriptors
1397 saved_fds = [os.dup(fd) for fd in range(3)]
1398 try:
1399 # duplicate the temp files over the standard fd's 0, 1, 2
1400 for fd, temp_fd in enumerate(temp_fds):
1401 os.dup2(temp_fd, fd)
1402
1403 # write some data to what will become stdin, and rewind
1404 os.write(stdin_no, b"STDIN")
1405 os.lseek(stdin_no, 0, 0)
1406
1407 # now use those files in the given order, so that subprocess
1408 # has to rearrange them in the child
1409 p = subprocess.Popen([sys.executable, "-c",
1410 'import sys; got = sys.stdin.read();'
1411 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1412 stdin=stdin_no,
1413 stdout=stdout_no,
1414 stderr=stderr_no)
1415 p.wait()
1416
1417 for fd in temp_fds:
1418 os.lseek(fd, 0, 0)
1419
1420 out = os.read(stdout_no, 1024)
1421 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1422 finally:
1423 for std, saved in enumerate(saved_fds):
1424 os.dup2(saved, std)
1425 os.close(saved)
1426
1427 self.assertEqual(out, b"got STDIN")
1428 self.assertEqual(err, b"err")
1429
1430 finally:
1431 for fd in temp_fds:
1432 os.close(fd)
1433
1434 # When duping fds, if there arises a situation where one of the fds is
1435 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1436 # This tests all combinations of this.
1437 def test_swap_fds(self):
1438 self.check_swap_fds(0, 1, 2)
1439 self.check_swap_fds(0, 2, 1)
1440 self.check_swap_fds(1, 0, 2)
1441 self.check_swap_fds(1, 2, 0)
1442 self.check_swap_fds(2, 0, 1)
1443 self.check_swap_fds(2, 1, 0)
1444
Victor Stinner13bb71c2010-04-23 21:41:56 +00001445 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001446 def prepare():
1447 raise ValueError("surrogate:\uDCff")
1448
1449 try:
1450 subprocess.call(
1451 [sys.executable, "-c", "pass"],
1452 preexec_fn=prepare)
1453 except ValueError as err:
1454 # Pure Python implementations keeps the message
1455 self.assertIsNone(subprocess._posixsubprocess)
1456 self.assertEqual(str(err), "surrogate:\uDCff")
1457 except RuntimeError as err:
1458 # _posixsubprocess uses a default message
1459 self.assertIsNotNone(subprocess._posixsubprocess)
1460 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1461 else:
1462 self.fail("Expected ValueError or RuntimeError")
1463
Victor Stinner13bb71c2010-04-23 21:41:56 +00001464 def test_undecodable_env(self):
1465 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001466 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001467 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001468 env = os.environ.copy()
1469 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001470 # Use C locale to get ascii for the locale encoding to force
1471 # surrogate-escaping of \xFF in the child process; otherwise it can
1472 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001473 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001474 stdout = subprocess.check_output(
1475 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001476 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001477 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001478 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001479
1480 # test bytes
1481 key = key.encode("ascii", "surrogateescape")
1482 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001483 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001484 env = os.environ.copy()
1485 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001486 stdout = subprocess.check_output(
1487 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001488 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001489 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001490 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001491
Victor Stinnerb745a742010-05-18 17:17:23 +00001492 def test_bytes_program(self):
1493 abs_program = os.fsencode(sys.executable)
1494 path, program = os.path.split(sys.executable)
1495 program = os.fsencode(program)
1496
1497 # absolute bytes path
1498 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001499 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001500
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001501 # absolute bytes path as a string
1502 cmd = b"'" + abs_program + b"' -c pass"
1503 exitcode = subprocess.call(cmd, shell=True)
1504 self.assertEqual(exitcode, 0)
1505
Victor Stinnerb745a742010-05-18 17:17:23 +00001506 # bytes program, unicode PATH
1507 env = os.environ.copy()
1508 env["PATH"] = path
1509 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001510 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001511
1512 # bytes program, bytes PATH
1513 envb = os.environb.copy()
1514 envb[b"PATH"] = os.fsencode(path)
1515 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001516 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001517
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001518 def test_pipe_cloexec(self):
1519 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1520 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1521
1522 p1 = subprocess.Popen([sys.executable, sleeper],
1523 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1524 stderr=subprocess.PIPE, close_fds=False)
1525
1526 self.addCleanup(p1.communicate, b'')
1527
1528 p2 = subprocess.Popen([sys.executable, fd_status],
1529 stdout=subprocess.PIPE, close_fds=False)
1530
1531 output, error = p2.communicate()
1532 result_fds = set(map(int, output.split(b',')))
1533 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1534 p1.stderr.fileno()])
1535
1536 self.assertFalse(result_fds & unwanted_fds,
1537 "Expected no fds from %r to be open in child, "
1538 "found %r" %
1539 (unwanted_fds, result_fds & unwanted_fds))
1540
1541 def test_pipe_cloexec_real_tools(self):
1542 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1543 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1544
1545 subdata = b'zxcvbn'
1546 data = subdata * 4 + b'\n'
1547
1548 p1 = subprocess.Popen([sys.executable, qcat],
1549 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1550 close_fds=False)
1551
1552 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1553 stdin=p1.stdout, stdout=subprocess.PIPE,
1554 close_fds=False)
1555
1556 self.addCleanup(p1.wait)
1557 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001558 def kill_p1():
1559 try:
1560 p1.terminate()
1561 except ProcessLookupError:
1562 pass
1563 def kill_p2():
1564 try:
1565 p2.terminate()
1566 except ProcessLookupError:
1567 pass
1568 self.addCleanup(kill_p1)
1569 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001570
1571 p1.stdin.write(data)
1572 p1.stdin.close()
1573
1574 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1575
1576 self.assertTrue(readfiles, "The child hung")
1577 self.assertEqual(p2.stdout.read(), data)
1578
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001579 p1.stdout.close()
1580 p2.stdout.close()
1581
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001582 def test_close_fds(self):
1583 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1584
1585 fds = os.pipe()
1586 self.addCleanup(os.close, fds[0])
1587 self.addCleanup(os.close, fds[1])
1588
1589 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001590 # add a bunch more fds
1591 for _ in range(9):
1592 fd = os.open("/dev/null", os.O_RDONLY)
1593 self.addCleanup(os.close, fd)
1594 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001595
1596 p = subprocess.Popen([sys.executable, fd_status],
1597 stdout=subprocess.PIPE, close_fds=False)
1598 output, ignored = p.communicate()
1599 remaining_fds = set(map(int, output.split(b',')))
1600
1601 self.assertEqual(remaining_fds & open_fds, open_fds,
1602 "Some fds were closed")
1603
1604 p = subprocess.Popen([sys.executable, fd_status],
1605 stdout=subprocess.PIPE, close_fds=True)
1606 output, ignored = p.communicate()
1607 remaining_fds = set(map(int, output.split(b',')))
1608
1609 self.assertFalse(remaining_fds & open_fds,
1610 "Some fds were left open")
1611 self.assertIn(1, remaining_fds, "Subprocess failed")
1612
Gregory P. Smith8facece2012-01-21 14:01:08 -08001613 # Keep some of the fd's we opened open in the subprocess.
1614 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1615 fds_to_keep = set(open_fds.pop() for _ in range(8))
1616 p = subprocess.Popen([sys.executable, fd_status],
1617 stdout=subprocess.PIPE, close_fds=True,
1618 pass_fds=())
1619 output, ignored = p.communicate()
1620 remaining_fds = set(map(int, output.split(b',')))
1621
1622 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1623 "Some fds not in pass_fds were left open")
1624 self.assertIn(1, remaining_fds, "Subprocess failed")
1625
Victor Stinner88701e22011-06-01 13:13:04 +02001626 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1627 # descriptor of a pipe closed in the parent process is valid in the
1628 # child process according to fstat(), but the mode of the file
1629 # descriptor is invalid, and read or write raise an error.
1630 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001631 def test_pass_fds(self):
1632 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1633
1634 open_fds = set()
1635
1636 for x in range(5):
1637 fds = os.pipe()
1638 self.addCleanup(os.close, fds[0])
1639 self.addCleanup(os.close, fds[1])
1640 open_fds.update(fds)
1641
1642 for fd in open_fds:
1643 p = subprocess.Popen([sys.executable, fd_status],
1644 stdout=subprocess.PIPE, close_fds=True,
1645 pass_fds=(fd, ))
1646 output, ignored = p.communicate()
1647
1648 remaining_fds = set(map(int, output.split(b',')))
1649 to_be_closed = open_fds - {fd}
1650
1651 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1652 self.assertFalse(remaining_fds & to_be_closed,
1653 "fd to be closed passed")
1654
1655 # pass_fds overrides close_fds with a warning.
1656 with self.assertWarns(RuntimeWarning) as context:
1657 self.assertFalse(subprocess.call(
1658 [sys.executable, "-c", "import sys; sys.exit(0)"],
1659 close_fds=False, pass_fds=(fd, )))
1660 self.assertIn('overriding close_fds', str(context.warning))
1661
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001662 def test_stdout_stdin_are_single_inout_fd(self):
1663 with io.open(os.devnull, "r+") as inout:
1664 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1665 stdout=inout, stdin=inout)
1666 p.wait()
1667
1668 def test_stdout_stderr_are_single_inout_fd(self):
1669 with io.open(os.devnull, "r+") as inout:
1670 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1671 stdout=inout, stderr=inout)
1672 p.wait()
1673
1674 def test_stderr_stdin_are_single_inout_fd(self):
1675 with io.open(os.devnull, "r+") as inout:
1676 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1677 stderr=inout, stdin=inout)
1678 p.wait()
1679
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001680 def test_wait_when_sigchild_ignored(self):
1681 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1682 sigchild_ignore = support.findfile("sigchild_ignore.py",
1683 subdir="subprocessdata")
1684 p = subprocess.Popen([sys.executable, sigchild_ignore],
1685 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1686 stdout, stderr = p.communicate()
1687 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001688 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001689 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001690
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001691 def test_select_unbuffered(self):
1692 # Issue #11459: bufsize=0 should really set the pipes as
1693 # unbuffered (and therefore let select() work properly).
1694 select = support.import_module("select")
1695 p = subprocess.Popen([sys.executable, "-c",
1696 'import sys;'
1697 'sys.stdout.write("apple")'],
1698 stdout=subprocess.PIPE,
1699 bufsize=0)
1700 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001701 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001702 try:
1703 self.assertEqual(f.read(4), b"appl")
1704 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1705 finally:
1706 p.wait()
1707
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001708 def test_zombie_fast_process_del(self):
1709 # Issue #12650: on Unix, if Popen.__del__() was called before the
1710 # process exited, it wouldn't be added to subprocess._active, and would
1711 # remain a zombie.
1712 # spawn a Popen, and delete its reference before it exits
1713 p = subprocess.Popen([sys.executable, "-c",
1714 'import sys, time;'
1715 'time.sleep(0.2)'],
1716 stdout=subprocess.PIPE,
1717 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001718 self.addCleanup(p.stdout.close)
1719 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001720 ident = id(p)
1721 pid = p.pid
1722 del p
1723 # check that p is in the active processes list
1724 self.assertIn(ident, [id(o) for o in subprocess._active])
1725
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001726 def test_leak_fast_process_del_killed(self):
1727 # Issue #12650: on Unix, if Popen.__del__() was called before the
1728 # process exited, and the process got killed by a signal, it would never
1729 # be removed from subprocess._active, which triggered a FD and memory
1730 # leak.
1731 # spawn a Popen, delete its reference and kill it
1732 p = subprocess.Popen([sys.executable, "-c",
1733 'import time;'
1734 'time.sleep(3)'],
1735 stdout=subprocess.PIPE,
1736 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001737 self.addCleanup(p.stdout.close)
1738 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001739 ident = id(p)
1740 pid = p.pid
1741 del p
1742 os.kill(pid, signal.SIGKILL)
1743 # check that p is in the active processes list
1744 self.assertIn(ident, [id(o) for o in subprocess._active])
1745
1746 # let some time for the process to exit, and create a new Popen: this
1747 # should trigger the wait() of p
1748 time.sleep(0.2)
1749 with self.assertRaises(EnvironmentError) as c:
1750 with subprocess.Popen(['nonexisting_i_hope'],
1751 stdout=subprocess.PIPE,
1752 stderr=subprocess.PIPE) as proc:
1753 pass
1754 # p should have been wait()ed on, and removed from the _active list
1755 self.assertRaises(OSError, os.waitpid, pid, 0)
1756 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1757
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001758
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001759@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001760class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001761
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001762 def test_startupinfo(self):
1763 # startupinfo argument
1764 # We uses hardcoded constants, because we do not want to
1765 # depend on win32all.
1766 STARTF_USESHOWWINDOW = 1
1767 SW_MAXIMIZE = 3
1768 startupinfo = subprocess.STARTUPINFO()
1769 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1770 startupinfo.wShowWindow = SW_MAXIMIZE
1771 # Since Python is a console process, it won't be affected
1772 # by wShowWindow, but the argument should be silently
1773 # ignored
1774 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001775 startupinfo=startupinfo)
1776
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001777 def test_creationflags(self):
1778 # creationflags argument
1779 CREATE_NEW_CONSOLE = 16
1780 sys.stderr.write(" a DOS box should flash briefly ...\n")
1781 subprocess.call(sys.executable +
1782 ' -c "import time; time.sleep(0.25)"',
1783 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001784
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001785 def test_invalid_args(self):
1786 # invalid arguments should raise ValueError
1787 self.assertRaises(ValueError, subprocess.call,
1788 [sys.executable, "-c",
1789 "import sys; sys.exit(47)"],
1790 preexec_fn=lambda: 1)
1791 self.assertRaises(ValueError, subprocess.call,
1792 [sys.executable, "-c",
1793 "import sys; sys.exit(47)"],
1794 stdout=subprocess.PIPE,
1795 close_fds=True)
1796
1797 def test_close_fds(self):
1798 # close file descriptors
1799 rc = subprocess.call([sys.executable, "-c",
1800 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001801 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001802 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001803
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001804 def test_shell_sequence(self):
1805 # Run command through the shell (sequence)
1806 newenv = os.environ.copy()
1807 newenv["FRUIT"] = "physalis"
1808 p = subprocess.Popen(["set"], shell=1,
1809 stdout=subprocess.PIPE,
1810 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001811 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001812 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001813
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001814 def test_shell_string(self):
1815 # Run command through the shell (string)
1816 newenv = os.environ.copy()
1817 newenv["FRUIT"] = "physalis"
1818 p = subprocess.Popen("set", shell=1,
1819 stdout=subprocess.PIPE,
1820 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001821 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001822 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001823
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001824 def test_call_string(self):
1825 # call() function with string argument on Windows
1826 rc = subprocess.call(sys.executable +
1827 ' -c "import sys; sys.exit(47)"')
1828 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001829
Florent Xicluna4886d242010-03-08 13:27:26 +00001830 def _kill_process(self, method, *args):
1831 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001832 p = subprocess.Popen([sys.executable, "-c", """if 1:
1833 import sys, time
1834 sys.stdout.write('x\\n')
1835 sys.stdout.flush()
1836 time.sleep(30)
1837 """],
1838 stdin=subprocess.PIPE,
1839 stdout=subprocess.PIPE,
1840 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001841 self.addCleanup(p.stdout.close)
1842 self.addCleanup(p.stderr.close)
1843 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001844 # Wait for the interpreter to be completely initialized before
1845 # sending any signal.
1846 p.stdout.read(1)
1847 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001848 _, stderr = p.communicate()
1849 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001850 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001851 self.assertNotEqual(returncode, 0)
1852
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001853 def _kill_dead_process(self, method, *args):
1854 p = subprocess.Popen([sys.executable, "-c", """if 1:
1855 import sys, time
1856 sys.stdout.write('x\\n')
1857 sys.stdout.flush()
1858 sys.exit(42)
1859 """],
1860 stdin=subprocess.PIPE,
1861 stdout=subprocess.PIPE,
1862 stderr=subprocess.PIPE)
1863 self.addCleanup(p.stdout.close)
1864 self.addCleanup(p.stderr.close)
1865 self.addCleanup(p.stdin.close)
1866 # Wait for the interpreter to be completely initialized before
1867 # sending any signal.
1868 p.stdout.read(1)
1869 # The process should end after this
1870 time.sleep(1)
1871 # This shouldn't raise even though the child is now dead
1872 getattr(p, method)(*args)
1873 _, stderr = p.communicate()
1874 self.assertStderrEqual(stderr, b'')
1875 rc = p.wait()
1876 self.assertEqual(rc, 42)
1877
Florent Xicluna4886d242010-03-08 13:27:26 +00001878 def test_send_signal(self):
1879 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001880
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001881 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001882 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001883
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001884 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001885 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001886
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001887 def test_send_signal_dead(self):
1888 self._kill_dead_process('send_signal', signal.SIGTERM)
1889
1890 def test_kill_dead(self):
1891 self._kill_dead_process('kill')
1892
1893 def test_terminate_dead(self):
1894 self._kill_dead_process('terminate')
1895
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001896
Brett Cannona23810f2008-05-26 19:04:21 +00001897# The module says:
1898# "NB This only works (and is only relevant) for UNIX."
1899#
1900# Actually, getoutput should work on any platform with an os.popen, but
1901# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001902@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001903class CommandTests(unittest.TestCase):
1904 def test_getoutput(self):
1905 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1906 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1907 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001908
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001909 # we use mkdtemp in the next line to create an empty directory
1910 # under our exclusive control; from that, we can invent a pathname
1911 # that we _know_ won't exist. This is guaranteed to fail.
1912 dir = None
1913 try:
1914 dir = tempfile.mkdtemp()
1915 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001916
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001917 status, output = subprocess.getstatusoutput('cat ' + name)
1918 self.assertNotEqual(status, 0)
1919 finally:
1920 if dir is not None:
1921 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001922
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001923
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001924@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1925 "poll system call not supported")
1926class ProcessTestCaseNoPoll(ProcessTestCase):
1927 def setUp(self):
1928 subprocess._has_poll = False
1929 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001930
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001931 def tearDown(self):
1932 subprocess._has_poll = True
1933 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001934
1935
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001936class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001937 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001938 def test_eintr_retry_call(self):
1939 record_calls = []
1940 def fake_os_func(*args):
1941 record_calls.append(args)
1942 if len(record_calls) == 2:
1943 raise OSError(errno.EINTR, "fake interrupted system call")
1944 return tuple(reversed(args))
1945
1946 self.assertEqual((999, 256),
1947 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1948 self.assertEqual([(256, 999)], record_calls)
1949 # This time there will be an EINTR so it will loop once.
1950 self.assertEqual((666,),
1951 subprocess._eintr_retry_call(fake_os_func, 666))
1952 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1953
1954
Tim Golden126c2962010-08-11 14:20:40 +00001955@unittest.skipUnless(mswindows, "Windows-specific tests")
1956class CommandsWithSpaces (BaseTestCase):
1957
1958 def setUp(self):
1959 super().setUp()
1960 f, fname = mkstemp(".py", "te st")
1961 self.fname = fname.lower ()
1962 os.write(f, b"import sys;"
1963 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1964 )
1965 os.close(f)
1966
1967 def tearDown(self):
1968 os.remove(self.fname)
1969 super().tearDown()
1970
1971 def with_spaces(self, *args, **kwargs):
1972 kwargs['stdout'] = subprocess.PIPE
1973 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001974 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001975 self.assertEqual(
1976 p.stdout.read ().decode("mbcs"),
1977 "2 [%r, 'ab cd']" % self.fname
1978 )
1979
1980 def test_shell_string_with_spaces(self):
1981 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001982 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1983 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001984
1985 def test_shell_sequence_with_spaces(self):
1986 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001987 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001988
1989 def test_noshell_string_with_spaces(self):
1990 # call() function with string argument with spaces on Windows
1991 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1992 "ab cd"))
1993
1994 def test_noshell_sequence_with_spaces(self):
1995 # call() function with sequence argument with spaces on Windows
1996 self.with_spaces([sys.executable, self.fname, "ab cd"])
1997
Brian Curtin79cdb662010-12-03 02:46:02 +00001998
Georg Brandla86b2622012-02-20 21:34:57 +01001999class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00002000
2001 def test_pipe(self):
2002 with subprocess.Popen([sys.executable, "-c",
2003 "import sys;"
2004 "sys.stdout.write('stdout');"
2005 "sys.stderr.write('stderr');"],
2006 stdout=subprocess.PIPE,
2007 stderr=subprocess.PIPE) as proc:
2008 self.assertEqual(proc.stdout.read(), b"stdout")
2009 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2010
2011 self.assertTrue(proc.stdout.closed)
2012 self.assertTrue(proc.stderr.closed)
2013
2014 def test_returncode(self):
2015 with subprocess.Popen([sys.executable, "-c",
2016 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002017 pass
2018 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002019 self.assertEqual(proc.returncode, 100)
2020
2021 def test_communicate_stdin(self):
2022 with subprocess.Popen([sys.executable, "-c",
2023 "import sys;"
2024 "sys.exit(sys.stdin.read() == 'context')"],
2025 stdin=subprocess.PIPE) as proc:
2026 proc.communicate(b"context")
2027 self.assertEqual(proc.returncode, 1)
2028
2029 def test_invalid_args(self):
2030 with self.assertRaises(EnvironmentError) as c:
2031 with subprocess.Popen(['nonexisting_i_hope'],
2032 stdout=subprocess.PIPE,
2033 stderr=subprocess.PIPE) as proc:
2034 pass
2035
2036 if c.exception.errno != errno.ENOENT: # ignore "no such file"
2037 raise c.exception
2038
2039
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002040def test_main():
2041 unit_tests = (ProcessTestCase,
2042 POSIXProcessTestCase,
2043 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002044 CommandTests,
2045 ProcessTestCaseNoPoll,
2046 HelperFunctionTests,
2047 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02002048 ContextManagerTests,
2049 )
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002050
2051 support.run_unittest(*unit_tests)
2052 support.reap_children()
2053
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002054if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002055 unittest.main()