blob: 65158a923a792fac2a3215594be60f3333c0c613 [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. Smithe14e9c22011-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
Benjamin Peterson964561b2011-12-10 12:31:42 -050019
20try:
21 import resource
22except ImportError:
23 resource = None
24
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000025mswindows = (sys.platform == "win32")
26
27#
28# Depends on the following external programs: Python
29#
30
31if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000032 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
33 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000034else:
35 SETBINARY = ''
36
Florent Xiclunab1e94e82010-02-27 22:12:37 +000037
38try:
39 mkstemp = tempfile.mkstemp
40except AttributeError:
41 # tempfile.mkstemp is not available
42 def mkstemp():
43 """Replacement for mkstemp, calling mktemp."""
44 fname = tempfile.mktemp()
45 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
46
Tim Peters3761e8d2004-10-13 04:07:12 +000047
Florent Xiclunac049d872010-03-27 22:47:23 +000048class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000049 def setUp(self):
50 # Try to minimize the number of children we have so this test
51 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000052 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000053
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000054 def tearDown(self):
55 for inst in subprocess._active:
56 inst.wait()
57 subprocess._cleanup()
58 self.assertFalse(subprocess._active, "subprocess._active not empty")
59
Florent Xiclunab1e94e82010-02-27 22:12:37 +000060 def assertStderrEqual(self, stderr, expected, msg=None):
61 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
62 # shutdown time. That frustrates tests trying to check stderr produced
63 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000064 actual = support.strip_python_stderr(stderr)
Florent Xiclunab1e94e82010-02-27 22:12:37 +000065 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000066
Florent Xiclunac049d872010-03-27 22:47:23 +000067
68class ProcessTestCase(BaseTestCase):
69
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000070 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000071 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000072 rc = subprocess.call([sys.executable, "-c",
73 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000074 self.assertEqual(rc, 47)
75
Peter Astrand454f7672005-01-01 09:36:35 +000076 def test_check_call_zero(self):
77 # check_call() function with zero return code
78 rc = subprocess.check_call([sys.executable, "-c",
79 "import sys; sys.exit(0)"])
80 self.assertEqual(rc, 0)
81
82 def test_check_call_nonzero(self):
83 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000084 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +000085 subprocess.check_call([sys.executable, "-c",
86 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000087 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000088
Georg Brandlf9734072008-12-07 15:30:06 +000089 def test_check_output(self):
90 # check_output() function with zero return code
91 output = subprocess.check_output(
92 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +000093 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +000094
95 def test_check_output_nonzero(self):
96 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000097 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +000098 subprocess.check_output(
99 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000100 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000101
102 def test_check_output_stderr(self):
103 # check_output() function stderr redirected to stdout
104 output = subprocess.check_output(
105 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
106 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000107 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000108
109 def test_check_output_stdout_arg(self):
110 # check_output() function stderr redirected to stdout
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000111 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000112 output = subprocess.check_output(
113 [sys.executable, "-c", "print('will not be run')"],
114 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000115 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000116 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000117
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000118 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000119 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000120 newenv = os.environ.copy()
121 newenv["FRUIT"] = "banana"
122 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000123 'import sys, os;'
124 'sys.exit(os.getenv("FRUIT")=="banana")'],
125 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000126 self.assertEqual(rc, 1)
127
Victor Stinner87b9bc32011-06-01 00:57:47 +0200128 def test_invalid_args(self):
129 # Popen() called with invalid arguments should raise TypeError
130 # but Popen.__del__ should not complain (issue #12085)
131 with support.captured_stderr() as s:
132 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
133 argcount = subprocess.Popen.__init__.__code__.co_argcount
134 too_many_args = [0] * (argcount + 1)
135 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
136 self.assertEqual(s.getvalue(), '')
137
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000138 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000139 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000140 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000141 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000142 self.addCleanup(p.stdout.close)
143 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000144 p.wait()
145 self.assertEqual(p.stdin, None)
146
147 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000148 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000149 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000150 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000151 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000152 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000153 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000154 self.addCleanup(p.stdin.close)
155 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000156 p.wait()
157 self.assertEqual(p.stdout, None)
158
159 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000160 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000161 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000162 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000163 self.addCleanup(p.stdout.close)
164 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000165 p.wait()
166 self.assertEqual(p.stderr, None)
167
Andrew Svetlovafbf90c2012-10-06 18:02:05 +0300168 @unittest.skipIf(mswindows, "path not included in Windows message")
169 def test_path_in_arg_not_found_message(self):
170 # Check that the error message displays the path not found when
171 # args[0] is not found.
172 self.assertRaisesRegex(FileNotFoundError, "notfound_blahblah",
173 subprocess.Popen, ["notfound_blahblah"])
174
175 @unittest.skipIf(mswindows, "path not displayed in Windows message")
176 def test_path_in_executable_not_found_message(self):
177 # Check that the error message displays the executable argument (and
178 # not args[0]) when the executable argument is not found
179 # (issue #16114).
180 # We call sys.exit() inside the code to prevent the test runner
181 # from hanging if the test fails and finds python.
182 self.assertRaisesRegex(FileNotFoundError, "notfound_blahblah",
183 subprocess.Popen, [sys.executable, "-c",
184 "import sys; sys.exit(47)"],
185 executable="notfound_blahblah")
186 self.assertRaisesRegex(FileNotFoundError, "exenotfound_blahblah",
187 subprocess.Popen, ["argnotfound_blahblah"],
188 executable="exenotfound_blahblah")
189
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700190 # For use in the test_cwd* tests below.
191 def _normalize_cwd(self, cwd):
192 # Normalize an expected cwd (for Tru64 support).
193 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
194 # strings. See bug #1063571.
195 original_cwd = os.getcwd()
196 os.chdir(cwd)
197 cwd = os.getcwd()
198 os.chdir(original_cwd)
199 return cwd
200
201 # For use in the test_cwd* tests below.
202 def _split_python_path(self):
203 # Return normalized (python_dir, python_base).
204 python_path = os.path.realpath(sys.executable)
205 return os.path.split(python_path)
206
207 # For use in the test_cwd* tests below.
208 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
209 # Invoke Python via Popen, and assert that (1) the call succeeds,
210 # and that (2) the current working directory of the child process
211 # matches *expected_cwd*.
212 p = subprocess.Popen([python_arg, "-c",
213 "import os, sys; "
214 "sys.stdout.write(os.getcwd()); "
215 "sys.exit(47)"],
216 stdout=subprocess.PIPE,
217 **kwargs)
218 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000219 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700220 self.assertEqual(47, p.returncode)
221 normcase = os.path.normcase
222 self.assertEqual(normcase(expected_cwd),
223 normcase(p.stdout.read().decode("utf-8")))
224
225 def test_cwd(self):
226 # Check that cwd changes the cwd for the child process.
227 temp_dir = tempfile.gettempdir()
228 temp_dir = self._normalize_cwd(temp_dir)
229 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
230
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700231 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700232 def test_cwd_with_relative_arg(self):
233 # Check that Popen looks for args[0] relative to cwd if args[0]
234 # is relative.
235 python_dir, python_base = self._split_python_path()
236 rel_python = os.path.join(os.curdir, python_base)
237 with support.temp_cwd() as wrong_dir:
238 # Before calling with the correct cwd, confirm that the call fails
239 # without cwd and with the wrong cwd.
240 self.assertRaises(OSError, subprocess.Popen,
241 [rel_python])
242 self.assertRaises(OSError, subprocess.Popen,
243 [rel_python], cwd=wrong_dir)
244 python_dir = self._normalize_cwd(python_dir)
245 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
246
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700247 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700248 def test_cwd_with_relative_executable(self):
249 # Check that Popen looks for executable relative to cwd if executable
250 # is relative (and that executable takes precedence over args[0]).
251 python_dir, python_base = self._split_python_path()
252 rel_python = os.path.join(os.curdir, python_base)
253 doesntexist = "somethingyoudonthave"
254 with support.temp_cwd() as wrong_dir:
255 # Before calling with the correct cwd, confirm that the call fails
256 # without cwd and with the wrong cwd.
257 self.assertRaises(OSError, subprocess.Popen,
258 [doesntexist], executable=rel_python)
259 self.assertRaises(OSError, subprocess.Popen,
260 [doesntexist], executable=rel_python,
261 cwd=wrong_dir)
262 python_dir = self._normalize_cwd(python_dir)
263 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
264 cwd=python_dir)
265
266 def test_cwd_with_absolute_arg(self):
267 # Check that Popen can find the executable when the cwd is wrong
268 # if args[0] is an absolute path.
269 python_dir, python_base = self._split_python_path()
270 abs_python = os.path.join(python_dir, python_base)
271 rel_python = os.path.join(os.curdir, python_base)
272 with script_helper.temp_dir() as wrong_dir:
273 # Before calling with an absolute path, confirm that using a
274 # relative path fails.
275 self.assertRaises(OSError, subprocess.Popen,
276 [rel_python], cwd=wrong_dir)
277 wrong_dir = self._normalize_cwd(wrong_dir)
278 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
279
280 def test_executable_with_cwd(self):
281 python_dir, python_base = self._split_python_path()
282 python_dir = self._normalize_cwd(python_dir)
283 self._assert_cwd(python_dir, "somethingyoudonthave",
284 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000285
286 @unittest.skipIf(sysconfig.is_python_build(),
287 "need an installed Python. See #7774")
288 def test_executable_without_cwd(self):
289 # For a normal installation, it should work without 'cwd'
290 # argument. For test runs in the build directory, see #7774.
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700291 self._assert_cwd('', "somethingyoudonthave", executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000292
293 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000294 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000295 p = subprocess.Popen([sys.executable, "-c",
296 'import sys; sys.exit(sys.stdin.read() == "pear")'],
297 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000298 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000299 p.stdin.close()
300 p.wait()
301 self.assertEqual(p.returncode, 1)
302
303 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000304 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000305 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000306 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000307 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000308 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000309 os.lseek(d, 0, 0)
310 p = subprocess.Popen([sys.executable, "-c",
311 'import sys; sys.exit(sys.stdin.read() == "pear")'],
312 stdin=d)
313 p.wait()
314 self.assertEqual(p.returncode, 1)
315
316 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000317 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000318 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000319 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000320 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000321 tf.seek(0)
322 p = subprocess.Popen([sys.executable, "-c",
323 'import sys; sys.exit(sys.stdin.read() == "pear")'],
324 stdin=tf)
325 p.wait()
326 self.assertEqual(p.returncode, 1)
327
328 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000329 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000330 p = subprocess.Popen([sys.executable, "-c",
331 'import sys; sys.stdout.write("orange")'],
332 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000333 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000334 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000335
336 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000337 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000338 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000339 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000340 d = tf.fileno()
341 p = subprocess.Popen([sys.executable, "-c",
342 'import sys; sys.stdout.write("orange")'],
343 stdout=d)
344 p.wait()
345 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000346 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000347
348 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000349 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000350 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000351 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000352 p = subprocess.Popen([sys.executable, "-c",
353 'import sys; sys.stdout.write("orange")'],
354 stdout=tf)
355 p.wait()
356 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000357 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000358
359 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000360 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000361 p = subprocess.Popen([sys.executable, "-c",
362 'import sys; sys.stderr.write("strawberry")'],
363 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000364 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000365 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000366
367 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000368 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000369 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000370 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000371 d = tf.fileno()
372 p = subprocess.Popen([sys.executable, "-c",
373 'import sys; sys.stderr.write("strawberry")'],
374 stderr=d)
375 p.wait()
376 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000377 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000378
379 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000380 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000381 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000382 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000383 p = subprocess.Popen([sys.executable, "-c",
384 'import sys; sys.stderr.write("strawberry")'],
385 stderr=tf)
386 p.wait()
387 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000388 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000389
390 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000391 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000392 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000393 'import sys;'
394 'sys.stdout.write("apple");'
395 'sys.stdout.flush();'
396 'sys.stderr.write("orange")'],
397 stdout=subprocess.PIPE,
398 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000399 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000400 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000401
402 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000403 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000404 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000405 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000406 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000407 'import sys;'
408 'sys.stdout.write("apple");'
409 'sys.stdout.flush();'
410 'sys.stderr.write("orange")'],
411 stdout=tf,
412 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000413 p.wait()
414 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000415 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000416
Thomas Wouters89f507f2006-12-13 04:49:30 +0000417 def test_stdout_filedes_of_stdout(self):
418 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000419 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000420 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000421 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000422
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000423 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000424 newenv = os.environ.copy()
425 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200426 with subprocess.Popen([sys.executable, "-c",
427 'import sys,os;'
428 'sys.stdout.write(os.getenv("FRUIT"))'],
429 stdout=subprocess.PIPE,
430 env=newenv) as p:
431 stdout, stderr = p.communicate()
432 self.assertEqual(stdout, b"orange")
433
Victor Stinner62d51182011-06-23 01:02:25 +0200434 # Windows requires at least the SYSTEMROOT environment variable to start
435 # Python
436 @unittest.skipIf(sys.platform == 'win32',
437 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200438 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200439 'the python library cannot be loaded '
440 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200441 def test_empty_env(self):
442 with subprocess.Popen([sys.executable, "-c",
443 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200444 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200445 stdout=subprocess.PIPE,
446 env={}) as p:
447 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200448 self.assertIn(stdout.strip(),
449 (b"[]",
450 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
451 # environment
452 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000453
Peter Astrandcbac93c2005-03-03 20:24:28 +0000454 def test_communicate_stdin(self):
455 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000456 'import sys;'
457 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000458 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000459 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000460 self.assertEqual(p.returncode, 1)
461
462 def test_communicate_stdout(self):
463 p = subprocess.Popen([sys.executable, "-c",
464 'import sys; sys.stdout.write("pineapple")'],
465 stdout=subprocess.PIPE)
466 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000467 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000468 self.assertEqual(stderr, None)
469
470 def test_communicate_stderr(self):
471 p = subprocess.Popen([sys.executable, "-c",
472 'import sys; sys.stderr.write("pineapple")'],
473 stderr=subprocess.PIPE)
474 (stdout, stderr) = p.communicate()
475 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000476 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000477
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000478 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000479 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000480 'import sys,os;'
481 'sys.stderr.write("pineapple");'
482 'sys.stdout.write(sys.stdin.read())'],
483 stdin=subprocess.PIPE,
484 stdout=subprocess.PIPE,
485 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000486 self.addCleanup(p.stdout.close)
487 self.addCleanup(p.stderr.close)
488 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000489 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000490 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000491 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000492
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000493 # Test for the fd leak reported in http://bugs.python.org/issue2791.
494 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000495 for stdin_pipe in (False, True):
496 for stdout_pipe in (False, True):
497 for stderr_pipe in (False, True):
498 options = {}
499 if stdin_pipe:
500 options['stdin'] = subprocess.PIPE
501 if stdout_pipe:
502 options['stdout'] = subprocess.PIPE
503 if stderr_pipe:
504 options['stderr'] = subprocess.PIPE
505 if not options:
506 continue
507 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
508 p.communicate()
509 if p.stdin is not None:
510 self.assertTrue(p.stdin.closed)
511 if p.stdout is not None:
512 self.assertTrue(p.stdout.closed)
513 if p.stderr is not None:
514 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000515
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000516 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000517 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000518 p = subprocess.Popen([sys.executable, "-c",
519 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000520 (stdout, stderr) = p.communicate()
521 self.assertEqual(stdout, None)
522 self.assertEqual(stderr, None)
523
524 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000525 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000526 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000527 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000528 x, y = os.pipe()
529 if mswindows:
530 pipe_buf = 512
531 else:
532 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
533 os.close(x)
534 os.close(y)
535 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000536 'import sys,os;'
537 'sys.stdout.write(sys.stdin.read(47));'
538 'sys.stderr.write("xyz"*%d);'
539 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
540 stdin=subprocess.PIPE,
541 stdout=subprocess.PIPE,
542 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000543 self.addCleanup(p.stdout.close)
544 self.addCleanup(p.stderr.close)
545 self.addCleanup(p.stdin.close)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000546 string_to_write = b"abc"*pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000547 (stdout, stderr) = p.communicate(string_to_write)
548 self.assertEqual(stdout, string_to_write)
549
550 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000551 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000552 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000553 'import sys,os;'
554 'sys.stdout.write(sys.stdin.read())'],
555 stdin=subprocess.PIPE,
556 stdout=subprocess.PIPE,
557 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000558 self.addCleanup(p.stdout.close)
559 self.addCleanup(p.stderr.close)
560 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000561 p.stdin.write(b"banana")
562 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000563 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000564 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000565
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000566 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000567 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000568 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200569 'buf = sys.stdout.buffer;'
570 'buf.write(sys.stdin.readline().encode());'
571 'buf.flush();'
572 'buf.write(b"line2\\n");'
573 'buf.flush();'
574 'buf.write(sys.stdin.read().encode());'
575 'buf.flush();'
576 'buf.write(b"line4\\n");'
577 'buf.flush();'
578 'buf.write(b"line5\\r\\n");'
579 'buf.flush();'
580 'buf.write(b"line6\\r");'
581 'buf.flush();'
582 'buf.write(b"\\nline7");'
583 'buf.flush();'
584 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200585 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000586 stdout=subprocess.PIPE,
587 universal_newlines=1)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200588 p.stdin.write("line1\n")
589 self.assertEqual(p.stdout.readline(), "line1\n")
590 p.stdin.write("line3\n")
591 p.stdin.close()
Brian Curtin3c6a9512010-11-05 03:58:52 +0000592 self.addCleanup(p.stdout.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200593 self.assertEqual(p.stdout.readline(),
594 "line2\n")
595 self.assertEqual(p.stdout.read(6),
596 "line3\n")
597 self.assertEqual(p.stdout.read(),
598 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000599
600 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000601 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000602 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000603 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200604 'buf = sys.stdout.buffer;'
605 'buf.write(b"line2\\n");'
606 'buf.flush();'
607 'buf.write(b"line4\\n");'
608 'buf.flush();'
609 'buf.write(b"line5\\r\\n");'
610 'buf.flush();'
611 'buf.write(b"line6\\r");'
612 'buf.flush();'
613 'buf.write(b"\\nline7");'
614 'buf.flush();'
615 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200616 stderr=subprocess.PIPE,
617 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000618 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000619 self.addCleanup(p.stdout.close)
620 self.addCleanup(p.stderr.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200621 # BUG: can't give a non-empty stdin because it breaks both the
622 # select- and poll-based communicate() implementations.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000623 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200624 self.assertEqual(stdout,
625 "line2\nline4\nline5\nline6\nline7\nline8")
626
627 def test_universal_newlines_communicate_stdin(self):
628 # universal newlines through communicate(), with only stdin
629 p = subprocess.Popen([sys.executable, "-c",
630 'import sys,os;' + SETBINARY + '''\nif True:
631 s = sys.stdin.readline()
632 assert s == "line1\\n", repr(s)
633 s = sys.stdin.read()
634 assert s == "line3\\n", repr(s)
635 '''],
636 stdin=subprocess.PIPE,
637 universal_newlines=1)
638 (stdout, stderr) = p.communicate("line1\nline3\n")
639 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000640
Andrew Svetlovf3765072012-08-14 18:35:17 +0300641 def test_universal_newlines_communicate_input_none(self):
642 # Test communicate(input=None) with universal newlines.
643 #
644 # We set stdout to PIPE because, as of this writing, a different
645 # code path is tested when the number of pipes is zero or one.
646 p = subprocess.Popen([sys.executable, "-c", "pass"],
647 stdin=subprocess.PIPE,
648 stdout=subprocess.PIPE,
649 universal_newlines=True)
650 p.communicate()
651 self.assertEqual(p.returncode, 0)
652
Andrew Svetlov82860712012-08-19 22:13:41 +0300653 def test_universal_newlines_communicate_encodings(self):
654 # Check that universal newlines mode works for various encodings,
655 # in particular for encodings in the UTF-16 and UTF-32 families.
656 # See issue #15595.
657 #
658 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
659 # without, and UTF-16 and UTF-32.
660 for encoding in ['utf-16', 'utf-32-be']:
661 old_getpreferredencoding = locale.getpreferredencoding
662 # Indirectly via io.TextIOWrapper, Popen() defaults to
663 # locale.getpreferredencoding(False) and earlier in Python 3.2 to
664 # locale.getpreferredencoding().
665 def getpreferredencoding(do_setlocale=True):
666 return encoding
667 code = ("import sys; "
668 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
669 encoding)
670 args = [sys.executable, '-c', code]
671 try:
672 locale.getpreferredencoding = getpreferredencoding
673 # We set stdin to be non-None because, as of this writing,
674 # a different code path is used when the number of pipes is
675 # zero or one.
676 popen = subprocess.Popen(args, universal_newlines=True,
677 stdin=subprocess.PIPE,
678 stdout=subprocess.PIPE)
679 stdout, stderr = popen.communicate(input='')
680 finally:
681 locale.getpreferredencoding = old_getpreferredencoding
682
683 self.assertEqual(stdout, '1\n2\n3\n4')
684
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000685 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000686 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000687 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000688 max_handles = 1026 # too much for most UNIX systems
689 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000690 max_handles = 2050 # too much for (at least some) Windows setups
691 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400692 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000693 try:
694 for i in range(max_handles):
695 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400696 tmpfile = os.path.join(tmpdir, support.TESTFN)
697 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000698 except OSError as e:
699 if e.errno != errno.EMFILE:
700 raise
701 break
702 else:
703 self.skipTest("failed to reach the file descriptor limit "
704 "(tried %d)" % max_handles)
705 # Close a couple of them (should be enough for a subprocess)
706 for i in range(10):
707 os.close(handles.pop())
708 # Loop creating some subprocesses. If one of them leaks some fds,
709 # the next loop iteration will fail by reaching the max fd limit.
710 for i in range(15):
711 p = subprocess.Popen([sys.executable, "-c",
712 "import sys;"
713 "sys.stdout.write(sys.stdin.read())"],
714 stdin=subprocess.PIPE,
715 stdout=subprocess.PIPE,
716 stderr=subprocess.PIPE)
717 data = p.communicate(b"lime")[0]
718 self.assertEqual(data, b"lime")
719 finally:
720 for h in handles:
721 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400722 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000723
724 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000725 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
726 '"a b c" d e')
727 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
728 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000729 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
730 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000731 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
732 'a\\\\\\b "de fg" h')
733 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
734 'a\\\\\\"b c d')
735 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
736 '"a\\\\b c" d e')
737 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
738 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000739 self.assertEqual(subprocess.list2cmdline(['ab', '']),
740 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000741
742
743 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000744 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000745 "-c", "import time; time.sleep(1)"])
746 count = 0
747 while p.poll() is None:
748 time.sleep(0.1)
749 count += 1
750 # We expect that the poll loop probably went around about 10 times,
751 # but, based on system scheduling we can't control, it's possible
752 # poll() never returned None. It "should be" very rare that it
753 # didn't go around at least twice.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000754 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000755 # Subsequent invocations should just return the returncode
756 self.assertEqual(p.poll(), 0)
757
758
759 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000760 p = subprocess.Popen([sys.executable,
761 "-c", "import time; time.sleep(2)"])
762 self.assertEqual(p.wait(), 0)
763 # Subsequent invocations should just return the returncode
764 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000765
Peter Astrand738131d2004-11-30 21:04:45 +0000766
767 def test_invalid_bufsize(self):
768 # an invalid type of the bufsize argument should raise
769 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000770 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000771 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000772
Guido van Rossum46a05a72007-06-07 21:56:45 +0000773 def test_bufsize_is_none(self):
774 # bufsize=None should be the same as bufsize=0.
775 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
776 self.assertEqual(p.wait(), 0)
777 # Again with keyword arg
778 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
779 self.assertEqual(p.wait(), 0)
780
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000781 def test_leaking_fds_on_error(self):
782 # see bug #5179: Popen leaks file descriptors to PIPEs if
783 # the child fails to execute; this will eventually exhaust
784 # the maximum number of open fds. 1024 seems a very common
785 # value for that limit, but Windows has 2048, so we loop
786 # 1024 times (each call leaked two fds).
787 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000788 # Windows raises IOError. Others raise OSError.
789 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000790 subprocess.Popen(['nonexisting_i_hope'],
791 stdout=subprocess.PIPE,
792 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400793 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400794 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000795 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000796
Victor Stinnerb3693582010-05-21 20:13:12 +0000797 def test_issue8780(self):
798 # Ensure that stdout is inherited from the parent
799 # if stdout=PIPE is not used
800 code = ';'.join((
801 'import subprocess, sys',
802 'retcode = subprocess.call('
803 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
804 'assert retcode == 0'))
805 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000806 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000807
Tim Goldenaf5ac392010-08-06 13:03:56 +0000808 def test_handles_closed_on_exception(self):
809 # If CreateProcess exits with an error, ensure the
810 # duplicate output handles are released
811 ifhandle, ifname = mkstemp()
812 ofhandle, ofname = mkstemp()
813 efhandle, efname = mkstemp()
814 try:
815 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
816 stderr=efhandle)
817 except OSError:
818 os.close(ifhandle)
819 os.remove(ifname)
820 os.close(ofhandle)
821 os.remove(ofname)
822 os.close(efhandle)
823 os.remove(efname)
824 self.assertFalse(os.path.exists(ifname))
825 self.assertFalse(os.path.exists(ofname))
826 self.assertFalse(os.path.exists(efname))
827
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200828 def test_communicate_epipe(self):
829 # Issue 10963: communicate() should hide EPIPE
830 p = subprocess.Popen([sys.executable, "-c", 'pass'],
831 stdin=subprocess.PIPE,
832 stdout=subprocess.PIPE,
833 stderr=subprocess.PIPE)
834 self.addCleanup(p.stdout.close)
835 self.addCleanup(p.stderr.close)
836 self.addCleanup(p.stdin.close)
837 p.communicate(b"x" * 2**20)
838
839 def test_communicate_epipe_only_stdin(self):
840 # Issue 10963: communicate() should hide EPIPE
841 p = subprocess.Popen([sys.executable, "-c", 'pass'],
842 stdin=subprocess.PIPE)
843 self.addCleanup(p.stdin.close)
844 time.sleep(2)
845 p.communicate(b"x" * 2**20)
846
Victor Stinner1848db82011-07-05 14:49:46 +0200847 @unittest.skipUnless(hasattr(signal, 'SIGALRM'),
848 "Requires signal.SIGALRM")
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200849 def test_communicate_eintr(self):
850 # Issue #12493: communicate() should handle EINTR
851 def handler(signum, frame):
852 pass
853 old_handler = signal.signal(signal.SIGALRM, handler)
854 self.addCleanup(signal.signal, signal.SIGALRM, old_handler)
855
856 # the process is running for 2 seconds
857 args = [sys.executable, "-c", 'import time; time.sleep(2)']
858 for stream in ('stdout', 'stderr'):
859 kw = {stream: subprocess.PIPE}
860 with subprocess.Popen(args, **kw) as process:
861 signal.alarm(1)
862 # communicate() will be interrupted by SIGALRM
863 process.communicate()
864
Tim Peterse718f612004-10-12 21:51:32 +0000865
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000866# context manager
867class _SuppressCoreFiles(object):
868 """Try to prevent core files from being created."""
869 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000870
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000871 def __enter__(self):
872 """Try to save previous ulimit, then set it to (0, 0)."""
Benjamin Peterson964561b2011-12-10 12:31:42 -0500873 if resource is not None:
874 try:
875 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
876 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
877 except (ValueError, resource.error):
878 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000879
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000880 if sys.platform == 'darwin':
881 # Check if the 'Crash Reporter' on OSX was configured
882 # in 'Developer' mode and warn that it will get triggered
883 # when it is.
884 #
885 # This assumes that this context manager is used in tests
886 # that might trigger the next manager.
887 value = subprocess.Popen(['/usr/bin/defaults', 'read',
888 'com.apple.CrashReporter', 'DialogType'],
889 stdout=subprocess.PIPE).communicate()[0]
890 if value.strip() == b'developer':
891 print("this tests triggers the Crash Reporter, "
892 "that is intentional", end='')
893 sys.stdout.flush()
894
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000895 def __exit__(self, *args):
896 """Return core file behavior to default."""
897 if self.old_limit is None:
898 return
Benjamin Peterson964561b2011-12-10 12:31:42 -0500899 if resource is not None:
900 try:
901 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
902 except (ValueError, resource.error):
903 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000904
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000905
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000906@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000907class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000908
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000909 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000910 nonexistent_dir = "/_this/pa.th/does/not/exist"
911 try:
912 os.chdir(nonexistent_dir)
913 except OSError as e:
914 # This avoids hard coding the errno value or the OS perror()
915 # string and instead capture the exception that we want to see
916 # below for comparison.
917 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000918 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000919 else:
920 self.fail("chdir to nonexistant directory %s succeeded." %
921 nonexistent_dir)
922
923 # Error in the child re-raised in the parent.
924 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000925 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000926 cwd=nonexistent_dir)
927 except OSError as e:
928 # Test that the child process chdir failure actually makes
929 # it up to the parent process as the correct exception.
930 self.assertEqual(desired_exception.errno, e.errno)
931 self.assertEqual(desired_exception.strerror, e.strerror)
932 else:
933 self.fail("Expected OSError: %s" % desired_exception)
934
935 def test_restore_signals(self):
936 # Code coverage for both values of restore_signals to make sure it
937 # at least does not blow up.
938 # A test for behavior would be complex. Contributions welcome.
939 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
940 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
941
942 def test_start_new_session(self):
943 # For code coverage of calling setsid(). We don't care if we get an
944 # EPERM error from it depending on the test execution environment, that
945 # still indicates that it was called.
946 try:
947 output = subprocess.check_output(
948 [sys.executable, "-c",
949 "import os; print(os.getpgid(os.getpid()))"],
950 start_new_session=True)
951 except OSError as e:
952 if e.errno != errno.EPERM:
953 raise
954 else:
955 parent_pgid = os.getpgid(os.getpid())
956 child_pgid = int(output)
957 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000958
959 def test_run_abort(self):
960 # returncode handles signal termination
961 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000962 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000963 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000964 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000965 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000966
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000967 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000968 # DISCLAIMER: Setting environment variables is *not* a good use
969 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000970 p = subprocess.Popen([sys.executable, "-c",
971 'import sys,os;'
972 'sys.stdout.write(os.getenv("FRUIT"))'],
973 stdout=subprocess.PIPE,
974 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000975 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000976 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000977
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000978 def test_preexec_exception(self):
979 def raise_it():
980 raise ValueError("What if two swallows carried a coconut?")
981 try:
982 p = subprocess.Popen([sys.executable, "-c", ""],
983 preexec_fn=raise_it)
984 except RuntimeError as e:
985 self.assertTrue(
986 subprocess._posixsubprocess,
987 "Expected a ValueError from the preexec_fn")
988 except ValueError as e:
989 self.assertIn("coconut", e.args[0])
990 else:
991 self.fail("Exception raised by preexec_fn did not make it "
992 "to the parent process.")
993
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000994 def test_preexec_gc_module_failure(self):
995 # This tests the code that disables garbage collection if the child
996 # process will execute any Python.
997 def raise_runtime_error():
998 raise RuntimeError("this shouldn't escape")
999 enabled = gc.isenabled()
1000 orig_gc_disable = gc.disable
1001 orig_gc_isenabled = gc.isenabled
1002 try:
1003 gc.disable()
1004 self.assertFalse(gc.isenabled())
1005 subprocess.call([sys.executable, '-c', ''],
1006 preexec_fn=lambda: None)
1007 self.assertFalse(gc.isenabled(),
1008 "Popen enabled gc when it shouldn't.")
1009
1010 gc.enable()
1011 self.assertTrue(gc.isenabled())
1012 subprocess.call([sys.executable, '-c', ''],
1013 preexec_fn=lambda: None)
1014 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1015
1016 gc.disable = raise_runtime_error
1017 self.assertRaises(RuntimeError, subprocess.Popen,
1018 [sys.executable, '-c', ''],
1019 preexec_fn=lambda: None)
1020
1021 del gc.isenabled # force an AttributeError
1022 self.assertRaises(AttributeError, subprocess.Popen,
1023 [sys.executable, '-c', ''],
1024 preexec_fn=lambda: None)
1025 finally:
1026 gc.disable = orig_gc_disable
1027 gc.isenabled = orig_gc_isenabled
1028 if not enabled:
1029 gc.disable()
1030
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001031 def test_args_string(self):
1032 # args is a string
1033 fd, fname = mkstemp()
1034 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001035 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001036 fobj.write("#!/bin/sh\n")
1037 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1038 sys.executable)
1039 os.chmod(fname, 0o700)
1040 p = subprocess.Popen(fname)
1041 p.wait()
1042 os.remove(fname)
1043 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001044
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001045 def test_invalid_args(self):
1046 # invalid arguments should raise ValueError
1047 self.assertRaises(ValueError, subprocess.call,
1048 [sys.executable, "-c",
1049 "import sys; sys.exit(47)"],
1050 startupinfo=47)
1051 self.assertRaises(ValueError, subprocess.call,
1052 [sys.executable, "-c",
1053 "import sys; sys.exit(47)"],
1054 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001055
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001056 def test_shell_sequence(self):
1057 # Run command through the shell (sequence)
1058 newenv = os.environ.copy()
1059 newenv["FRUIT"] = "apple"
1060 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1061 stdout=subprocess.PIPE,
1062 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001063 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001064 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001065
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001066 def test_shell_string(self):
1067 # Run command through the shell (string)
1068 newenv = os.environ.copy()
1069 newenv["FRUIT"] = "apple"
1070 p = subprocess.Popen("echo $FRUIT", shell=1,
1071 stdout=subprocess.PIPE,
1072 env=newenv)
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().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001075
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001076 def test_call_string(self):
1077 # call() function with string argument on UNIX
1078 fd, fname = mkstemp()
1079 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001080 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001081 fobj.write("#!/bin/sh\n")
1082 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1083 sys.executable)
1084 os.chmod(fname, 0o700)
1085 rc = subprocess.call(fname)
1086 os.remove(fname)
1087 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001088
Stefan Krah9542cc62010-07-19 14:20:53 +00001089 def test_specific_shell(self):
1090 # Issue #9265: Incorrect name passed as arg[0].
1091 shells = []
1092 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1093 for name in ['bash', 'ksh']:
1094 sh = os.path.join(prefix, name)
1095 if os.path.isfile(sh):
1096 shells.append(sh)
1097 if not shells: # Will probably work for any shell but csh.
1098 self.skipTest("bash or ksh required for this test")
1099 sh = '/bin/sh'
1100 if os.path.isfile(sh) and not os.path.islink(sh):
1101 # Test will fail if /bin/sh is a symlink to csh.
1102 shells.append(sh)
1103 for sh in shells:
1104 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1105 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001106 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001107 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1108
Florent Xicluna4886d242010-03-08 13:27:26 +00001109 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001110 # Do not inherit file handles from the parent.
1111 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001112 p = subprocess.Popen([sys.executable, "-c", """if 1:
1113 import sys, time
1114 sys.stdout.write('x\\n')
1115 sys.stdout.flush()
1116 time.sleep(30)
1117 """],
1118 close_fds=True,
1119 stdin=subprocess.PIPE,
1120 stdout=subprocess.PIPE,
1121 stderr=subprocess.PIPE)
1122 # Wait for the interpreter to be completely initialized before
1123 # sending any signal.
1124 p.stdout.read(1)
1125 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001126 return p
1127
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001128 def _kill_dead_process(self, method, *args):
1129 # Do not inherit file handles from the parent.
1130 # It should fix failures on some platforms.
1131 p = subprocess.Popen([sys.executable, "-c", """if 1:
1132 import sys, time
1133 sys.stdout.write('x\\n')
1134 sys.stdout.flush()
1135 """],
1136 close_fds=True,
1137 stdin=subprocess.PIPE,
1138 stdout=subprocess.PIPE,
1139 stderr=subprocess.PIPE)
1140 # Wait for the interpreter to be completely initialized before
1141 # sending any signal.
1142 p.stdout.read(1)
1143 # The process should end after this
1144 time.sleep(1)
1145 # This shouldn't raise even though the child is now dead
1146 getattr(p, method)(*args)
1147 p.communicate()
1148
Florent Xicluna4886d242010-03-08 13:27:26 +00001149 def test_send_signal(self):
1150 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001151 _, stderr = p.communicate()
1152 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001153 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001154
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001155 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001156 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001157 _, stderr = p.communicate()
1158 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001159 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001160
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001161 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001162 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001163 _, stderr = p.communicate()
1164 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001165 self.assertEqual(p.wait(), -signal.SIGTERM)
1166
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001167 def test_send_signal_dead(self):
1168 # Sending a signal to a dead process
1169 self._kill_dead_process('send_signal', signal.SIGINT)
1170
1171 def test_kill_dead(self):
1172 # Killing a dead process
1173 self._kill_dead_process('kill')
1174
1175 def test_terminate_dead(self):
1176 # Terminating a dead process
1177 self._kill_dead_process('terminate')
1178
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001179 def check_close_std_fds(self, fds):
1180 # Issue #9905: test that subprocess pipes still work properly with
1181 # some standard fds closed
1182 stdin = 0
1183 newfds = []
1184 for a in fds:
1185 b = os.dup(a)
1186 newfds.append(b)
1187 if a == 0:
1188 stdin = b
1189 try:
1190 for fd in fds:
1191 os.close(fd)
1192 out, err = subprocess.Popen([sys.executable, "-c",
1193 'import sys;'
1194 'sys.stdout.write("apple");'
1195 'sys.stdout.flush();'
1196 'sys.stderr.write("orange")'],
1197 stdin=stdin,
1198 stdout=subprocess.PIPE,
1199 stderr=subprocess.PIPE).communicate()
1200 err = support.strip_python_stderr(err)
1201 self.assertEqual((out, err), (b'apple', b'orange'))
1202 finally:
1203 for b, a in zip(newfds, fds):
1204 os.dup2(b, a)
1205 for b in newfds:
1206 os.close(b)
1207
1208 def test_close_fd_0(self):
1209 self.check_close_std_fds([0])
1210
1211 def test_close_fd_1(self):
1212 self.check_close_std_fds([1])
1213
1214 def test_close_fd_2(self):
1215 self.check_close_std_fds([2])
1216
1217 def test_close_fds_0_1(self):
1218 self.check_close_std_fds([0, 1])
1219
1220 def test_close_fds_0_2(self):
1221 self.check_close_std_fds([0, 2])
1222
1223 def test_close_fds_1_2(self):
1224 self.check_close_std_fds([1, 2])
1225
1226 def test_close_fds_0_1_2(self):
1227 # Issue #10806: test that subprocess pipes still work properly with
1228 # all standard fds closed.
1229 self.check_close_std_fds([0, 1, 2])
1230
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001231 def test_remapping_std_fds(self):
1232 # open up some temporary files
1233 temps = [mkstemp() for i in range(3)]
1234 try:
1235 temp_fds = [fd for fd, fname in temps]
1236
1237 # unlink the files -- we won't need to reopen them
1238 for fd, fname in temps:
1239 os.unlink(fname)
1240
1241 # write some data to what will become stdin, and rewind
1242 os.write(temp_fds[1], b"STDIN")
1243 os.lseek(temp_fds[1], 0, 0)
1244
1245 # move the standard file descriptors out of the way
1246 saved_fds = [os.dup(fd) for fd in range(3)]
1247 try:
1248 # duplicate the file objects over the standard fd's
1249 for fd, temp_fd in enumerate(temp_fds):
1250 os.dup2(temp_fd, fd)
1251
1252 # now use those files in the "wrong" order, so that subprocess
1253 # has to rearrange them in the child
1254 p = subprocess.Popen([sys.executable, "-c",
1255 'import sys; got = sys.stdin.read();'
1256 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1257 stdin=temp_fds[1],
1258 stdout=temp_fds[2],
1259 stderr=temp_fds[0])
1260 p.wait()
1261 finally:
1262 # restore the original fd's underneath sys.stdin, etc.
1263 for std, saved in enumerate(saved_fds):
1264 os.dup2(saved, std)
1265 os.close(saved)
1266
1267 for fd in temp_fds:
1268 os.lseek(fd, 0, 0)
1269
1270 out = os.read(temp_fds[2], 1024)
1271 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1272 self.assertEqual(out, b"got STDIN")
1273 self.assertEqual(err, b"err")
1274
1275 finally:
1276 for fd in temp_fds:
1277 os.close(fd)
1278
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001279 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1280 # open up some temporary files
1281 temps = [mkstemp() for i in range(3)]
1282 temp_fds = [fd for fd, fname in temps]
1283 try:
1284 # unlink the files -- we won't need to reopen them
1285 for fd, fname in temps:
1286 os.unlink(fname)
1287
1288 # save a copy of the standard file descriptors
1289 saved_fds = [os.dup(fd) for fd in range(3)]
1290 try:
1291 # duplicate the temp files over the standard fd's 0, 1, 2
1292 for fd, temp_fd in enumerate(temp_fds):
1293 os.dup2(temp_fd, fd)
1294
1295 # write some data to what will become stdin, and rewind
1296 os.write(stdin_no, b"STDIN")
1297 os.lseek(stdin_no, 0, 0)
1298
1299 # now use those files in the given order, so that subprocess
1300 # has to rearrange them in the child
1301 p = subprocess.Popen([sys.executable, "-c",
1302 'import sys; got = sys.stdin.read();'
1303 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1304 stdin=stdin_no,
1305 stdout=stdout_no,
1306 stderr=stderr_no)
1307 p.wait()
1308
1309 for fd in temp_fds:
1310 os.lseek(fd, 0, 0)
1311
1312 out = os.read(stdout_no, 1024)
1313 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1314 finally:
1315 for std, saved in enumerate(saved_fds):
1316 os.dup2(saved, std)
1317 os.close(saved)
1318
1319 self.assertEqual(out, b"got STDIN")
1320 self.assertEqual(err, b"err")
1321
1322 finally:
1323 for fd in temp_fds:
1324 os.close(fd)
1325
1326 # When duping fds, if there arises a situation where one of the fds is
1327 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1328 # This tests all combinations of this.
1329 def test_swap_fds(self):
1330 self.check_swap_fds(0, 1, 2)
1331 self.check_swap_fds(0, 2, 1)
1332 self.check_swap_fds(1, 0, 2)
1333 self.check_swap_fds(1, 2, 0)
1334 self.check_swap_fds(2, 0, 1)
1335 self.check_swap_fds(2, 1, 0)
1336
Victor Stinner13bb71c2010-04-23 21:41:56 +00001337 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001338 def prepare():
1339 raise ValueError("surrogate:\uDCff")
1340
1341 try:
1342 subprocess.call(
1343 [sys.executable, "-c", "pass"],
1344 preexec_fn=prepare)
1345 except ValueError as err:
1346 # Pure Python implementations keeps the message
1347 self.assertIsNone(subprocess._posixsubprocess)
1348 self.assertEqual(str(err), "surrogate:\uDCff")
1349 except RuntimeError as err:
1350 # _posixsubprocess uses a default message
1351 self.assertIsNotNone(subprocess._posixsubprocess)
1352 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1353 else:
1354 self.fail("Expected ValueError or RuntimeError")
1355
Victor Stinner13bb71c2010-04-23 21:41:56 +00001356 def test_undecodable_env(self):
1357 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001358 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001359 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001360 env = os.environ.copy()
1361 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001362 # Use C locale to get ascii for the locale encoding to force
1363 # surrogate-escaping of \xFF in the child process; otherwise it can
1364 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001365 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001366 stdout = subprocess.check_output(
1367 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001368 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001369 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001370 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001371
1372 # test bytes
1373 key = key.encode("ascii", "surrogateescape")
1374 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001375 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001376 env = os.environ.copy()
1377 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001378 stdout = subprocess.check_output(
1379 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001380 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001381 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001382 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001383
Victor Stinnerb745a742010-05-18 17:17:23 +00001384 def test_bytes_program(self):
1385 abs_program = os.fsencode(sys.executable)
1386 path, program = os.path.split(sys.executable)
1387 program = os.fsencode(program)
1388
1389 # absolute bytes path
1390 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001391 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001392
1393 # bytes program, unicode PATH
1394 env = os.environ.copy()
1395 env["PATH"] = path
1396 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001397 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001398
1399 # bytes program, bytes PATH
1400 envb = os.environb.copy()
1401 envb[b"PATH"] = os.fsencode(path)
1402 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001403 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001404
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001405 def test_pipe_cloexec(self):
1406 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1407 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1408
1409 p1 = subprocess.Popen([sys.executable, sleeper],
1410 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1411 stderr=subprocess.PIPE, close_fds=False)
1412
1413 self.addCleanup(p1.communicate, b'')
1414
1415 p2 = subprocess.Popen([sys.executable, fd_status],
1416 stdout=subprocess.PIPE, close_fds=False)
1417
1418 output, error = p2.communicate()
1419 result_fds = set(map(int, output.split(b',')))
1420 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1421 p1.stderr.fileno()])
1422
1423 self.assertFalse(result_fds & unwanted_fds,
1424 "Expected no fds from %r to be open in child, "
1425 "found %r" %
1426 (unwanted_fds, result_fds & unwanted_fds))
1427
1428 def test_pipe_cloexec_real_tools(self):
1429 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1430 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1431
1432 subdata = b'zxcvbn'
1433 data = subdata * 4 + b'\n'
1434
1435 p1 = subprocess.Popen([sys.executable, qcat],
1436 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1437 close_fds=False)
1438
1439 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1440 stdin=p1.stdout, stdout=subprocess.PIPE,
1441 close_fds=False)
1442
1443 self.addCleanup(p1.wait)
1444 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001445 def kill_p1():
1446 try:
1447 p1.terminate()
1448 except ProcessLookupError:
1449 pass
1450 def kill_p2():
1451 try:
1452 p2.terminate()
1453 except ProcessLookupError:
1454 pass
1455 self.addCleanup(kill_p1)
1456 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001457
1458 p1.stdin.write(data)
1459 p1.stdin.close()
1460
1461 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1462
1463 self.assertTrue(readfiles, "The child hung")
1464 self.assertEqual(p2.stdout.read(), data)
1465
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001466 p1.stdout.close()
1467 p2.stdout.close()
1468
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001469 def test_close_fds(self):
1470 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1471
1472 fds = os.pipe()
1473 self.addCleanup(os.close, fds[0])
1474 self.addCleanup(os.close, fds[1])
1475
1476 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001477 # add a bunch more fds
1478 for _ in range(9):
1479 fd = os.open("/dev/null", os.O_RDONLY)
1480 self.addCleanup(os.close, fd)
1481 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001482
1483 p = subprocess.Popen([sys.executable, fd_status],
1484 stdout=subprocess.PIPE, close_fds=False)
1485 output, ignored = p.communicate()
1486 remaining_fds = set(map(int, output.split(b',')))
1487
1488 self.assertEqual(remaining_fds & open_fds, open_fds,
1489 "Some fds were closed")
1490
1491 p = subprocess.Popen([sys.executable, fd_status],
1492 stdout=subprocess.PIPE, close_fds=True)
1493 output, ignored = p.communicate()
1494 remaining_fds = set(map(int, output.split(b',')))
1495
1496 self.assertFalse(remaining_fds & open_fds,
1497 "Some fds were left open")
1498 self.assertIn(1, remaining_fds, "Subprocess failed")
1499
Gregory P. Smith8facece2012-01-21 14:01:08 -08001500 # Keep some of the fd's we opened open in the subprocess.
1501 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1502 fds_to_keep = set(open_fds.pop() for _ in range(8))
1503 p = subprocess.Popen([sys.executable, fd_status],
1504 stdout=subprocess.PIPE, close_fds=True,
1505 pass_fds=())
1506 output, ignored = p.communicate()
1507 remaining_fds = set(map(int, output.split(b',')))
1508
1509 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1510 "Some fds not in pass_fds were left open")
1511 self.assertIn(1, remaining_fds, "Subprocess failed")
1512
Victor Stinner88701e22011-06-01 13:13:04 +02001513 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1514 # descriptor of a pipe closed in the parent process is valid in the
1515 # child process according to fstat(), but the mode of the file
1516 # descriptor is invalid, and read or write raise an error.
1517 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001518 def test_pass_fds(self):
1519 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1520
1521 open_fds = set()
1522
1523 for x in range(5):
1524 fds = os.pipe()
1525 self.addCleanup(os.close, fds[0])
1526 self.addCleanup(os.close, fds[1])
1527 open_fds.update(fds)
1528
1529 for fd in open_fds:
1530 p = subprocess.Popen([sys.executable, fd_status],
1531 stdout=subprocess.PIPE, close_fds=True,
1532 pass_fds=(fd, ))
1533 output, ignored = p.communicate()
1534
1535 remaining_fds = set(map(int, output.split(b',')))
1536 to_be_closed = open_fds - {fd}
1537
1538 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1539 self.assertFalse(remaining_fds & to_be_closed,
1540 "fd to be closed passed")
1541
1542 # pass_fds overrides close_fds with a warning.
1543 with self.assertWarns(RuntimeWarning) as context:
1544 self.assertFalse(subprocess.call(
1545 [sys.executable, "-c", "import sys; sys.exit(0)"],
1546 close_fds=False, pass_fds=(fd, )))
1547 self.assertIn('overriding close_fds', str(context.warning))
1548
Gregory P. Smithe14e9c22011-03-15 14:55:17 -04001549 def test_stdout_stdin_are_single_inout_fd(self):
1550 with io.open(os.devnull, "r+") as inout:
1551 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1552 stdout=inout, stdin=inout)
1553 p.wait()
1554
1555 def test_stdout_stderr_are_single_inout_fd(self):
1556 with io.open(os.devnull, "r+") as inout:
1557 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1558 stdout=inout, stderr=inout)
1559 p.wait()
1560
1561 def test_stderr_stdin_are_single_inout_fd(self):
1562 with io.open(os.devnull, "r+") as inout:
1563 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1564 stderr=inout, stdin=inout)
1565 p.wait()
1566
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001567 def test_wait_when_sigchild_ignored(self):
1568 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1569 sigchild_ignore = support.findfile("sigchild_ignore.py",
1570 subdir="subprocessdata")
1571 p = subprocess.Popen([sys.executable, sigchild_ignore],
1572 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1573 stdout, stderr = p.communicate()
1574 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001575 " non-zero with this error:\n%s" %
1576 stderr.decode('utf8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001577
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001578 def test_select_unbuffered(self):
1579 # Issue #11459: bufsize=0 should really set the pipes as
1580 # unbuffered (and therefore let select() work properly).
1581 select = support.import_module("select")
1582 p = subprocess.Popen([sys.executable, "-c",
1583 'import sys;'
1584 'sys.stdout.write("apple")'],
1585 stdout=subprocess.PIPE,
1586 bufsize=0)
1587 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001588 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001589 try:
1590 self.assertEqual(f.read(4), b"appl")
1591 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1592 finally:
1593 p.wait()
1594
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001595 def test_zombie_fast_process_del(self):
1596 # Issue #12650: on Unix, if Popen.__del__() was called before the
1597 # process exited, it wouldn't be added to subprocess._active, and would
1598 # remain a zombie.
1599 # spawn a Popen, and delete its reference before it exits
1600 p = subprocess.Popen([sys.executable, "-c",
1601 'import sys, time;'
1602 'time.sleep(0.2)'],
1603 stdout=subprocess.PIPE,
1604 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001605 self.addCleanup(p.stdout.close)
1606 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001607 ident = id(p)
1608 pid = p.pid
1609 del p
1610 # check that p is in the active processes list
1611 self.assertIn(ident, [id(o) for o in subprocess._active])
1612
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001613 def test_leak_fast_process_del_killed(self):
1614 # Issue #12650: on Unix, if Popen.__del__() was called before the
1615 # process exited, and the process got killed by a signal, it would never
1616 # be removed from subprocess._active, which triggered a FD and memory
1617 # leak.
1618 # spawn a Popen, delete its reference and kill it
1619 p = subprocess.Popen([sys.executable, "-c",
1620 'import time;'
1621 'time.sleep(3)'],
1622 stdout=subprocess.PIPE,
1623 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001624 self.addCleanup(p.stdout.close)
1625 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001626 ident = id(p)
1627 pid = p.pid
1628 del p
1629 os.kill(pid, signal.SIGKILL)
1630 # check that p is in the active processes list
1631 self.assertIn(ident, [id(o) for o in subprocess._active])
1632
1633 # let some time for the process to exit, and create a new Popen: this
1634 # should trigger the wait() of p
1635 time.sleep(0.2)
1636 with self.assertRaises(EnvironmentError) as c:
1637 with subprocess.Popen(['nonexisting_i_hope'],
1638 stdout=subprocess.PIPE,
1639 stderr=subprocess.PIPE) as proc:
1640 pass
1641 # p should have been wait()ed on, and removed from the _active list
1642 self.assertRaises(OSError, os.waitpid, pid, 0)
1643 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1644
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001645
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001646@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001647class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001648
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001649 def test_startupinfo(self):
1650 # startupinfo argument
1651 # We uses hardcoded constants, because we do not want to
1652 # depend on win32all.
1653 STARTF_USESHOWWINDOW = 1
1654 SW_MAXIMIZE = 3
1655 startupinfo = subprocess.STARTUPINFO()
1656 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1657 startupinfo.wShowWindow = SW_MAXIMIZE
1658 # Since Python is a console process, it won't be affected
1659 # by wShowWindow, but the argument should be silently
1660 # ignored
1661 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001662 startupinfo=startupinfo)
1663
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001664 def test_creationflags(self):
1665 # creationflags argument
1666 CREATE_NEW_CONSOLE = 16
1667 sys.stderr.write(" a DOS box should flash briefly ...\n")
1668 subprocess.call(sys.executable +
1669 ' -c "import time; time.sleep(0.25)"',
1670 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001671
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001672 def test_invalid_args(self):
1673 # invalid arguments should raise ValueError
1674 self.assertRaises(ValueError, subprocess.call,
1675 [sys.executable, "-c",
1676 "import sys; sys.exit(47)"],
1677 preexec_fn=lambda: 1)
1678 self.assertRaises(ValueError, subprocess.call,
1679 [sys.executable, "-c",
1680 "import sys; sys.exit(47)"],
1681 stdout=subprocess.PIPE,
1682 close_fds=True)
1683
1684 def test_close_fds(self):
1685 # close file descriptors
1686 rc = subprocess.call([sys.executable, "-c",
1687 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001688 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001689 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001690
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001691 def test_shell_sequence(self):
1692 # Run command through the shell (sequence)
1693 newenv = os.environ.copy()
1694 newenv["FRUIT"] = "physalis"
1695 p = subprocess.Popen(["set"], shell=1,
1696 stdout=subprocess.PIPE,
1697 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001698 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001699 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001700
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001701 def test_shell_string(self):
1702 # Run command through the shell (string)
1703 newenv = os.environ.copy()
1704 newenv["FRUIT"] = "physalis"
1705 p = subprocess.Popen("set", shell=1,
1706 stdout=subprocess.PIPE,
1707 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001708 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001709 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001710
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001711 def test_call_string(self):
1712 # call() function with string argument on Windows
1713 rc = subprocess.call(sys.executable +
1714 ' -c "import sys; sys.exit(47)"')
1715 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001716
Florent Xicluna4886d242010-03-08 13:27:26 +00001717 def _kill_process(self, method, *args):
1718 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001719 p = subprocess.Popen([sys.executable, "-c", """if 1:
1720 import sys, time
1721 sys.stdout.write('x\\n')
1722 sys.stdout.flush()
1723 time.sleep(30)
1724 """],
1725 stdin=subprocess.PIPE,
1726 stdout=subprocess.PIPE,
1727 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001728 self.addCleanup(p.stdout.close)
1729 self.addCleanup(p.stderr.close)
1730 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001731 # Wait for the interpreter to be completely initialized before
1732 # sending any signal.
1733 p.stdout.read(1)
1734 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001735 _, stderr = p.communicate()
1736 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001737 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001738 self.assertNotEqual(returncode, 0)
1739
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001740 def _kill_dead_process(self, method, *args):
1741 p = subprocess.Popen([sys.executable, "-c", """if 1:
1742 import sys, time
1743 sys.stdout.write('x\\n')
1744 sys.stdout.flush()
1745 sys.exit(42)
1746 """],
1747 stdin=subprocess.PIPE,
1748 stdout=subprocess.PIPE,
1749 stderr=subprocess.PIPE)
1750 self.addCleanup(p.stdout.close)
1751 self.addCleanup(p.stderr.close)
1752 self.addCleanup(p.stdin.close)
1753 # Wait for the interpreter to be completely initialized before
1754 # sending any signal.
1755 p.stdout.read(1)
1756 # The process should end after this
1757 time.sleep(1)
1758 # This shouldn't raise even though the child is now dead
1759 getattr(p, method)(*args)
1760 _, stderr = p.communicate()
1761 self.assertStderrEqual(stderr, b'')
1762 rc = p.wait()
1763 self.assertEqual(rc, 42)
1764
Florent Xicluna4886d242010-03-08 13:27:26 +00001765 def test_send_signal(self):
1766 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001767
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001768 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001769 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001770
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001771 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001772 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001773
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001774 def test_send_signal_dead(self):
1775 self._kill_dead_process('send_signal', signal.SIGTERM)
1776
1777 def test_kill_dead(self):
1778 self._kill_dead_process('kill')
1779
1780 def test_terminate_dead(self):
1781 self._kill_dead_process('terminate')
1782
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001783
Brett Cannona23810f2008-05-26 19:04:21 +00001784# The module says:
1785# "NB This only works (and is only relevant) for UNIX."
1786#
1787# Actually, getoutput should work on any platform with an os.popen, but
1788# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001789@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001790class CommandTests(unittest.TestCase):
1791 def test_getoutput(self):
1792 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1793 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1794 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001795
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001796 # we use mkdtemp in the next line to create an empty directory
1797 # under our exclusive control; from that, we can invent a pathname
1798 # that we _know_ won't exist. This is guaranteed to fail.
1799 dir = None
1800 try:
1801 dir = tempfile.mkdtemp()
1802 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001803
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001804 status, output = subprocess.getstatusoutput('cat ' + name)
1805 self.assertNotEqual(status, 0)
1806 finally:
1807 if dir is not None:
1808 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001809
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001810
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001811@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1812 "poll system call not supported")
1813class ProcessTestCaseNoPoll(ProcessTestCase):
1814 def setUp(self):
1815 subprocess._has_poll = False
1816 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001817
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001818 def tearDown(self):
1819 subprocess._has_poll = True
1820 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001821
1822
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001823@unittest.skipUnless(getattr(subprocess, '_posixsubprocess', False),
1824 "_posixsubprocess extension module not found.")
1825class ProcessTestCasePOSIXPurePython(ProcessTestCase, POSIXProcessTestCase):
Gregory P. Smith7439e7b2011-05-28 09:06:02 -07001826 @classmethod
1827 def setUpClass(cls):
1828 global subprocess
1829 assert subprocess._posixsubprocess
1830 # Reimport subprocess while forcing _posixsubprocess to not exist.
1831 with support.check_warnings(('.*_posixsubprocess .* not being used.*',
1832 RuntimeWarning)):
1833 subprocess = support.import_fresh_module(
1834 'subprocess', blocked=['_posixsubprocess'])
1835 assert not subprocess._posixsubprocess
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001836
Gregory P. Smith7439e7b2011-05-28 09:06:02 -07001837 @classmethod
1838 def tearDownClass(cls):
1839 global subprocess
1840 # Reimport subprocess as it should be, restoring order to the universe.
1841 subprocess = support.import_fresh_module('subprocess')
1842 assert subprocess._posixsubprocess
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001843
1844
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001845class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001846 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001847 def test_eintr_retry_call(self):
1848 record_calls = []
1849 def fake_os_func(*args):
1850 record_calls.append(args)
1851 if len(record_calls) == 2:
1852 raise OSError(errno.EINTR, "fake interrupted system call")
1853 return tuple(reversed(args))
1854
1855 self.assertEqual((999, 256),
1856 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1857 self.assertEqual([(256, 999)], record_calls)
1858 # This time there will be an EINTR so it will loop once.
1859 self.assertEqual((666,),
1860 subprocess._eintr_retry_call(fake_os_func, 666))
1861 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1862
1863
Tim Golden126c2962010-08-11 14:20:40 +00001864@unittest.skipUnless(mswindows, "Windows-specific tests")
1865class CommandsWithSpaces (BaseTestCase):
1866
1867 def setUp(self):
1868 super().setUp()
1869 f, fname = mkstemp(".py", "te st")
1870 self.fname = fname.lower ()
1871 os.write(f, b"import sys;"
1872 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1873 )
1874 os.close(f)
1875
1876 def tearDown(self):
1877 os.remove(self.fname)
1878 super().tearDown()
1879
1880 def with_spaces(self, *args, **kwargs):
1881 kwargs['stdout'] = subprocess.PIPE
1882 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001883 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001884 self.assertEqual(
1885 p.stdout.read ().decode("mbcs"),
1886 "2 [%r, 'ab cd']" % self.fname
1887 )
1888
1889 def test_shell_string_with_spaces(self):
1890 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001891 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1892 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001893
1894 def test_shell_sequence_with_spaces(self):
1895 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001896 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001897
1898 def test_noshell_string_with_spaces(self):
1899 # call() function with string argument with spaces on Windows
1900 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1901 "ab cd"))
1902
1903 def test_noshell_sequence_with_spaces(self):
1904 # call() function with sequence argument with spaces on Windows
1905 self.with_spaces([sys.executable, self.fname, "ab cd"])
1906
Brian Curtin79cdb662010-12-03 02:46:02 +00001907
Georg Brandla86b2622012-02-20 21:34:57 +01001908class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00001909
1910 def test_pipe(self):
1911 with subprocess.Popen([sys.executable, "-c",
1912 "import sys;"
1913 "sys.stdout.write('stdout');"
1914 "sys.stderr.write('stderr');"],
1915 stdout=subprocess.PIPE,
1916 stderr=subprocess.PIPE) as proc:
1917 self.assertEqual(proc.stdout.read(), b"stdout")
1918 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1919
1920 self.assertTrue(proc.stdout.closed)
1921 self.assertTrue(proc.stderr.closed)
1922
1923 def test_returncode(self):
1924 with subprocess.Popen([sys.executable, "-c",
1925 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smithc9557af2011-05-11 22:18:23 -07001926 pass
1927 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00001928 self.assertEqual(proc.returncode, 100)
1929
1930 def test_communicate_stdin(self):
1931 with subprocess.Popen([sys.executable, "-c",
1932 "import sys;"
1933 "sys.exit(sys.stdin.read() == 'context')"],
1934 stdin=subprocess.PIPE) as proc:
1935 proc.communicate(b"context")
1936 self.assertEqual(proc.returncode, 1)
1937
1938 def test_invalid_args(self):
1939 with self.assertRaises(EnvironmentError) as c:
1940 with subprocess.Popen(['nonexisting_i_hope'],
1941 stdout=subprocess.PIPE,
1942 stderr=subprocess.PIPE) as proc:
1943 pass
1944
1945 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1946 raise c.exception
1947
1948
Gregory P. Smith961e0e82011-03-15 15:43:39 -04001949def test_main():
1950 unit_tests = (ProcessTestCase,
1951 POSIXProcessTestCase,
1952 Win32ProcessTestCase,
1953 ProcessTestCasePOSIXPurePython,
1954 CommandTests,
1955 ProcessTestCaseNoPoll,
1956 HelperFunctionTests,
1957 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02001958 ContextManagerTests,
1959 )
Gregory P. Smith961e0e82011-03-15 15:43:39 -04001960
1961 support.run_unittest(*unit_tests)
1962 support.reap_children()
1963
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001964if __name__ == "__main__":
Gregory P. Smithe14e9c22011-03-15 14:55:17 -04001965 unittest.main()