blob: 476d22981a23c645ec5c9f4d46772ea33d86dc58 [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
302 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000303 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000304 p = subprocess.Popen([sys.executable, "-c",
305 'import sys; sys.exit(sys.stdin.read() == "pear")'],
306 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000307 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000308 p.stdin.close()
309 p.wait()
310 self.assertEqual(p.returncode, 1)
311
312 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000313 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000314 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000315 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000316 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000317 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000318 os.lseek(d, 0, 0)
319 p = subprocess.Popen([sys.executable, "-c",
320 'import sys; sys.exit(sys.stdin.read() == "pear")'],
321 stdin=d)
322 p.wait()
323 self.assertEqual(p.returncode, 1)
324
325 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000326 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000327 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000328 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000329 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000330 tf.seek(0)
331 p = subprocess.Popen([sys.executable, "-c",
332 'import sys; sys.exit(sys.stdin.read() == "pear")'],
333 stdin=tf)
334 p.wait()
335 self.assertEqual(p.returncode, 1)
336
337 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000338 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000339 p = subprocess.Popen([sys.executable, "-c",
340 'import sys; sys.stdout.write("orange")'],
341 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000342 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000343 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000344
345 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000346 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000347 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000348 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000349 d = tf.fileno()
350 p = subprocess.Popen([sys.executable, "-c",
351 'import sys; sys.stdout.write("orange")'],
352 stdout=d)
353 p.wait()
354 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000355 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000356
357 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000358 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000359 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000360 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000361 p = subprocess.Popen([sys.executable, "-c",
362 'import sys; sys.stdout.write("orange")'],
363 stdout=tf)
364 p.wait()
365 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000366 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000367
368 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000369 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000370 p = subprocess.Popen([sys.executable, "-c",
371 'import sys; sys.stderr.write("strawberry")'],
372 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000373 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000374 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000375
376 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000377 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000378 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000379 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000380 d = tf.fileno()
381 p = subprocess.Popen([sys.executable, "-c",
382 'import sys; sys.stderr.write("strawberry")'],
383 stderr=d)
384 p.wait()
385 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000386 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000387
388 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000389 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000390 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000391 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000392 p = subprocess.Popen([sys.executable, "-c",
393 'import sys; sys.stderr.write("strawberry")'],
394 stderr=tf)
395 p.wait()
396 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000397 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000398
399 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000400 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000401 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000402 'import sys;'
403 'sys.stdout.write("apple");'
404 'sys.stdout.flush();'
405 'sys.stderr.write("orange")'],
406 stdout=subprocess.PIPE,
407 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000408 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000409 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000410
411 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000412 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000413 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000414 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000415 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000416 'import sys;'
417 'sys.stdout.write("apple");'
418 'sys.stdout.flush();'
419 'sys.stderr.write("orange")'],
420 stdout=tf,
421 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000422 p.wait()
423 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000424 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000425
Thomas Wouters89f507f2006-12-13 04:49:30 +0000426 def test_stdout_filedes_of_stdout(self):
427 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000428 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000429 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000430 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000431
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200432 def test_stdout_devnull(self):
433 p = subprocess.Popen([sys.executable, "-c",
434 'for i in range(10240):'
435 'print("x" * 1024)'],
436 stdout=subprocess.DEVNULL)
437 p.wait()
438 self.assertEqual(p.stdout, None)
439
440 def test_stderr_devnull(self):
441 p = subprocess.Popen([sys.executable, "-c",
442 'import sys\n'
443 'for i in range(10240):'
444 'sys.stderr.write("x" * 1024)'],
445 stderr=subprocess.DEVNULL)
446 p.wait()
447 self.assertEqual(p.stderr, None)
448
449 def test_stdin_devnull(self):
450 p = subprocess.Popen([sys.executable, "-c",
451 'import sys;'
452 'sys.stdin.read(1)'],
453 stdin=subprocess.DEVNULL)
454 p.wait()
455 self.assertEqual(p.stdin, None)
456
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000457 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000458 newenv = os.environ.copy()
459 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200460 with subprocess.Popen([sys.executable, "-c",
461 'import sys,os;'
462 'sys.stdout.write(os.getenv("FRUIT"))'],
463 stdout=subprocess.PIPE,
464 env=newenv) as p:
465 stdout, stderr = p.communicate()
466 self.assertEqual(stdout, b"orange")
467
Victor Stinner62d51182011-06-23 01:02:25 +0200468 # Windows requires at least the SYSTEMROOT environment variable to start
469 # Python
470 @unittest.skipIf(sys.platform == 'win32',
471 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200472 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200473 'the python library cannot be loaded '
474 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200475 def test_empty_env(self):
476 with subprocess.Popen([sys.executable, "-c",
477 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200478 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200479 stdout=subprocess.PIPE,
480 env={}) as p:
481 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200482 self.assertIn(stdout.strip(),
483 (b"[]",
484 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
485 # environment
486 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000487
Peter Astrandcbac93c2005-03-03 20:24:28 +0000488 def test_communicate_stdin(self):
489 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000490 'import sys;'
491 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000492 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000493 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000494 self.assertEqual(p.returncode, 1)
495
496 def test_communicate_stdout(self):
497 p = subprocess.Popen([sys.executable, "-c",
498 'import sys; sys.stdout.write("pineapple")'],
499 stdout=subprocess.PIPE)
500 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000501 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000502 self.assertEqual(stderr, None)
503
504 def test_communicate_stderr(self):
505 p = subprocess.Popen([sys.executable, "-c",
506 'import sys; sys.stderr.write("pineapple")'],
507 stderr=subprocess.PIPE)
508 (stdout, stderr) = p.communicate()
509 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000510 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000511
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000512 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000513 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000514 'import sys,os;'
515 'sys.stderr.write("pineapple");'
516 'sys.stdout.write(sys.stdin.read())'],
517 stdin=subprocess.PIPE,
518 stdout=subprocess.PIPE,
519 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000520 self.addCleanup(p.stdout.close)
521 self.addCleanup(p.stderr.close)
522 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000523 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000524 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000525 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000526
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400527 def test_communicate_timeout(self):
528 p = subprocess.Popen([sys.executable, "-c",
529 'import sys,os,time;'
530 'sys.stderr.write("pineapple\\n");'
531 'time.sleep(1);'
532 'sys.stderr.write("pear\\n");'
533 'sys.stdout.write(sys.stdin.read())'],
534 universal_newlines=True,
535 stdin=subprocess.PIPE,
536 stdout=subprocess.PIPE,
537 stderr=subprocess.PIPE)
538 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
539 timeout=0.3)
540 # Make sure we can keep waiting for it, and that we get the whole output
541 # after it completes.
542 (stdout, stderr) = p.communicate()
543 self.assertEqual(stdout, "banana")
544 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
545
546 def test_communicate_timeout_large_ouput(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200547 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400548 p = subprocess.Popen([sys.executable, "-c",
549 'import sys,os,time;'
550 'sys.stdout.write("a" * (64 * 1024));'
551 'time.sleep(0.2);'
552 'sys.stdout.write("a" * (64 * 1024));'
553 'time.sleep(0.2);'
554 'sys.stdout.write("a" * (64 * 1024));'
555 'time.sleep(0.2);'
556 'sys.stdout.write("a" * (64 * 1024));'],
557 stdout=subprocess.PIPE)
558 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
559 (stdout, _) = p.communicate()
560 self.assertEqual(len(stdout), 4 * 64 * 1024)
561
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000562 # Test for the fd leak reported in http://bugs.python.org/issue2791.
563 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000564 for stdin_pipe in (False, True):
565 for stdout_pipe in (False, True):
566 for stderr_pipe in (False, True):
567 options = {}
568 if stdin_pipe:
569 options['stdin'] = subprocess.PIPE
570 if stdout_pipe:
571 options['stdout'] = subprocess.PIPE
572 if stderr_pipe:
573 options['stderr'] = subprocess.PIPE
574 if not options:
575 continue
576 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
577 p.communicate()
578 if p.stdin is not None:
579 self.assertTrue(p.stdin.closed)
580 if p.stdout is not None:
581 self.assertTrue(p.stdout.closed)
582 if p.stderr is not None:
583 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000584
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000585 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000586 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000587 p = subprocess.Popen([sys.executable, "-c",
588 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000589 (stdout, stderr) = p.communicate()
590 self.assertEqual(stdout, None)
591 self.assertEqual(stderr, None)
592
593 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000594 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000595 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000596 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000597 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000598 os.close(x)
599 os.close(y)
600 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000601 'import sys,os;'
602 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200603 'sys.stderr.write("x" * %d);'
604 'sys.stdout.write(sys.stdin.read())' %
605 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000606 stdin=subprocess.PIPE,
607 stdout=subprocess.PIPE,
608 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000609 self.addCleanup(p.stdout.close)
610 self.addCleanup(p.stderr.close)
611 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200612 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000613 (stdout, stderr) = p.communicate(string_to_write)
614 self.assertEqual(stdout, string_to_write)
615
616 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000617 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000618 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000619 'import sys,os;'
620 'sys.stdout.write(sys.stdin.read())'],
621 stdin=subprocess.PIPE,
622 stdout=subprocess.PIPE,
623 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000624 self.addCleanup(p.stdout.close)
625 self.addCleanup(p.stderr.close)
626 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000627 p.stdin.write(b"banana")
628 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000629 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000630 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000631
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000632 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000633 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000634 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200635 'buf = sys.stdout.buffer;'
636 'buf.write(sys.stdin.readline().encode());'
637 'buf.flush();'
638 'buf.write(b"line2\\n");'
639 'buf.flush();'
640 'buf.write(sys.stdin.read().encode());'
641 'buf.flush();'
642 'buf.write(b"line4\\n");'
643 'buf.flush();'
644 'buf.write(b"line5\\r\\n");'
645 'buf.flush();'
646 'buf.write(b"line6\\r");'
647 'buf.flush();'
648 'buf.write(b"\\nline7");'
649 'buf.flush();'
650 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200651 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000652 stdout=subprocess.PIPE,
653 universal_newlines=1)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200654 p.stdin.write("line1\n")
655 self.assertEqual(p.stdout.readline(), "line1\n")
656 p.stdin.write("line3\n")
657 p.stdin.close()
Brian Curtin3c6a9512010-11-05 03:58:52 +0000658 self.addCleanup(p.stdout.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200659 self.assertEqual(p.stdout.readline(),
660 "line2\n")
661 self.assertEqual(p.stdout.read(6),
662 "line3\n")
663 self.assertEqual(p.stdout.read(),
664 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000665
666 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000667 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000668 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000669 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200670 'buf = sys.stdout.buffer;'
671 'buf.write(b"line2\\n");'
672 'buf.flush();'
673 'buf.write(b"line4\\n");'
674 'buf.flush();'
675 'buf.write(b"line5\\r\\n");'
676 'buf.flush();'
677 'buf.write(b"line6\\r");'
678 'buf.flush();'
679 'buf.write(b"\\nline7");'
680 'buf.flush();'
681 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200682 stderr=subprocess.PIPE,
683 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000684 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000685 self.addCleanup(p.stdout.close)
686 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000687 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200688 self.assertEqual(stdout,
689 "line2\nline4\nline5\nline6\nline7\nline8")
690
691 def test_universal_newlines_communicate_stdin(self):
692 # universal newlines through communicate(), with only stdin
693 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300694 'import sys,os;' + SETBINARY + textwrap.dedent('''
695 s = sys.stdin.readline()
696 assert s == "line1\\n", repr(s)
697 s = sys.stdin.read()
698 assert s == "line3\\n", repr(s)
699 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200700 stdin=subprocess.PIPE,
701 universal_newlines=1)
702 (stdout, stderr) = p.communicate("line1\nline3\n")
703 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000704
Andrew Svetlovf3765072012-08-14 18:35:17 +0300705 def test_universal_newlines_communicate_input_none(self):
706 # Test communicate(input=None) with universal newlines.
707 #
708 # We set stdout to PIPE because, as of this writing, a different
709 # code path is tested when the number of pipes is zero or one.
710 p = subprocess.Popen([sys.executable, "-c", "pass"],
711 stdin=subprocess.PIPE,
712 stdout=subprocess.PIPE,
713 universal_newlines=True)
714 p.communicate()
715 self.assertEqual(p.returncode, 0)
716
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300717 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300718 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300719 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300720 'import sys,os;' + SETBINARY + textwrap.dedent('''
721 s = sys.stdin.buffer.readline()
722 sys.stdout.buffer.write(s)
723 sys.stdout.buffer.write(b"line2\\r")
724 sys.stderr.buffer.write(b"eline2\\n")
725 s = sys.stdin.buffer.read()
726 sys.stdout.buffer.write(s)
727 sys.stdout.buffer.write(b"line4\\n")
728 sys.stdout.buffer.write(b"line5\\r\\n")
729 sys.stderr.buffer.write(b"eline6\\r")
730 sys.stderr.buffer.write(b"eline7\\r\\nz")
731 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300732 stdin=subprocess.PIPE,
733 stderr=subprocess.PIPE,
734 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300735 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300736 self.addCleanup(p.stdout.close)
737 self.addCleanup(p.stderr.close)
738 (stdout, stderr) = p.communicate("line1\nline3\n")
739 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300740 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300741 # Python debug build push something like "[42442 refs]\n"
742 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300743 # Don't use assertStderrEqual because it strips CR and LF from output.
744 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300745
Andrew Svetlov82860712012-08-19 22:13:41 +0300746 def test_universal_newlines_communicate_encodings(self):
747 # Check that universal newlines mode works for various encodings,
748 # in particular for encodings in the UTF-16 and UTF-32 families.
749 # See issue #15595.
750 #
751 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
752 # without, and UTF-16 and UTF-32.
753 for encoding in ['utf-16', 'utf-32-be']:
754 old_getpreferredencoding = locale.getpreferredencoding
755 # Indirectly via io.TextIOWrapper, Popen() defaults to
756 # locale.getpreferredencoding(False) and earlier in Python 3.2 to
757 # locale.getpreferredencoding().
758 def getpreferredencoding(do_setlocale=True):
759 return encoding
760 code = ("import sys; "
761 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
762 encoding)
763 args = [sys.executable, '-c', code]
764 try:
765 locale.getpreferredencoding = getpreferredencoding
766 # We set stdin to be non-None because, as of this writing,
767 # a different code path is used when the number of pipes is
768 # zero or one.
769 popen = subprocess.Popen(args, universal_newlines=True,
770 stdin=subprocess.PIPE,
771 stdout=subprocess.PIPE)
772 stdout, stderr = popen.communicate(input='')
773 finally:
774 locale.getpreferredencoding = old_getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300775 self.assertEqual(stdout, '1\n2\n3\n4')
776
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000777 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000778 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000779 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000780 max_handles = 1026 # too much for most UNIX systems
781 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000782 max_handles = 2050 # too much for (at least some) Windows setups
783 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400784 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000785 try:
786 for i in range(max_handles):
787 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400788 tmpfile = os.path.join(tmpdir, support.TESTFN)
789 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000790 except OSError as e:
791 if e.errno != errno.EMFILE:
792 raise
793 break
794 else:
795 self.skipTest("failed to reach the file descriptor limit "
796 "(tried %d)" % max_handles)
797 # Close a couple of them (should be enough for a subprocess)
798 for i in range(10):
799 os.close(handles.pop())
800 # Loop creating some subprocesses. If one of them leaks some fds,
801 # the next loop iteration will fail by reaching the max fd limit.
802 for i in range(15):
803 p = subprocess.Popen([sys.executable, "-c",
804 "import sys;"
805 "sys.stdout.write(sys.stdin.read())"],
806 stdin=subprocess.PIPE,
807 stdout=subprocess.PIPE,
808 stderr=subprocess.PIPE)
809 data = p.communicate(b"lime")[0]
810 self.assertEqual(data, b"lime")
811 finally:
812 for h in handles:
813 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400814 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000815
816 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000817 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
818 '"a b c" d e')
819 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
820 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000821 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
822 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000823 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
824 'a\\\\\\b "de fg" h')
825 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
826 'a\\\\\\"b c d')
827 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
828 '"a\\\\b c" d e')
829 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
830 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000831 self.assertEqual(subprocess.list2cmdline(['ab', '']),
832 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000833
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000834 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200835 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +0200836 "import os; os.read(0, 1)"],
837 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200838 self.addCleanup(p.stdin.close)
839 self.assertIsNone(p.poll())
840 os.write(p.stdin.fileno(), b'A')
841 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000842 # Subsequent invocations should just return the returncode
843 self.assertEqual(p.poll(), 0)
844
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000845 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200846 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000847 self.assertEqual(p.wait(), 0)
848 # Subsequent invocations should just return the returncode
849 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000850
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400851 def test_wait_timeout(self):
852 p = subprocess.Popen([sys.executable,
Reid Kleckner93479cc2011-03-14 19:32:41 -0400853 "-c", "import time; time.sleep(0.1)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -0400854 with self.assertRaises(subprocess.TimeoutExpired) as c:
855 p.wait(timeout=0.01)
856 self.assertIn("0.01", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -0400857 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
858 # time to start.
859 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400860
Peter Astrand738131d2004-11-30 21:04:45 +0000861 def test_invalid_bufsize(self):
862 # an invalid type of the bufsize argument should raise
863 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000864 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000865 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000866
Guido van Rossum46a05a72007-06-07 21:56:45 +0000867 def test_bufsize_is_none(self):
868 # bufsize=None should be the same as bufsize=0.
869 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
870 self.assertEqual(p.wait(), 0)
871 # Again with keyword arg
872 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
873 self.assertEqual(p.wait(), 0)
874
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000875 def test_leaking_fds_on_error(self):
876 # see bug #5179: Popen leaks file descriptors to PIPEs if
877 # the child fails to execute; this will eventually exhaust
878 # the maximum number of open fds. 1024 seems a very common
879 # value for that limit, but Windows has 2048, so we loop
880 # 1024 times (each call leaked two fds).
881 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000882 # Windows raises IOError. Others raise OSError.
883 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000884 subprocess.Popen(['nonexisting_i_hope'],
885 stdout=subprocess.PIPE,
886 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400887 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400888 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000889 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000890
Victor Stinnerb3693582010-05-21 20:13:12 +0000891 def test_issue8780(self):
892 # Ensure that stdout is inherited from the parent
893 # if stdout=PIPE is not used
894 code = ';'.join((
895 'import subprocess, sys',
896 'retcode = subprocess.call('
897 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
898 'assert retcode == 0'))
899 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000900 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000901
Tim Goldenaf5ac392010-08-06 13:03:56 +0000902 def test_handles_closed_on_exception(self):
903 # If CreateProcess exits with an error, ensure the
904 # duplicate output handles are released
905 ifhandle, ifname = mkstemp()
906 ofhandle, ofname = mkstemp()
907 efhandle, efname = mkstemp()
908 try:
909 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
910 stderr=efhandle)
911 except OSError:
912 os.close(ifhandle)
913 os.remove(ifname)
914 os.close(ofhandle)
915 os.remove(ofname)
916 os.close(efhandle)
917 os.remove(efname)
918 self.assertFalse(os.path.exists(ifname))
919 self.assertFalse(os.path.exists(ofname))
920 self.assertFalse(os.path.exists(efname))
921
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200922 def test_communicate_epipe(self):
923 # Issue 10963: communicate() should hide EPIPE
924 p = subprocess.Popen([sys.executable, "-c", 'pass'],
925 stdin=subprocess.PIPE,
926 stdout=subprocess.PIPE,
927 stderr=subprocess.PIPE)
928 self.addCleanup(p.stdout.close)
929 self.addCleanup(p.stderr.close)
930 self.addCleanup(p.stdin.close)
931 p.communicate(b"x" * 2**20)
932
933 def test_communicate_epipe_only_stdin(self):
934 # Issue 10963: communicate() should hide EPIPE
935 p = subprocess.Popen([sys.executable, "-c", 'pass'],
936 stdin=subprocess.PIPE)
937 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200938 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200939 p.communicate(b"x" * 2**20)
940
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200941 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
942 "Requires signal.SIGUSR1")
943 @unittest.skipUnless(hasattr(os, 'kill'),
944 "Requires os.kill")
945 @unittest.skipUnless(hasattr(os, 'getppid'),
946 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200947 def test_communicate_eintr(self):
948 # Issue #12493: communicate() should handle EINTR
949 def handler(signum, frame):
950 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200951 old_handler = signal.signal(signal.SIGUSR1, handler)
952 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200953
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200954 args = [sys.executable, "-c",
955 'import os, signal;'
956 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200957 for stream in ('stdout', 'stderr'):
958 kw = {stream: subprocess.PIPE}
959 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200960 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200961 process.communicate()
962
Tim Peterse718f612004-10-12 21:51:32 +0000963
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000964# context manager
965class _SuppressCoreFiles(object):
966 """Try to prevent core files from being created."""
967 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000968
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000969 def __enter__(self):
970 """Try to save previous ulimit, then set it to (0, 0)."""
Benjamin Peterson964561b2011-12-10 12:31:42 -0500971 if resource is not None:
972 try:
973 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
974 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
975 except (ValueError, resource.error):
976 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000977
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000978 if sys.platform == 'darwin':
979 # Check if the 'Crash Reporter' on OSX was configured
980 # in 'Developer' mode and warn that it will get triggered
981 # when it is.
982 #
983 # This assumes that this context manager is used in tests
984 # that might trigger the next manager.
985 value = subprocess.Popen(['/usr/bin/defaults', 'read',
986 'com.apple.CrashReporter', 'DialogType'],
987 stdout=subprocess.PIPE).communicate()[0]
988 if value.strip() == b'developer':
989 print("this tests triggers the Crash Reporter, "
990 "that is intentional", end='')
991 sys.stdout.flush()
992
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000993 def __exit__(self, *args):
994 """Return core file behavior to default."""
995 if self.old_limit is None:
996 return
Benjamin Peterson964561b2011-12-10 12:31:42 -0500997 if resource is not None:
998 try:
999 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
1000 except (ValueError, resource.error):
1001 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001002
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001003
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001004@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001005class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001006
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001007 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001008 nonexistent_dir = "/_this/pa.th/does/not/exist"
1009 try:
1010 os.chdir(nonexistent_dir)
1011 except OSError as e:
1012 # This avoids hard coding the errno value or the OS perror()
1013 # string and instead capture the exception that we want to see
1014 # below for comparison.
1015 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +00001016 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001017 else:
1018 self.fail("chdir to nonexistant directory %s succeeded." %
1019 nonexistent_dir)
1020
1021 # Error in the child re-raised in the parent.
1022 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001023 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001024 cwd=nonexistent_dir)
1025 except OSError as e:
1026 # Test that the child process chdir failure actually makes
1027 # it up to the parent process as the correct exception.
1028 self.assertEqual(desired_exception.errno, e.errno)
1029 self.assertEqual(desired_exception.strerror, e.strerror)
1030 else:
1031 self.fail("Expected OSError: %s" % desired_exception)
1032
1033 def test_restore_signals(self):
1034 # Code coverage for both values of restore_signals to make sure it
1035 # at least does not blow up.
1036 # A test for behavior would be complex. Contributions welcome.
1037 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
1038 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
1039
1040 def test_start_new_session(self):
1041 # For code coverage of calling setsid(). We don't care if we get an
1042 # EPERM error from it depending on the test execution environment, that
1043 # still indicates that it was called.
1044 try:
1045 output = subprocess.check_output(
1046 [sys.executable, "-c",
1047 "import os; print(os.getpgid(os.getpid()))"],
1048 start_new_session=True)
1049 except OSError as e:
1050 if e.errno != errno.EPERM:
1051 raise
1052 else:
1053 parent_pgid = os.getpgid(os.getpid())
1054 child_pgid = int(output)
1055 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001056
1057 def test_run_abort(self):
1058 # returncode handles signal termination
1059 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001060 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001061 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001062 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001063 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001064
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001065 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001066 # DISCLAIMER: Setting environment variables is *not* a good use
1067 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001068 p = subprocess.Popen([sys.executable, "-c",
1069 'import sys,os;'
1070 'sys.stdout.write(os.getenv("FRUIT"))'],
1071 stdout=subprocess.PIPE,
1072 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +00001073 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001074 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001075
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001076 def test_preexec_exception(self):
1077 def raise_it():
1078 raise ValueError("What if two swallows carried a coconut?")
1079 try:
1080 p = subprocess.Popen([sys.executable, "-c", ""],
1081 preexec_fn=raise_it)
1082 except RuntimeError as e:
1083 self.assertTrue(
1084 subprocess._posixsubprocess,
1085 "Expected a ValueError from the preexec_fn")
1086 except ValueError as e:
1087 self.assertIn("coconut", e.args[0])
1088 else:
1089 self.fail("Exception raised by preexec_fn did not make it "
1090 "to the parent process.")
1091
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001092 def test_preexec_gc_module_failure(self):
1093 # This tests the code that disables garbage collection if the child
1094 # process will execute any Python.
1095 def raise_runtime_error():
1096 raise RuntimeError("this shouldn't escape")
1097 enabled = gc.isenabled()
1098 orig_gc_disable = gc.disable
1099 orig_gc_isenabled = gc.isenabled
1100 try:
1101 gc.disable()
1102 self.assertFalse(gc.isenabled())
1103 subprocess.call([sys.executable, '-c', ''],
1104 preexec_fn=lambda: None)
1105 self.assertFalse(gc.isenabled(),
1106 "Popen enabled gc when it shouldn't.")
1107
1108 gc.enable()
1109 self.assertTrue(gc.isenabled())
1110 subprocess.call([sys.executable, '-c', ''],
1111 preexec_fn=lambda: None)
1112 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1113
1114 gc.disable = raise_runtime_error
1115 self.assertRaises(RuntimeError, subprocess.Popen,
1116 [sys.executable, '-c', ''],
1117 preexec_fn=lambda: None)
1118
1119 del gc.isenabled # force an AttributeError
1120 self.assertRaises(AttributeError, subprocess.Popen,
1121 [sys.executable, '-c', ''],
1122 preexec_fn=lambda: None)
1123 finally:
1124 gc.disable = orig_gc_disable
1125 gc.isenabled = orig_gc_isenabled
1126 if not enabled:
1127 gc.disable()
1128
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001129 def test_args_string(self):
1130 # args is a string
1131 fd, fname = mkstemp()
1132 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001133 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001134 fobj.write("#!/bin/sh\n")
1135 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1136 sys.executable)
1137 os.chmod(fname, 0o700)
1138 p = subprocess.Popen(fname)
1139 p.wait()
1140 os.remove(fname)
1141 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001142
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001143 def test_invalid_args(self):
1144 # invalid arguments should raise ValueError
1145 self.assertRaises(ValueError, subprocess.call,
1146 [sys.executable, "-c",
1147 "import sys; sys.exit(47)"],
1148 startupinfo=47)
1149 self.assertRaises(ValueError, subprocess.call,
1150 [sys.executable, "-c",
1151 "import sys; sys.exit(47)"],
1152 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001153
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001154 def test_shell_sequence(self):
1155 # Run command through the shell (sequence)
1156 newenv = os.environ.copy()
1157 newenv["FRUIT"] = "apple"
1158 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1159 stdout=subprocess.PIPE,
1160 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001161 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001162 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001163
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001164 def test_shell_string(self):
1165 # Run command through the shell (string)
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")
Christian Heimesa342c012008-04-20 21:01:16 +00001173
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001174 def test_call_string(self):
1175 # call() function with string argument on UNIX
1176 fd, fname = mkstemp()
1177 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001178 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001179 fobj.write("#!/bin/sh\n")
1180 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1181 sys.executable)
1182 os.chmod(fname, 0o700)
1183 rc = subprocess.call(fname)
1184 os.remove(fname)
1185 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001186
Stefan Krah9542cc62010-07-19 14:20:53 +00001187 def test_specific_shell(self):
1188 # Issue #9265: Incorrect name passed as arg[0].
1189 shells = []
1190 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1191 for name in ['bash', 'ksh']:
1192 sh = os.path.join(prefix, name)
1193 if os.path.isfile(sh):
1194 shells.append(sh)
1195 if not shells: # Will probably work for any shell but csh.
1196 self.skipTest("bash or ksh required for this test")
1197 sh = '/bin/sh'
1198 if os.path.isfile(sh) and not os.path.islink(sh):
1199 # Test will fail if /bin/sh is a symlink to csh.
1200 shells.append(sh)
1201 for sh in shells:
1202 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1203 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001204 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001205 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1206
Florent Xicluna4886d242010-03-08 13:27:26 +00001207 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001208 # Do not inherit file handles from the parent.
1209 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001210 p = subprocess.Popen([sys.executable, "-c", """if 1:
1211 import sys, time
1212 sys.stdout.write('x\\n')
1213 sys.stdout.flush()
1214 time.sleep(30)
1215 """],
1216 close_fds=True,
1217 stdin=subprocess.PIPE,
1218 stdout=subprocess.PIPE,
1219 stderr=subprocess.PIPE)
1220 # Wait for the interpreter to be completely initialized before
1221 # sending any signal.
1222 p.stdout.read(1)
1223 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001224 return p
1225
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001226 def _kill_dead_process(self, method, *args):
1227 # Do not inherit file handles from the parent.
1228 # It should fix failures on some platforms.
1229 p = subprocess.Popen([sys.executable, "-c", """if 1:
1230 import sys, time
1231 sys.stdout.write('x\\n')
1232 sys.stdout.flush()
1233 """],
1234 close_fds=True,
1235 stdin=subprocess.PIPE,
1236 stdout=subprocess.PIPE,
1237 stderr=subprocess.PIPE)
1238 # Wait for the interpreter to be completely initialized before
1239 # sending any signal.
1240 p.stdout.read(1)
1241 # The process should end after this
1242 time.sleep(1)
1243 # This shouldn't raise even though the child is now dead
1244 getattr(p, method)(*args)
1245 p.communicate()
1246
Florent Xicluna4886d242010-03-08 13:27:26 +00001247 def test_send_signal(self):
1248 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001249 _, stderr = p.communicate()
1250 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001251 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001252
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001253 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001254 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001255 _, stderr = p.communicate()
1256 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001257 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001258
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001259 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001260 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001261 _, stderr = p.communicate()
1262 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001263 self.assertEqual(p.wait(), -signal.SIGTERM)
1264
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001265 def test_send_signal_dead(self):
1266 # Sending a signal to a dead process
1267 self._kill_dead_process('send_signal', signal.SIGINT)
1268
1269 def test_kill_dead(self):
1270 # Killing a dead process
1271 self._kill_dead_process('kill')
1272
1273 def test_terminate_dead(self):
1274 # Terminating a dead process
1275 self._kill_dead_process('terminate')
1276
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001277 def check_close_std_fds(self, fds):
1278 # Issue #9905: test that subprocess pipes still work properly with
1279 # some standard fds closed
1280 stdin = 0
1281 newfds = []
1282 for a in fds:
1283 b = os.dup(a)
1284 newfds.append(b)
1285 if a == 0:
1286 stdin = b
1287 try:
1288 for fd in fds:
1289 os.close(fd)
1290 out, err = subprocess.Popen([sys.executable, "-c",
1291 'import sys;'
1292 'sys.stdout.write("apple");'
1293 'sys.stdout.flush();'
1294 'sys.stderr.write("orange")'],
1295 stdin=stdin,
1296 stdout=subprocess.PIPE,
1297 stderr=subprocess.PIPE).communicate()
1298 err = support.strip_python_stderr(err)
1299 self.assertEqual((out, err), (b'apple', b'orange'))
1300 finally:
1301 for b, a in zip(newfds, fds):
1302 os.dup2(b, a)
1303 for b in newfds:
1304 os.close(b)
1305
1306 def test_close_fd_0(self):
1307 self.check_close_std_fds([0])
1308
1309 def test_close_fd_1(self):
1310 self.check_close_std_fds([1])
1311
1312 def test_close_fd_2(self):
1313 self.check_close_std_fds([2])
1314
1315 def test_close_fds_0_1(self):
1316 self.check_close_std_fds([0, 1])
1317
1318 def test_close_fds_0_2(self):
1319 self.check_close_std_fds([0, 2])
1320
1321 def test_close_fds_1_2(self):
1322 self.check_close_std_fds([1, 2])
1323
1324 def test_close_fds_0_1_2(self):
1325 # Issue #10806: test that subprocess pipes still work properly with
1326 # all standard fds closed.
1327 self.check_close_std_fds([0, 1, 2])
1328
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001329 def test_remapping_std_fds(self):
1330 # open up some temporary files
1331 temps = [mkstemp() for i in range(3)]
1332 try:
1333 temp_fds = [fd for fd, fname in temps]
1334
1335 # unlink the files -- we won't need to reopen them
1336 for fd, fname in temps:
1337 os.unlink(fname)
1338
1339 # write some data to what will become stdin, and rewind
1340 os.write(temp_fds[1], b"STDIN")
1341 os.lseek(temp_fds[1], 0, 0)
1342
1343 # move the standard file descriptors out of the way
1344 saved_fds = [os.dup(fd) for fd in range(3)]
1345 try:
1346 # duplicate the file objects over the standard fd's
1347 for fd, temp_fd in enumerate(temp_fds):
1348 os.dup2(temp_fd, fd)
1349
1350 # now use those files in the "wrong" order, so that subprocess
1351 # has to rearrange them in the child
1352 p = subprocess.Popen([sys.executable, "-c",
1353 'import sys; got = sys.stdin.read();'
1354 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1355 stdin=temp_fds[1],
1356 stdout=temp_fds[2],
1357 stderr=temp_fds[0])
1358 p.wait()
1359 finally:
1360 # restore the original fd's underneath sys.stdin, etc.
1361 for std, saved in enumerate(saved_fds):
1362 os.dup2(saved, std)
1363 os.close(saved)
1364
1365 for fd in temp_fds:
1366 os.lseek(fd, 0, 0)
1367
1368 out = os.read(temp_fds[2], 1024)
1369 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1370 self.assertEqual(out, b"got STDIN")
1371 self.assertEqual(err, b"err")
1372
1373 finally:
1374 for fd in temp_fds:
1375 os.close(fd)
1376
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001377 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1378 # open up some temporary files
1379 temps = [mkstemp() for i in range(3)]
1380 temp_fds = [fd for fd, fname in temps]
1381 try:
1382 # unlink the files -- we won't need to reopen them
1383 for fd, fname in temps:
1384 os.unlink(fname)
1385
1386 # save a copy of the standard file descriptors
1387 saved_fds = [os.dup(fd) for fd in range(3)]
1388 try:
1389 # duplicate the temp files over the standard fd's 0, 1, 2
1390 for fd, temp_fd in enumerate(temp_fds):
1391 os.dup2(temp_fd, fd)
1392
1393 # write some data to what will become stdin, and rewind
1394 os.write(stdin_no, b"STDIN")
1395 os.lseek(stdin_no, 0, 0)
1396
1397 # now use those files in the given order, so that subprocess
1398 # has to rearrange them in the child
1399 p = subprocess.Popen([sys.executable, "-c",
1400 'import sys; got = sys.stdin.read();'
1401 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1402 stdin=stdin_no,
1403 stdout=stdout_no,
1404 stderr=stderr_no)
1405 p.wait()
1406
1407 for fd in temp_fds:
1408 os.lseek(fd, 0, 0)
1409
1410 out = os.read(stdout_no, 1024)
1411 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1412 finally:
1413 for std, saved in enumerate(saved_fds):
1414 os.dup2(saved, std)
1415 os.close(saved)
1416
1417 self.assertEqual(out, b"got STDIN")
1418 self.assertEqual(err, b"err")
1419
1420 finally:
1421 for fd in temp_fds:
1422 os.close(fd)
1423
1424 # When duping fds, if there arises a situation where one of the fds is
1425 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1426 # This tests all combinations of this.
1427 def test_swap_fds(self):
1428 self.check_swap_fds(0, 1, 2)
1429 self.check_swap_fds(0, 2, 1)
1430 self.check_swap_fds(1, 0, 2)
1431 self.check_swap_fds(1, 2, 0)
1432 self.check_swap_fds(2, 0, 1)
1433 self.check_swap_fds(2, 1, 0)
1434
Victor Stinner13bb71c2010-04-23 21:41:56 +00001435 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001436 def prepare():
1437 raise ValueError("surrogate:\uDCff")
1438
1439 try:
1440 subprocess.call(
1441 [sys.executable, "-c", "pass"],
1442 preexec_fn=prepare)
1443 except ValueError as err:
1444 # Pure Python implementations keeps the message
1445 self.assertIsNone(subprocess._posixsubprocess)
1446 self.assertEqual(str(err), "surrogate:\uDCff")
1447 except RuntimeError as err:
1448 # _posixsubprocess uses a default message
1449 self.assertIsNotNone(subprocess._posixsubprocess)
1450 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1451 else:
1452 self.fail("Expected ValueError or RuntimeError")
1453
Victor Stinner13bb71c2010-04-23 21:41:56 +00001454 def test_undecodable_env(self):
1455 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001456 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001457 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001458 env = os.environ.copy()
1459 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001460 # Use C locale to get ascii for the locale encoding to force
1461 # surrogate-escaping of \xFF in the child process; otherwise it can
1462 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001463 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001464 stdout = subprocess.check_output(
1465 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001466 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001467 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001468 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001469
1470 # test bytes
1471 key = key.encode("ascii", "surrogateescape")
1472 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001473 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001474 env = os.environ.copy()
1475 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001476 stdout = subprocess.check_output(
1477 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001478 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001479 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001480 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001481
Victor Stinnerb745a742010-05-18 17:17:23 +00001482 def test_bytes_program(self):
1483 abs_program = os.fsencode(sys.executable)
1484 path, program = os.path.split(sys.executable)
1485 program = os.fsencode(program)
1486
1487 # absolute bytes path
1488 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001489 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001490
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001491 # absolute bytes path as a string
1492 cmd = b"'" + abs_program + b"' -c pass"
1493 exitcode = subprocess.call(cmd, shell=True)
1494 self.assertEqual(exitcode, 0)
1495
Victor Stinnerb745a742010-05-18 17:17:23 +00001496 # bytes program, unicode PATH
1497 env = os.environ.copy()
1498 env["PATH"] = path
1499 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001500 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001501
1502 # bytes program, bytes PATH
1503 envb = os.environb.copy()
1504 envb[b"PATH"] = os.fsencode(path)
1505 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001506 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001507
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001508 def test_pipe_cloexec(self):
1509 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1510 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1511
1512 p1 = subprocess.Popen([sys.executable, sleeper],
1513 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1514 stderr=subprocess.PIPE, close_fds=False)
1515
1516 self.addCleanup(p1.communicate, b'')
1517
1518 p2 = subprocess.Popen([sys.executable, fd_status],
1519 stdout=subprocess.PIPE, close_fds=False)
1520
1521 output, error = p2.communicate()
1522 result_fds = set(map(int, output.split(b',')))
1523 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1524 p1.stderr.fileno()])
1525
1526 self.assertFalse(result_fds & unwanted_fds,
1527 "Expected no fds from %r to be open in child, "
1528 "found %r" %
1529 (unwanted_fds, result_fds & unwanted_fds))
1530
1531 def test_pipe_cloexec_real_tools(self):
1532 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1533 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1534
1535 subdata = b'zxcvbn'
1536 data = subdata * 4 + b'\n'
1537
1538 p1 = subprocess.Popen([sys.executable, qcat],
1539 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1540 close_fds=False)
1541
1542 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1543 stdin=p1.stdout, stdout=subprocess.PIPE,
1544 close_fds=False)
1545
1546 self.addCleanup(p1.wait)
1547 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001548 def kill_p1():
1549 try:
1550 p1.terminate()
1551 except ProcessLookupError:
1552 pass
1553 def kill_p2():
1554 try:
1555 p2.terminate()
1556 except ProcessLookupError:
1557 pass
1558 self.addCleanup(kill_p1)
1559 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001560
1561 p1.stdin.write(data)
1562 p1.stdin.close()
1563
1564 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1565
1566 self.assertTrue(readfiles, "The child hung")
1567 self.assertEqual(p2.stdout.read(), data)
1568
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001569 p1.stdout.close()
1570 p2.stdout.close()
1571
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001572 def test_close_fds(self):
1573 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1574
1575 fds = os.pipe()
1576 self.addCleanup(os.close, fds[0])
1577 self.addCleanup(os.close, fds[1])
1578
1579 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001580 # add a bunch more fds
1581 for _ in range(9):
1582 fd = os.open("/dev/null", os.O_RDONLY)
1583 self.addCleanup(os.close, fd)
1584 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001585
1586 p = subprocess.Popen([sys.executable, fd_status],
1587 stdout=subprocess.PIPE, close_fds=False)
1588 output, ignored = p.communicate()
1589 remaining_fds = set(map(int, output.split(b',')))
1590
1591 self.assertEqual(remaining_fds & open_fds, open_fds,
1592 "Some fds were closed")
1593
1594 p = subprocess.Popen([sys.executable, fd_status],
1595 stdout=subprocess.PIPE, close_fds=True)
1596 output, ignored = p.communicate()
1597 remaining_fds = set(map(int, output.split(b',')))
1598
1599 self.assertFalse(remaining_fds & open_fds,
1600 "Some fds were left open")
1601 self.assertIn(1, remaining_fds, "Subprocess failed")
1602
Gregory P. Smith8facece2012-01-21 14:01:08 -08001603 # Keep some of the fd's we opened open in the subprocess.
1604 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1605 fds_to_keep = set(open_fds.pop() for _ in range(8))
1606 p = subprocess.Popen([sys.executable, fd_status],
1607 stdout=subprocess.PIPE, close_fds=True,
1608 pass_fds=())
1609 output, ignored = p.communicate()
1610 remaining_fds = set(map(int, output.split(b',')))
1611
1612 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1613 "Some fds not in pass_fds were left open")
1614 self.assertIn(1, remaining_fds, "Subprocess failed")
1615
Victor Stinner88701e22011-06-01 13:13:04 +02001616 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1617 # descriptor of a pipe closed in the parent process is valid in the
1618 # child process according to fstat(), but the mode of the file
1619 # descriptor is invalid, and read or write raise an error.
1620 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001621 def test_pass_fds(self):
1622 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1623
1624 open_fds = set()
1625
1626 for x in range(5):
1627 fds = os.pipe()
1628 self.addCleanup(os.close, fds[0])
1629 self.addCleanup(os.close, fds[1])
1630 open_fds.update(fds)
1631
1632 for fd in open_fds:
1633 p = subprocess.Popen([sys.executable, fd_status],
1634 stdout=subprocess.PIPE, close_fds=True,
1635 pass_fds=(fd, ))
1636 output, ignored = p.communicate()
1637
1638 remaining_fds = set(map(int, output.split(b',')))
1639 to_be_closed = open_fds - {fd}
1640
1641 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1642 self.assertFalse(remaining_fds & to_be_closed,
1643 "fd to be closed passed")
1644
1645 # pass_fds overrides close_fds with a warning.
1646 with self.assertWarns(RuntimeWarning) as context:
1647 self.assertFalse(subprocess.call(
1648 [sys.executable, "-c", "import sys; sys.exit(0)"],
1649 close_fds=False, pass_fds=(fd, )))
1650 self.assertIn('overriding close_fds', str(context.warning))
1651
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001652 def test_stdout_stdin_are_single_inout_fd(self):
1653 with io.open(os.devnull, "r+") as inout:
1654 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1655 stdout=inout, stdin=inout)
1656 p.wait()
1657
1658 def test_stdout_stderr_are_single_inout_fd(self):
1659 with io.open(os.devnull, "r+") as inout:
1660 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1661 stdout=inout, stderr=inout)
1662 p.wait()
1663
1664 def test_stderr_stdin_are_single_inout_fd(self):
1665 with io.open(os.devnull, "r+") as inout:
1666 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1667 stderr=inout, stdin=inout)
1668 p.wait()
1669
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001670 def test_wait_when_sigchild_ignored(self):
1671 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1672 sigchild_ignore = support.findfile("sigchild_ignore.py",
1673 subdir="subprocessdata")
1674 p = subprocess.Popen([sys.executable, sigchild_ignore],
1675 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1676 stdout, stderr = p.communicate()
1677 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001678 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001679 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001680
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001681 def test_select_unbuffered(self):
1682 # Issue #11459: bufsize=0 should really set the pipes as
1683 # unbuffered (and therefore let select() work properly).
1684 select = support.import_module("select")
1685 p = subprocess.Popen([sys.executable, "-c",
1686 'import sys;'
1687 'sys.stdout.write("apple")'],
1688 stdout=subprocess.PIPE,
1689 bufsize=0)
1690 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001691 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001692 try:
1693 self.assertEqual(f.read(4), b"appl")
1694 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1695 finally:
1696 p.wait()
1697
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001698 def test_zombie_fast_process_del(self):
1699 # Issue #12650: on Unix, if Popen.__del__() was called before the
1700 # process exited, it wouldn't be added to subprocess._active, and would
1701 # remain a zombie.
1702 # spawn a Popen, and delete its reference before it exits
1703 p = subprocess.Popen([sys.executable, "-c",
1704 'import sys, time;'
1705 'time.sleep(0.2)'],
1706 stdout=subprocess.PIPE,
1707 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001708 self.addCleanup(p.stdout.close)
1709 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001710 ident = id(p)
1711 pid = p.pid
1712 del p
1713 # check that p is in the active processes list
1714 self.assertIn(ident, [id(o) for o in subprocess._active])
1715
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001716 def test_leak_fast_process_del_killed(self):
1717 # Issue #12650: on Unix, if Popen.__del__() was called before the
1718 # process exited, and the process got killed by a signal, it would never
1719 # be removed from subprocess._active, which triggered a FD and memory
1720 # leak.
1721 # spawn a Popen, delete its reference and kill it
1722 p = subprocess.Popen([sys.executable, "-c",
1723 'import time;'
1724 'time.sleep(3)'],
1725 stdout=subprocess.PIPE,
1726 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001727 self.addCleanup(p.stdout.close)
1728 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001729 ident = id(p)
1730 pid = p.pid
1731 del p
1732 os.kill(pid, signal.SIGKILL)
1733 # check that p is in the active processes list
1734 self.assertIn(ident, [id(o) for o in subprocess._active])
1735
1736 # let some time for the process to exit, and create a new Popen: this
1737 # should trigger the wait() of p
1738 time.sleep(0.2)
1739 with self.assertRaises(EnvironmentError) as c:
1740 with subprocess.Popen(['nonexisting_i_hope'],
1741 stdout=subprocess.PIPE,
1742 stderr=subprocess.PIPE) as proc:
1743 pass
1744 # p should have been wait()ed on, and removed from the _active list
1745 self.assertRaises(OSError, os.waitpid, pid, 0)
1746 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1747
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001748
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001749@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001750class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001751
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001752 def test_startupinfo(self):
1753 # startupinfo argument
1754 # We uses hardcoded constants, because we do not want to
1755 # depend on win32all.
1756 STARTF_USESHOWWINDOW = 1
1757 SW_MAXIMIZE = 3
1758 startupinfo = subprocess.STARTUPINFO()
1759 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1760 startupinfo.wShowWindow = SW_MAXIMIZE
1761 # Since Python is a console process, it won't be affected
1762 # by wShowWindow, but the argument should be silently
1763 # ignored
1764 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001765 startupinfo=startupinfo)
1766
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001767 def test_creationflags(self):
1768 # creationflags argument
1769 CREATE_NEW_CONSOLE = 16
1770 sys.stderr.write(" a DOS box should flash briefly ...\n")
1771 subprocess.call(sys.executable +
1772 ' -c "import time; time.sleep(0.25)"',
1773 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001774
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001775 def test_invalid_args(self):
1776 # invalid arguments should raise ValueError
1777 self.assertRaises(ValueError, subprocess.call,
1778 [sys.executable, "-c",
1779 "import sys; sys.exit(47)"],
1780 preexec_fn=lambda: 1)
1781 self.assertRaises(ValueError, subprocess.call,
1782 [sys.executable, "-c",
1783 "import sys; sys.exit(47)"],
1784 stdout=subprocess.PIPE,
1785 close_fds=True)
1786
1787 def test_close_fds(self):
1788 # close file descriptors
1789 rc = subprocess.call([sys.executable, "-c",
1790 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001791 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001792 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001793
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001794 def test_shell_sequence(self):
1795 # Run command through the shell (sequence)
1796 newenv = os.environ.copy()
1797 newenv["FRUIT"] = "physalis"
1798 p = subprocess.Popen(["set"], shell=1,
1799 stdout=subprocess.PIPE,
1800 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001801 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001802 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001803
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001804 def test_shell_string(self):
1805 # Run command through the shell (string)
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())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001813
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001814 def test_call_string(self):
1815 # call() function with string argument on Windows
1816 rc = subprocess.call(sys.executable +
1817 ' -c "import sys; sys.exit(47)"')
1818 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001819
Florent Xicluna4886d242010-03-08 13:27:26 +00001820 def _kill_process(self, method, *args):
1821 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001822 p = subprocess.Popen([sys.executable, "-c", """if 1:
1823 import sys, time
1824 sys.stdout.write('x\\n')
1825 sys.stdout.flush()
1826 time.sleep(30)
1827 """],
1828 stdin=subprocess.PIPE,
1829 stdout=subprocess.PIPE,
1830 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001831 self.addCleanup(p.stdout.close)
1832 self.addCleanup(p.stderr.close)
1833 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001834 # Wait for the interpreter to be completely initialized before
1835 # sending any signal.
1836 p.stdout.read(1)
1837 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001838 _, stderr = p.communicate()
1839 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001840 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001841 self.assertNotEqual(returncode, 0)
1842
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001843 def _kill_dead_process(self, method, *args):
1844 p = subprocess.Popen([sys.executable, "-c", """if 1:
1845 import sys, time
1846 sys.stdout.write('x\\n')
1847 sys.stdout.flush()
1848 sys.exit(42)
1849 """],
1850 stdin=subprocess.PIPE,
1851 stdout=subprocess.PIPE,
1852 stderr=subprocess.PIPE)
1853 self.addCleanup(p.stdout.close)
1854 self.addCleanup(p.stderr.close)
1855 self.addCleanup(p.stdin.close)
1856 # Wait for the interpreter to be completely initialized before
1857 # sending any signal.
1858 p.stdout.read(1)
1859 # The process should end after this
1860 time.sleep(1)
1861 # This shouldn't raise even though the child is now dead
1862 getattr(p, method)(*args)
1863 _, stderr = p.communicate()
1864 self.assertStderrEqual(stderr, b'')
1865 rc = p.wait()
1866 self.assertEqual(rc, 42)
1867
Florent Xicluna4886d242010-03-08 13:27:26 +00001868 def test_send_signal(self):
1869 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001870
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001871 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001872 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001873
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001874 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001875 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001876
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001877 def test_send_signal_dead(self):
1878 self._kill_dead_process('send_signal', signal.SIGTERM)
1879
1880 def test_kill_dead(self):
1881 self._kill_dead_process('kill')
1882
1883 def test_terminate_dead(self):
1884 self._kill_dead_process('terminate')
1885
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001886
Brett Cannona23810f2008-05-26 19:04:21 +00001887# The module says:
1888# "NB This only works (and is only relevant) for UNIX."
1889#
1890# Actually, getoutput should work on any platform with an os.popen, but
1891# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001892@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001893class CommandTests(unittest.TestCase):
1894 def test_getoutput(self):
1895 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1896 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1897 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001898
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001899 # we use mkdtemp in the next line to create an empty directory
1900 # under our exclusive control; from that, we can invent a pathname
1901 # that we _know_ won't exist. This is guaranteed to fail.
1902 dir = None
1903 try:
1904 dir = tempfile.mkdtemp()
1905 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001906
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001907 status, output = subprocess.getstatusoutput('cat ' + name)
1908 self.assertNotEqual(status, 0)
1909 finally:
1910 if dir is not None:
1911 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001912
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001913
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001914@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1915 "poll system call not supported")
1916class ProcessTestCaseNoPoll(ProcessTestCase):
1917 def setUp(self):
1918 subprocess._has_poll = False
1919 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001920
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001921 def tearDown(self):
1922 subprocess._has_poll = True
1923 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001924
1925
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001926class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001927 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001928 def test_eintr_retry_call(self):
1929 record_calls = []
1930 def fake_os_func(*args):
1931 record_calls.append(args)
1932 if len(record_calls) == 2:
1933 raise OSError(errno.EINTR, "fake interrupted system call")
1934 return tuple(reversed(args))
1935
1936 self.assertEqual((999, 256),
1937 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1938 self.assertEqual([(256, 999)], record_calls)
1939 # This time there will be an EINTR so it will loop once.
1940 self.assertEqual((666,),
1941 subprocess._eintr_retry_call(fake_os_func, 666))
1942 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1943
1944
Tim Golden126c2962010-08-11 14:20:40 +00001945@unittest.skipUnless(mswindows, "Windows-specific tests")
1946class CommandsWithSpaces (BaseTestCase):
1947
1948 def setUp(self):
1949 super().setUp()
1950 f, fname = mkstemp(".py", "te st")
1951 self.fname = fname.lower ()
1952 os.write(f, b"import sys;"
1953 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1954 )
1955 os.close(f)
1956
1957 def tearDown(self):
1958 os.remove(self.fname)
1959 super().tearDown()
1960
1961 def with_spaces(self, *args, **kwargs):
1962 kwargs['stdout'] = subprocess.PIPE
1963 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001964 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001965 self.assertEqual(
1966 p.stdout.read ().decode("mbcs"),
1967 "2 [%r, 'ab cd']" % self.fname
1968 )
1969
1970 def test_shell_string_with_spaces(self):
1971 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001972 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1973 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001974
1975 def test_shell_sequence_with_spaces(self):
1976 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001977 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001978
1979 def test_noshell_string_with_spaces(self):
1980 # call() function with string argument with spaces on Windows
1981 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1982 "ab cd"))
1983
1984 def test_noshell_sequence_with_spaces(self):
1985 # call() function with sequence argument with spaces on Windows
1986 self.with_spaces([sys.executable, self.fname, "ab cd"])
1987
Brian Curtin79cdb662010-12-03 02:46:02 +00001988
Georg Brandla86b2622012-02-20 21:34:57 +01001989class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00001990
1991 def test_pipe(self):
1992 with subprocess.Popen([sys.executable, "-c",
1993 "import sys;"
1994 "sys.stdout.write('stdout');"
1995 "sys.stderr.write('stderr');"],
1996 stdout=subprocess.PIPE,
1997 stderr=subprocess.PIPE) as proc:
1998 self.assertEqual(proc.stdout.read(), b"stdout")
1999 self.assertStderrEqual(proc.stderr.read(), b"stderr")
2000
2001 self.assertTrue(proc.stdout.closed)
2002 self.assertTrue(proc.stderr.closed)
2003
2004 def test_returncode(self):
2005 with subprocess.Popen([sys.executable, "-c",
2006 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07002007 pass
2008 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00002009 self.assertEqual(proc.returncode, 100)
2010
2011 def test_communicate_stdin(self):
2012 with subprocess.Popen([sys.executable, "-c",
2013 "import sys;"
2014 "sys.exit(sys.stdin.read() == 'context')"],
2015 stdin=subprocess.PIPE) as proc:
2016 proc.communicate(b"context")
2017 self.assertEqual(proc.returncode, 1)
2018
2019 def test_invalid_args(self):
2020 with self.assertRaises(EnvironmentError) as c:
2021 with subprocess.Popen(['nonexisting_i_hope'],
2022 stdout=subprocess.PIPE,
2023 stderr=subprocess.PIPE) as proc:
2024 pass
2025
2026 if c.exception.errno != errno.ENOENT: # ignore "no such file"
2027 raise c.exception
2028
2029
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002030def test_main():
2031 unit_tests = (ProcessTestCase,
2032 POSIXProcessTestCase,
2033 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002034 CommandTests,
2035 ProcessTestCaseNoPoll,
2036 HelperFunctionTests,
2037 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02002038 ContextManagerTests,
2039 )
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04002040
2041 support.run_unittest(*unit_tests)
2042 support.reap_children()
2043
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00002044if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04002045 unittest.main()