blob: 15fb498d2466e32ecf8eaee3af7dfe1baf7b228d [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
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700168 # For use in the test_cwd* tests below.
169 def _normalize_cwd(self, cwd):
170 # Normalize an expected cwd (for Tru64 support).
171 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
172 # strings. See bug #1063571.
173 original_cwd = os.getcwd()
174 os.chdir(cwd)
175 cwd = os.getcwd()
176 os.chdir(original_cwd)
177 return cwd
178
179 # For use in the test_cwd* tests below.
180 def _split_python_path(self):
181 # Return normalized (python_dir, python_base).
182 python_path = os.path.realpath(sys.executable)
183 return os.path.split(python_path)
184
185 # For use in the test_cwd* tests below.
186 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
187 # Invoke Python via Popen, and assert that (1) the call succeeds,
188 # and that (2) the current working directory of the child process
189 # matches *expected_cwd*.
190 p = subprocess.Popen([python_arg, "-c",
191 "import os, sys; "
192 "sys.stdout.write(os.getcwd()); "
193 "sys.exit(47)"],
194 stdout=subprocess.PIPE,
195 **kwargs)
196 self.addCleanup(p.stdout.close)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000197 p.wait()
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700198 self.assertEqual(47, p.returncode)
199 normcase = os.path.normcase
200 self.assertEqual(normcase(expected_cwd),
201 normcase(p.stdout.read().decode("utf-8")))
202
203 def test_cwd(self):
204 # Check that cwd changes the cwd for the child process.
205 temp_dir = tempfile.gettempdir()
206 temp_dir = self._normalize_cwd(temp_dir)
207 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
208
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700209 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700210 def test_cwd_with_relative_arg(self):
211 # Check that Popen looks for args[0] relative to cwd if args[0]
212 # is relative.
213 python_dir, python_base = self._split_python_path()
214 rel_python = os.path.join(os.curdir, python_base)
215 with support.temp_cwd() as wrong_dir:
216 # Before calling with the correct cwd, confirm that the call fails
217 # without cwd and with the wrong cwd.
218 self.assertRaises(OSError, subprocess.Popen,
219 [rel_python])
220 self.assertRaises(OSError, subprocess.Popen,
221 [rel_python], cwd=wrong_dir)
222 python_dir = self._normalize_cwd(python_dir)
223 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
224
Chris Jerdonekc2cd6262012-09-30 09:45:00 -0700225 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700226 def test_cwd_with_relative_executable(self):
227 # Check that Popen looks for executable relative to cwd if executable
228 # is relative (and that executable takes precedence over args[0]).
229 python_dir, python_base = self._split_python_path()
230 rel_python = os.path.join(os.curdir, python_base)
231 doesntexist = "somethingyoudonthave"
232 with support.temp_cwd() as wrong_dir:
233 # Before calling with the correct cwd, confirm that the call fails
234 # without cwd and with the wrong cwd.
235 self.assertRaises(OSError, subprocess.Popen,
236 [doesntexist], executable=rel_python)
237 self.assertRaises(OSError, subprocess.Popen,
238 [doesntexist], executable=rel_python,
239 cwd=wrong_dir)
240 python_dir = self._normalize_cwd(python_dir)
241 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
242 cwd=python_dir)
243
244 def test_cwd_with_absolute_arg(self):
245 # Check that Popen can find the executable when the cwd is wrong
246 # if args[0] is an absolute path.
247 python_dir, python_base = self._split_python_path()
248 abs_python = os.path.join(python_dir, python_base)
249 rel_python = os.path.join(os.curdir, python_base)
250 with script_helper.temp_dir() as wrong_dir:
251 # Before calling with an absolute path, confirm that using a
252 # relative path fails.
253 self.assertRaises(OSError, subprocess.Popen,
254 [rel_python], cwd=wrong_dir)
255 wrong_dir = self._normalize_cwd(wrong_dir)
256 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
257
258 def test_executable_with_cwd(self):
259 python_dir, python_base = self._split_python_path()
260 python_dir = self._normalize_cwd(python_dir)
261 self._assert_cwd(python_dir, "somethingyoudonthave",
262 executable=sys.executable, cwd=python_dir)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000263
264 @unittest.skipIf(sysconfig.is_python_build(),
265 "need an installed Python. See #7774")
266 def test_executable_without_cwd(self):
267 # For a normal installation, it should work without 'cwd'
268 # argument. For test runs in the build directory, see #7774.
Chris Jerdonekec3ea942012-09-30 00:10:28 -0700269 self._assert_cwd('', "somethingyoudonthave", executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000270
271 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000272 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000273 p = subprocess.Popen([sys.executable, "-c",
274 'import sys; sys.exit(sys.stdin.read() == "pear")'],
275 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000276 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000277 p.stdin.close()
278 p.wait()
279 self.assertEqual(p.returncode, 1)
280
281 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000282 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000283 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000284 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000285 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000286 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000287 os.lseek(d, 0, 0)
288 p = subprocess.Popen([sys.executable, "-c",
289 'import sys; sys.exit(sys.stdin.read() == "pear")'],
290 stdin=d)
291 p.wait()
292 self.assertEqual(p.returncode, 1)
293
294 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000295 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000296 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000297 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000298 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000299 tf.seek(0)
300 p = subprocess.Popen([sys.executable, "-c",
301 'import sys; sys.exit(sys.stdin.read() == "pear")'],
302 stdin=tf)
303 p.wait()
304 self.assertEqual(p.returncode, 1)
305
306 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000307 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000308 p = subprocess.Popen([sys.executable, "-c",
309 'import sys; sys.stdout.write("orange")'],
310 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000311 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000312 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000313
314 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000315 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000316 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000317 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000318 d = tf.fileno()
319 p = subprocess.Popen([sys.executable, "-c",
320 'import sys; sys.stdout.write("orange")'],
321 stdout=d)
322 p.wait()
323 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000324 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000325
326 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000327 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000328 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000329 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000330 p = subprocess.Popen([sys.executable, "-c",
331 'import sys; sys.stdout.write("orange")'],
332 stdout=tf)
333 p.wait()
334 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000335 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000336
337 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000338 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000339 p = subprocess.Popen([sys.executable, "-c",
340 'import sys; sys.stderr.write("strawberry")'],
341 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000342 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000343 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000344
345 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000346 # stderr 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.stderr.write("strawberry")'],
352 stderr=d)
353 p.wait()
354 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000355 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000356
357 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000358 # stderr 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.stderr.write("strawberry")'],
363 stderr=tf)
364 p.wait()
365 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000366 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000367
368 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000369 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000370 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000371 'import sys;'
372 'sys.stdout.write("apple");'
373 'sys.stdout.flush();'
374 'sys.stderr.write("orange")'],
375 stdout=subprocess.PIPE,
376 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000377 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000378 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000379
380 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000381 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000382 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000383 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000384 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000385 'import sys;'
386 'sys.stdout.write("apple");'
387 'sys.stdout.flush();'
388 'sys.stderr.write("orange")'],
389 stdout=tf,
390 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000391 p.wait()
392 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000393 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000394
Thomas Wouters89f507f2006-12-13 04:49:30 +0000395 def test_stdout_filedes_of_stdout(self):
396 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000397 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000398 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000399 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000400
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000401 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000402 newenv = os.environ.copy()
403 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200404 with subprocess.Popen([sys.executable, "-c",
405 'import sys,os;'
406 'sys.stdout.write(os.getenv("FRUIT"))'],
407 stdout=subprocess.PIPE,
408 env=newenv) as p:
409 stdout, stderr = p.communicate()
410 self.assertEqual(stdout, b"orange")
411
Victor Stinner62d51182011-06-23 01:02:25 +0200412 # Windows requires at least the SYSTEMROOT environment variable to start
413 # Python
414 @unittest.skipIf(sys.platform == 'win32',
415 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200416 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200417 'the python library cannot be loaded '
418 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200419 def test_empty_env(self):
420 with subprocess.Popen([sys.executable, "-c",
421 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200422 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200423 stdout=subprocess.PIPE,
424 env={}) as p:
425 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200426 self.assertIn(stdout.strip(),
427 (b"[]",
428 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
429 # environment
430 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000431
Peter Astrandcbac93c2005-03-03 20:24:28 +0000432 def test_communicate_stdin(self):
433 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000434 'import sys;'
435 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000436 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000437 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000438 self.assertEqual(p.returncode, 1)
439
440 def test_communicate_stdout(self):
441 p = subprocess.Popen([sys.executable, "-c",
442 'import sys; sys.stdout.write("pineapple")'],
443 stdout=subprocess.PIPE)
444 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000445 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000446 self.assertEqual(stderr, None)
447
448 def test_communicate_stderr(self):
449 p = subprocess.Popen([sys.executable, "-c",
450 'import sys; sys.stderr.write("pineapple")'],
451 stderr=subprocess.PIPE)
452 (stdout, stderr) = p.communicate()
453 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000454 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000455
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000456 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000457 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000458 'import sys,os;'
459 'sys.stderr.write("pineapple");'
460 'sys.stdout.write(sys.stdin.read())'],
461 stdin=subprocess.PIPE,
462 stdout=subprocess.PIPE,
463 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000464 self.addCleanup(p.stdout.close)
465 self.addCleanup(p.stderr.close)
466 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000467 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000468 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000469 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000470
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000471 # Test for the fd leak reported in http://bugs.python.org/issue2791.
472 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000473 for stdin_pipe in (False, True):
474 for stdout_pipe in (False, True):
475 for stderr_pipe in (False, True):
476 options = {}
477 if stdin_pipe:
478 options['stdin'] = subprocess.PIPE
479 if stdout_pipe:
480 options['stdout'] = subprocess.PIPE
481 if stderr_pipe:
482 options['stderr'] = subprocess.PIPE
483 if not options:
484 continue
485 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
486 p.communicate()
487 if p.stdin is not None:
488 self.assertTrue(p.stdin.closed)
489 if p.stdout is not None:
490 self.assertTrue(p.stdout.closed)
491 if p.stderr is not None:
492 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000493
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000494 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000495 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000496 p = subprocess.Popen([sys.executable, "-c",
497 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000498 (stdout, stderr) = p.communicate()
499 self.assertEqual(stdout, None)
500 self.assertEqual(stderr, None)
501
502 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000503 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000504 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000505 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000506 x, y = os.pipe()
507 if mswindows:
508 pipe_buf = 512
509 else:
510 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
511 os.close(x)
512 os.close(y)
513 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000514 'import sys,os;'
515 'sys.stdout.write(sys.stdin.read(47));'
516 'sys.stderr.write("xyz"*%d);'
517 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
518 stdin=subprocess.PIPE,
519 stdout=subprocess.PIPE,
520 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000521 self.addCleanup(p.stdout.close)
522 self.addCleanup(p.stderr.close)
523 self.addCleanup(p.stdin.close)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000524 string_to_write = b"abc"*pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000525 (stdout, stderr) = p.communicate(string_to_write)
526 self.assertEqual(stdout, string_to_write)
527
528 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000529 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000530 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000531 'import sys,os;'
532 'sys.stdout.write(sys.stdin.read())'],
533 stdin=subprocess.PIPE,
534 stdout=subprocess.PIPE,
535 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000536 self.addCleanup(p.stdout.close)
537 self.addCleanup(p.stderr.close)
538 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000539 p.stdin.write(b"banana")
540 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000541 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000542 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000543
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000544 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000545 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000546 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200547 'buf = sys.stdout.buffer;'
548 'buf.write(sys.stdin.readline().encode());'
549 'buf.flush();'
550 'buf.write(b"line2\\n");'
551 'buf.flush();'
552 'buf.write(sys.stdin.read().encode());'
553 'buf.flush();'
554 'buf.write(b"line4\\n");'
555 'buf.flush();'
556 'buf.write(b"line5\\r\\n");'
557 'buf.flush();'
558 'buf.write(b"line6\\r");'
559 'buf.flush();'
560 'buf.write(b"\\nline7");'
561 'buf.flush();'
562 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200563 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000564 stdout=subprocess.PIPE,
565 universal_newlines=1)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200566 p.stdin.write("line1\n")
567 self.assertEqual(p.stdout.readline(), "line1\n")
568 p.stdin.write("line3\n")
569 p.stdin.close()
Brian Curtin3c6a9512010-11-05 03:58:52 +0000570 self.addCleanup(p.stdout.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200571 self.assertEqual(p.stdout.readline(),
572 "line2\n")
573 self.assertEqual(p.stdout.read(6),
574 "line3\n")
575 self.assertEqual(p.stdout.read(),
576 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000577
578 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000579 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000580 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000581 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200582 'buf = sys.stdout.buffer;'
583 'buf.write(b"line2\\n");'
584 'buf.flush();'
585 'buf.write(b"line4\\n");'
586 'buf.flush();'
587 'buf.write(b"line5\\r\\n");'
588 'buf.flush();'
589 'buf.write(b"line6\\r");'
590 'buf.flush();'
591 'buf.write(b"\\nline7");'
592 'buf.flush();'
593 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200594 stderr=subprocess.PIPE,
595 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000596 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000597 self.addCleanup(p.stdout.close)
598 self.addCleanup(p.stderr.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200599 # BUG: can't give a non-empty stdin because it breaks both the
600 # select- and poll-based communicate() implementations.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000601 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200602 self.assertEqual(stdout,
603 "line2\nline4\nline5\nline6\nline7\nline8")
604
605 def test_universal_newlines_communicate_stdin(self):
606 # universal newlines through communicate(), with only stdin
607 p = subprocess.Popen([sys.executable, "-c",
608 'import sys,os;' + SETBINARY + '''\nif True:
609 s = sys.stdin.readline()
610 assert s == "line1\\n", repr(s)
611 s = sys.stdin.read()
612 assert s == "line3\\n", repr(s)
613 '''],
614 stdin=subprocess.PIPE,
615 universal_newlines=1)
616 (stdout, stderr) = p.communicate("line1\nline3\n")
617 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000618
Andrew Svetlovf3765072012-08-14 18:35:17 +0300619 def test_universal_newlines_communicate_input_none(self):
620 # Test communicate(input=None) with universal newlines.
621 #
622 # We set stdout to PIPE because, as of this writing, a different
623 # code path is tested when the number of pipes is zero or one.
624 p = subprocess.Popen([sys.executable, "-c", "pass"],
625 stdin=subprocess.PIPE,
626 stdout=subprocess.PIPE,
627 universal_newlines=True)
628 p.communicate()
629 self.assertEqual(p.returncode, 0)
630
Andrew Svetlov82860712012-08-19 22:13:41 +0300631 def test_universal_newlines_communicate_encodings(self):
632 # Check that universal newlines mode works for various encodings,
633 # in particular for encodings in the UTF-16 and UTF-32 families.
634 # See issue #15595.
635 #
636 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
637 # without, and UTF-16 and UTF-32.
638 for encoding in ['utf-16', 'utf-32-be']:
639 old_getpreferredencoding = locale.getpreferredencoding
640 # Indirectly via io.TextIOWrapper, Popen() defaults to
641 # locale.getpreferredencoding(False) and earlier in Python 3.2 to
642 # locale.getpreferredencoding().
643 def getpreferredencoding(do_setlocale=True):
644 return encoding
645 code = ("import sys; "
646 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
647 encoding)
648 args = [sys.executable, '-c', code]
649 try:
650 locale.getpreferredencoding = getpreferredencoding
651 # We set stdin to be non-None because, as of this writing,
652 # a different code path is used when the number of pipes is
653 # zero or one.
654 popen = subprocess.Popen(args, universal_newlines=True,
655 stdin=subprocess.PIPE,
656 stdout=subprocess.PIPE)
657 stdout, stderr = popen.communicate(input='')
658 finally:
659 locale.getpreferredencoding = old_getpreferredencoding
660
661 self.assertEqual(stdout, '1\n2\n3\n4')
662
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000663 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000664 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000665 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000666 max_handles = 1026 # too much for most UNIX systems
667 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000668 max_handles = 2050 # too much for (at least some) Windows setups
669 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400670 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000671 try:
672 for i in range(max_handles):
673 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400674 tmpfile = os.path.join(tmpdir, support.TESTFN)
675 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000676 except OSError as e:
677 if e.errno != errno.EMFILE:
678 raise
679 break
680 else:
681 self.skipTest("failed to reach the file descriptor limit "
682 "(tried %d)" % max_handles)
683 # Close a couple of them (should be enough for a subprocess)
684 for i in range(10):
685 os.close(handles.pop())
686 # Loop creating some subprocesses. If one of them leaks some fds,
687 # the next loop iteration will fail by reaching the max fd limit.
688 for i in range(15):
689 p = subprocess.Popen([sys.executable, "-c",
690 "import sys;"
691 "sys.stdout.write(sys.stdin.read())"],
692 stdin=subprocess.PIPE,
693 stdout=subprocess.PIPE,
694 stderr=subprocess.PIPE)
695 data = p.communicate(b"lime")[0]
696 self.assertEqual(data, b"lime")
697 finally:
698 for h in handles:
699 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400700 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000701
702 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000703 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
704 '"a b c" d e')
705 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
706 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000707 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
708 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000709 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
710 'a\\\\\\b "de fg" h')
711 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
712 'a\\\\\\"b c d')
713 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
714 '"a\\\\b c" d e')
715 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
716 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000717 self.assertEqual(subprocess.list2cmdline(['ab', '']),
718 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000719
720
721 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000722 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000723 "-c", "import time; time.sleep(1)"])
724 count = 0
725 while p.poll() is None:
726 time.sleep(0.1)
727 count += 1
728 # We expect that the poll loop probably went around about 10 times,
729 # but, based on system scheduling we can't control, it's possible
730 # poll() never returned None. It "should be" very rare that it
731 # didn't go around at least twice.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000732 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000733 # Subsequent invocations should just return the returncode
734 self.assertEqual(p.poll(), 0)
735
736
737 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000738 p = subprocess.Popen([sys.executable,
739 "-c", "import time; time.sleep(2)"])
740 self.assertEqual(p.wait(), 0)
741 # Subsequent invocations should just return the returncode
742 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000743
Peter Astrand738131d2004-11-30 21:04:45 +0000744
745 def test_invalid_bufsize(self):
746 # an invalid type of the bufsize argument should raise
747 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000748 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000749 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000750
Guido van Rossum46a05a72007-06-07 21:56:45 +0000751 def test_bufsize_is_none(self):
752 # bufsize=None should be the same as bufsize=0.
753 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
754 self.assertEqual(p.wait(), 0)
755 # Again with keyword arg
756 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
757 self.assertEqual(p.wait(), 0)
758
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000759 def test_leaking_fds_on_error(self):
760 # see bug #5179: Popen leaks file descriptors to PIPEs if
761 # the child fails to execute; this will eventually exhaust
762 # the maximum number of open fds. 1024 seems a very common
763 # value for that limit, but Windows has 2048, so we loop
764 # 1024 times (each call leaked two fds).
765 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000766 # Windows raises IOError. Others raise OSError.
767 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000768 subprocess.Popen(['nonexisting_i_hope'],
769 stdout=subprocess.PIPE,
770 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400771 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400772 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000773 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000774
Victor Stinnerb3693582010-05-21 20:13:12 +0000775 def test_issue8780(self):
776 # Ensure that stdout is inherited from the parent
777 # if stdout=PIPE is not used
778 code = ';'.join((
779 'import subprocess, sys',
780 'retcode = subprocess.call('
781 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
782 'assert retcode == 0'))
783 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000784 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000785
Tim Goldenaf5ac392010-08-06 13:03:56 +0000786 def test_handles_closed_on_exception(self):
787 # If CreateProcess exits with an error, ensure the
788 # duplicate output handles are released
789 ifhandle, ifname = mkstemp()
790 ofhandle, ofname = mkstemp()
791 efhandle, efname = mkstemp()
792 try:
793 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
794 stderr=efhandle)
795 except OSError:
796 os.close(ifhandle)
797 os.remove(ifname)
798 os.close(ofhandle)
799 os.remove(ofname)
800 os.close(efhandle)
801 os.remove(efname)
802 self.assertFalse(os.path.exists(ifname))
803 self.assertFalse(os.path.exists(ofname))
804 self.assertFalse(os.path.exists(efname))
805
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200806 def test_communicate_epipe(self):
807 # Issue 10963: communicate() should hide EPIPE
808 p = subprocess.Popen([sys.executable, "-c", 'pass'],
809 stdin=subprocess.PIPE,
810 stdout=subprocess.PIPE,
811 stderr=subprocess.PIPE)
812 self.addCleanup(p.stdout.close)
813 self.addCleanup(p.stderr.close)
814 self.addCleanup(p.stdin.close)
815 p.communicate(b"x" * 2**20)
816
817 def test_communicate_epipe_only_stdin(self):
818 # Issue 10963: communicate() should hide EPIPE
819 p = subprocess.Popen([sys.executable, "-c", 'pass'],
820 stdin=subprocess.PIPE)
821 self.addCleanup(p.stdin.close)
822 time.sleep(2)
823 p.communicate(b"x" * 2**20)
824
Victor Stinner1848db82011-07-05 14:49:46 +0200825 @unittest.skipUnless(hasattr(signal, 'SIGALRM'),
826 "Requires signal.SIGALRM")
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200827 def test_communicate_eintr(self):
828 # Issue #12493: communicate() should handle EINTR
829 def handler(signum, frame):
830 pass
831 old_handler = signal.signal(signal.SIGALRM, handler)
832 self.addCleanup(signal.signal, signal.SIGALRM, old_handler)
833
834 # the process is running for 2 seconds
835 args = [sys.executable, "-c", 'import time; time.sleep(2)']
836 for stream in ('stdout', 'stderr'):
837 kw = {stream: subprocess.PIPE}
838 with subprocess.Popen(args, **kw) as process:
839 signal.alarm(1)
840 # communicate() will be interrupted by SIGALRM
841 process.communicate()
842
Tim Peterse718f612004-10-12 21:51:32 +0000843
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000844# context manager
845class _SuppressCoreFiles(object):
846 """Try to prevent core files from being created."""
847 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000848
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000849 def __enter__(self):
850 """Try to save previous ulimit, then set it to (0, 0)."""
Benjamin Peterson964561b2011-12-10 12:31:42 -0500851 if resource is not None:
852 try:
853 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
854 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
855 except (ValueError, resource.error):
856 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000857
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000858 if sys.platform == 'darwin':
859 # Check if the 'Crash Reporter' on OSX was configured
860 # in 'Developer' mode and warn that it will get triggered
861 # when it is.
862 #
863 # This assumes that this context manager is used in tests
864 # that might trigger the next manager.
865 value = subprocess.Popen(['/usr/bin/defaults', 'read',
866 'com.apple.CrashReporter', 'DialogType'],
867 stdout=subprocess.PIPE).communicate()[0]
868 if value.strip() == b'developer':
869 print("this tests triggers the Crash Reporter, "
870 "that is intentional", end='')
871 sys.stdout.flush()
872
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000873 def __exit__(self, *args):
874 """Return core file behavior to default."""
875 if self.old_limit is None:
876 return
Benjamin Peterson964561b2011-12-10 12:31:42 -0500877 if resource is not None:
878 try:
879 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
880 except (ValueError, resource.error):
881 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000882
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000883
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000884@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000885class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000886
Gregory P. Smith5591b022012-10-10 03:34:47 -0700887 def setUp(self):
888 super().setUp()
889 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
890
891 def _get_chdir_exception(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000892 try:
Gregory P. Smith5591b022012-10-10 03:34:47 -0700893 os.chdir(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000894 except OSError as e:
895 # This avoids hard coding the errno value or the OS perror()
896 # string and instead capture the exception that we want to see
897 # below for comparison.
898 desired_exception = e
Gregory P. Smith5591b022012-10-10 03:34:47 -0700899 desired_exception.strerror += ': ' + repr(self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000900 else:
901 self.fail("chdir to nonexistant directory %s succeeded." %
Gregory P. Smith5591b022012-10-10 03:34:47 -0700902 self._nonexistent_dir)
903 return desired_exception
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000904
Gregory P. Smith5591b022012-10-10 03:34:47 -0700905 def test_exception_cwd(self):
906 """Test error in the child raised in the parent for a bad cwd."""
907 desired_exception = self._get_chdir_exception()
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000908 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000909 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smith5591b022012-10-10 03:34:47 -0700910 cwd=self._nonexistent_dir)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000911 except OSError as e:
912 # Test that the child process chdir failure actually makes
913 # it up to the parent process as the correct exception.
914 self.assertEqual(desired_exception.errno, e.errno)
915 self.assertEqual(desired_exception.strerror, e.strerror)
916 else:
917 self.fail("Expected OSError: %s" % desired_exception)
918
Gregory P. Smith5591b022012-10-10 03:34:47 -0700919 def test_exception_bad_executable(self):
920 """Test error in the child raised in the parent for a bad executable."""
921 desired_exception = self._get_chdir_exception()
922 try:
923 p = subprocess.Popen([sys.executable, "-c", ""],
924 executable=self._nonexistent_dir)
925 except OSError as e:
926 # Test that the child process exec failure actually makes
927 # it up to the parent process as the correct exception.
928 self.assertEqual(desired_exception.errno, e.errno)
929 self.assertEqual(desired_exception.strerror, e.strerror)
930 else:
931 self.fail("Expected OSError: %s" % desired_exception)
932
933 def test_exception_bad_args_0(self):
934 """Test error in the child raised in the parent for a bad args[0]."""
935 desired_exception = self._get_chdir_exception()
936 try:
937 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
938 except OSError as e:
939 # Test that the child process exec failure actually makes
940 # it up to the parent process as the correct exception.
941 self.assertEqual(desired_exception.errno, e.errno)
942 self.assertEqual(desired_exception.strerror, e.strerror)
943 else:
944 self.fail("Expected OSError: %s" % desired_exception)
945
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000946 def test_restore_signals(self):
947 # Code coverage for both values of restore_signals to make sure it
948 # at least does not blow up.
949 # A test for behavior would be complex. Contributions welcome.
950 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
951 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
952
953 def test_start_new_session(self):
954 # For code coverage of calling setsid(). We don't care if we get an
955 # EPERM error from it depending on the test execution environment, that
956 # still indicates that it was called.
957 try:
958 output = subprocess.check_output(
959 [sys.executable, "-c",
960 "import os; print(os.getpgid(os.getpid()))"],
961 start_new_session=True)
962 except OSError as e:
963 if e.errno != errno.EPERM:
964 raise
965 else:
966 parent_pgid = os.getpgid(os.getpid())
967 child_pgid = int(output)
968 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000969
970 def test_run_abort(self):
971 # returncode handles signal termination
972 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000973 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000974 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000975 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000976 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000977
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000978 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000979 # DISCLAIMER: Setting environment variables is *not* a good use
980 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000981 p = subprocess.Popen([sys.executable, "-c",
982 'import sys,os;'
983 'sys.stdout.write(os.getenv("FRUIT"))'],
984 stdout=subprocess.PIPE,
985 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000986 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000987 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000988
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000989 def test_preexec_exception(self):
990 def raise_it():
991 raise ValueError("What if two swallows carried a coconut?")
992 try:
993 p = subprocess.Popen([sys.executable, "-c", ""],
994 preexec_fn=raise_it)
995 except RuntimeError as e:
996 self.assertTrue(
997 subprocess._posixsubprocess,
998 "Expected a ValueError from the preexec_fn")
999 except ValueError as e:
1000 self.assertIn("coconut", e.args[0])
1001 else:
1002 self.fail("Exception raised by preexec_fn did not make it "
1003 "to the parent process.")
1004
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001005 def test_preexec_gc_module_failure(self):
1006 # This tests the code that disables garbage collection if the child
1007 # process will execute any Python.
1008 def raise_runtime_error():
1009 raise RuntimeError("this shouldn't escape")
1010 enabled = gc.isenabled()
1011 orig_gc_disable = gc.disable
1012 orig_gc_isenabled = gc.isenabled
1013 try:
1014 gc.disable()
1015 self.assertFalse(gc.isenabled())
1016 subprocess.call([sys.executable, '-c', ''],
1017 preexec_fn=lambda: None)
1018 self.assertFalse(gc.isenabled(),
1019 "Popen enabled gc when it shouldn't.")
1020
1021 gc.enable()
1022 self.assertTrue(gc.isenabled())
1023 subprocess.call([sys.executable, '-c', ''],
1024 preexec_fn=lambda: None)
1025 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1026
1027 gc.disable = raise_runtime_error
1028 self.assertRaises(RuntimeError, subprocess.Popen,
1029 [sys.executable, '-c', ''],
1030 preexec_fn=lambda: None)
1031
1032 del gc.isenabled # force an AttributeError
1033 self.assertRaises(AttributeError, subprocess.Popen,
1034 [sys.executable, '-c', ''],
1035 preexec_fn=lambda: None)
1036 finally:
1037 gc.disable = orig_gc_disable
1038 gc.isenabled = orig_gc_isenabled
1039 if not enabled:
1040 gc.disable()
1041
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001042 def test_args_string(self):
1043 # args is a string
1044 fd, fname = mkstemp()
1045 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001046 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001047 fobj.write("#!/bin/sh\n")
1048 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1049 sys.executable)
1050 os.chmod(fname, 0o700)
1051 p = subprocess.Popen(fname)
1052 p.wait()
1053 os.remove(fname)
1054 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001055
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001056 def test_invalid_args(self):
1057 # invalid arguments should raise ValueError
1058 self.assertRaises(ValueError, subprocess.call,
1059 [sys.executable, "-c",
1060 "import sys; sys.exit(47)"],
1061 startupinfo=47)
1062 self.assertRaises(ValueError, subprocess.call,
1063 [sys.executable, "-c",
1064 "import sys; sys.exit(47)"],
1065 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001066
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001067 def test_shell_sequence(self):
1068 # Run command through the shell (sequence)
1069 newenv = os.environ.copy()
1070 newenv["FRUIT"] = "apple"
1071 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1072 stdout=subprocess.PIPE,
1073 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001074 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001075 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001076
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001077 def test_shell_string(self):
1078 # Run command through the shell (string)
1079 newenv = os.environ.copy()
1080 newenv["FRUIT"] = "apple"
1081 p = subprocess.Popen("echo $FRUIT", shell=1,
1082 stdout=subprocess.PIPE,
1083 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001084 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001085 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001086
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001087 def test_call_string(self):
1088 # call() function with string argument on UNIX
1089 fd, fname = mkstemp()
1090 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001091 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001092 fobj.write("#!/bin/sh\n")
1093 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1094 sys.executable)
1095 os.chmod(fname, 0o700)
1096 rc = subprocess.call(fname)
1097 os.remove(fname)
1098 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001099
Stefan Krah9542cc62010-07-19 14:20:53 +00001100 def test_specific_shell(self):
1101 # Issue #9265: Incorrect name passed as arg[0].
1102 shells = []
1103 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1104 for name in ['bash', 'ksh']:
1105 sh = os.path.join(prefix, name)
1106 if os.path.isfile(sh):
1107 shells.append(sh)
1108 if not shells: # Will probably work for any shell but csh.
1109 self.skipTest("bash or ksh required for this test")
1110 sh = '/bin/sh'
1111 if os.path.isfile(sh) and not os.path.islink(sh):
1112 # Test will fail if /bin/sh is a symlink to csh.
1113 shells.append(sh)
1114 for sh in shells:
1115 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1116 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001117 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001118 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1119
Florent Xicluna4886d242010-03-08 13:27:26 +00001120 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001121 # Do not inherit file handles from the parent.
1122 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001123 p = subprocess.Popen([sys.executable, "-c", """if 1:
1124 import sys, time
1125 sys.stdout.write('x\\n')
1126 sys.stdout.flush()
1127 time.sleep(30)
1128 """],
1129 close_fds=True,
1130 stdin=subprocess.PIPE,
1131 stdout=subprocess.PIPE,
1132 stderr=subprocess.PIPE)
1133 # Wait for the interpreter to be completely initialized before
1134 # sending any signal.
1135 p.stdout.read(1)
1136 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001137 return p
1138
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001139 def _kill_dead_process(self, method, *args):
1140 # Do not inherit file handles from the parent.
1141 # It should fix failures on some platforms.
1142 p = subprocess.Popen([sys.executable, "-c", """if 1:
1143 import sys, time
1144 sys.stdout.write('x\\n')
1145 sys.stdout.flush()
1146 """],
1147 close_fds=True,
1148 stdin=subprocess.PIPE,
1149 stdout=subprocess.PIPE,
1150 stderr=subprocess.PIPE)
1151 # Wait for the interpreter to be completely initialized before
1152 # sending any signal.
1153 p.stdout.read(1)
1154 # The process should end after this
1155 time.sleep(1)
1156 # This shouldn't raise even though the child is now dead
1157 getattr(p, method)(*args)
1158 p.communicate()
1159
Florent Xicluna4886d242010-03-08 13:27:26 +00001160 def test_send_signal(self):
1161 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001162 _, stderr = p.communicate()
1163 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001164 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001165
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001166 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001167 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001168 _, stderr = p.communicate()
1169 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001170 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001171
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001172 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001173 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001174 _, stderr = p.communicate()
1175 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001176 self.assertEqual(p.wait(), -signal.SIGTERM)
1177
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001178 def test_send_signal_dead(self):
1179 # Sending a signal to a dead process
1180 self._kill_dead_process('send_signal', signal.SIGINT)
1181
1182 def test_kill_dead(self):
1183 # Killing a dead process
1184 self._kill_dead_process('kill')
1185
1186 def test_terminate_dead(self):
1187 # Terminating a dead process
1188 self._kill_dead_process('terminate')
1189
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001190 def check_close_std_fds(self, fds):
1191 # Issue #9905: test that subprocess pipes still work properly with
1192 # some standard fds closed
1193 stdin = 0
1194 newfds = []
1195 for a in fds:
1196 b = os.dup(a)
1197 newfds.append(b)
1198 if a == 0:
1199 stdin = b
1200 try:
1201 for fd in fds:
1202 os.close(fd)
1203 out, err = subprocess.Popen([sys.executable, "-c",
1204 'import sys;'
1205 'sys.stdout.write("apple");'
1206 'sys.stdout.flush();'
1207 'sys.stderr.write("orange")'],
1208 stdin=stdin,
1209 stdout=subprocess.PIPE,
1210 stderr=subprocess.PIPE).communicate()
1211 err = support.strip_python_stderr(err)
1212 self.assertEqual((out, err), (b'apple', b'orange'))
1213 finally:
1214 for b, a in zip(newfds, fds):
1215 os.dup2(b, a)
1216 for b in newfds:
1217 os.close(b)
1218
1219 def test_close_fd_0(self):
1220 self.check_close_std_fds([0])
1221
1222 def test_close_fd_1(self):
1223 self.check_close_std_fds([1])
1224
1225 def test_close_fd_2(self):
1226 self.check_close_std_fds([2])
1227
1228 def test_close_fds_0_1(self):
1229 self.check_close_std_fds([0, 1])
1230
1231 def test_close_fds_0_2(self):
1232 self.check_close_std_fds([0, 2])
1233
1234 def test_close_fds_1_2(self):
1235 self.check_close_std_fds([1, 2])
1236
1237 def test_close_fds_0_1_2(self):
1238 # Issue #10806: test that subprocess pipes still work properly with
1239 # all standard fds closed.
1240 self.check_close_std_fds([0, 1, 2])
1241
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001242 def test_remapping_std_fds(self):
1243 # open up some temporary files
1244 temps = [mkstemp() for i in range(3)]
1245 try:
1246 temp_fds = [fd for fd, fname in temps]
1247
1248 # unlink the files -- we won't need to reopen them
1249 for fd, fname in temps:
1250 os.unlink(fname)
1251
1252 # write some data to what will become stdin, and rewind
1253 os.write(temp_fds[1], b"STDIN")
1254 os.lseek(temp_fds[1], 0, 0)
1255
1256 # move the standard file descriptors out of the way
1257 saved_fds = [os.dup(fd) for fd in range(3)]
1258 try:
1259 # duplicate the file objects over the standard fd's
1260 for fd, temp_fd in enumerate(temp_fds):
1261 os.dup2(temp_fd, fd)
1262
1263 # now use those files in the "wrong" order, so that subprocess
1264 # has to rearrange them in the child
1265 p = subprocess.Popen([sys.executable, "-c",
1266 'import sys; got = sys.stdin.read();'
1267 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1268 stdin=temp_fds[1],
1269 stdout=temp_fds[2],
1270 stderr=temp_fds[0])
1271 p.wait()
1272 finally:
1273 # restore the original fd's underneath sys.stdin, etc.
1274 for std, saved in enumerate(saved_fds):
1275 os.dup2(saved, std)
1276 os.close(saved)
1277
1278 for fd in temp_fds:
1279 os.lseek(fd, 0, 0)
1280
1281 out = os.read(temp_fds[2], 1024)
1282 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1283 self.assertEqual(out, b"got STDIN")
1284 self.assertEqual(err, b"err")
1285
1286 finally:
1287 for fd in temp_fds:
1288 os.close(fd)
1289
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001290 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1291 # open up some temporary files
1292 temps = [mkstemp() for i in range(3)]
1293 temp_fds = [fd for fd, fname in temps]
1294 try:
1295 # unlink the files -- we won't need to reopen them
1296 for fd, fname in temps:
1297 os.unlink(fname)
1298
1299 # save a copy of the standard file descriptors
1300 saved_fds = [os.dup(fd) for fd in range(3)]
1301 try:
1302 # duplicate the temp files over the standard fd's 0, 1, 2
1303 for fd, temp_fd in enumerate(temp_fds):
1304 os.dup2(temp_fd, fd)
1305
1306 # write some data to what will become stdin, and rewind
1307 os.write(stdin_no, b"STDIN")
1308 os.lseek(stdin_no, 0, 0)
1309
1310 # now use those files in the given order, so that subprocess
1311 # has to rearrange them in the child
1312 p = subprocess.Popen([sys.executable, "-c",
1313 'import sys; got = sys.stdin.read();'
1314 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1315 stdin=stdin_no,
1316 stdout=stdout_no,
1317 stderr=stderr_no)
1318 p.wait()
1319
1320 for fd in temp_fds:
1321 os.lseek(fd, 0, 0)
1322
1323 out = os.read(stdout_no, 1024)
1324 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1325 finally:
1326 for std, saved in enumerate(saved_fds):
1327 os.dup2(saved, std)
1328 os.close(saved)
1329
1330 self.assertEqual(out, b"got STDIN")
1331 self.assertEqual(err, b"err")
1332
1333 finally:
1334 for fd in temp_fds:
1335 os.close(fd)
1336
1337 # When duping fds, if there arises a situation where one of the fds is
1338 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1339 # This tests all combinations of this.
1340 def test_swap_fds(self):
1341 self.check_swap_fds(0, 1, 2)
1342 self.check_swap_fds(0, 2, 1)
1343 self.check_swap_fds(1, 0, 2)
1344 self.check_swap_fds(1, 2, 0)
1345 self.check_swap_fds(2, 0, 1)
1346 self.check_swap_fds(2, 1, 0)
1347
Victor Stinner13bb71c2010-04-23 21:41:56 +00001348 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001349 def prepare():
1350 raise ValueError("surrogate:\uDCff")
1351
1352 try:
1353 subprocess.call(
1354 [sys.executable, "-c", "pass"],
1355 preexec_fn=prepare)
1356 except ValueError as err:
1357 # Pure Python implementations keeps the message
1358 self.assertIsNone(subprocess._posixsubprocess)
1359 self.assertEqual(str(err), "surrogate:\uDCff")
1360 except RuntimeError as err:
1361 # _posixsubprocess uses a default message
1362 self.assertIsNotNone(subprocess._posixsubprocess)
1363 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1364 else:
1365 self.fail("Expected ValueError or RuntimeError")
1366
Victor Stinner13bb71c2010-04-23 21:41:56 +00001367 def test_undecodable_env(self):
1368 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001369 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001370 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001371 env = os.environ.copy()
1372 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001373 # Use C locale to get ascii for the locale encoding to force
1374 # surrogate-escaping of \xFF in the child process; otherwise it can
1375 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001376 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001377 stdout = subprocess.check_output(
1378 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001379 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001380 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001381 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001382
1383 # test bytes
1384 key = key.encode("ascii", "surrogateescape")
1385 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001386 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001387 env = os.environ.copy()
1388 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001389 stdout = subprocess.check_output(
1390 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001391 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001392 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001393 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001394
Victor Stinnerb745a742010-05-18 17:17:23 +00001395 def test_bytes_program(self):
1396 abs_program = os.fsencode(sys.executable)
1397 path, program = os.path.split(sys.executable)
1398 program = os.fsencode(program)
1399
1400 # absolute bytes path
1401 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001402 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001403
1404 # bytes program, unicode PATH
1405 env = os.environ.copy()
1406 env["PATH"] = path
1407 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001408 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001409
1410 # bytes program, bytes PATH
1411 envb = os.environb.copy()
1412 envb[b"PATH"] = os.fsencode(path)
1413 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001414 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001415
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001416 def test_pipe_cloexec(self):
1417 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1418 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1419
1420 p1 = subprocess.Popen([sys.executable, sleeper],
1421 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1422 stderr=subprocess.PIPE, close_fds=False)
1423
1424 self.addCleanup(p1.communicate, b'')
1425
1426 p2 = subprocess.Popen([sys.executable, fd_status],
1427 stdout=subprocess.PIPE, close_fds=False)
1428
1429 output, error = p2.communicate()
1430 result_fds = set(map(int, output.split(b',')))
1431 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1432 p1.stderr.fileno()])
1433
1434 self.assertFalse(result_fds & unwanted_fds,
1435 "Expected no fds from %r to be open in child, "
1436 "found %r" %
1437 (unwanted_fds, result_fds & unwanted_fds))
1438
1439 def test_pipe_cloexec_real_tools(self):
1440 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1441 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1442
1443 subdata = b'zxcvbn'
1444 data = subdata * 4 + b'\n'
1445
1446 p1 = subprocess.Popen([sys.executable, qcat],
1447 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1448 close_fds=False)
1449
1450 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1451 stdin=p1.stdout, stdout=subprocess.PIPE,
1452 close_fds=False)
1453
1454 self.addCleanup(p1.wait)
1455 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001456 def kill_p1():
1457 try:
1458 p1.terminate()
1459 except ProcessLookupError:
1460 pass
1461 def kill_p2():
1462 try:
1463 p2.terminate()
1464 except ProcessLookupError:
1465 pass
1466 self.addCleanup(kill_p1)
1467 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001468
1469 p1.stdin.write(data)
1470 p1.stdin.close()
1471
1472 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1473
1474 self.assertTrue(readfiles, "The child hung")
1475 self.assertEqual(p2.stdout.read(), data)
1476
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001477 p1.stdout.close()
1478 p2.stdout.close()
1479
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001480 def test_close_fds(self):
1481 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1482
1483 fds = os.pipe()
1484 self.addCleanup(os.close, fds[0])
1485 self.addCleanup(os.close, fds[1])
1486
1487 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001488 # add a bunch more fds
1489 for _ in range(9):
1490 fd = os.open("/dev/null", os.O_RDONLY)
1491 self.addCleanup(os.close, fd)
1492 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001493
1494 p = subprocess.Popen([sys.executable, fd_status],
1495 stdout=subprocess.PIPE, close_fds=False)
1496 output, ignored = p.communicate()
1497 remaining_fds = set(map(int, output.split(b',')))
1498
1499 self.assertEqual(remaining_fds & open_fds, open_fds,
1500 "Some fds were closed")
1501
1502 p = subprocess.Popen([sys.executable, fd_status],
1503 stdout=subprocess.PIPE, close_fds=True)
1504 output, ignored = p.communicate()
1505 remaining_fds = set(map(int, output.split(b',')))
1506
1507 self.assertFalse(remaining_fds & open_fds,
1508 "Some fds were left open")
1509 self.assertIn(1, remaining_fds, "Subprocess failed")
1510
Gregory P. Smith8facece2012-01-21 14:01:08 -08001511 # Keep some of the fd's we opened open in the subprocess.
1512 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1513 fds_to_keep = set(open_fds.pop() for _ in range(8))
1514 p = subprocess.Popen([sys.executable, fd_status],
1515 stdout=subprocess.PIPE, close_fds=True,
1516 pass_fds=())
1517 output, ignored = p.communicate()
1518 remaining_fds = set(map(int, output.split(b',')))
1519
1520 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1521 "Some fds not in pass_fds were left open")
1522 self.assertIn(1, remaining_fds, "Subprocess failed")
1523
Victor Stinner88701e22011-06-01 13:13:04 +02001524 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1525 # descriptor of a pipe closed in the parent process is valid in the
1526 # child process according to fstat(), but the mode of the file
1527 # descriptor is invalid, and read or write raise an error.
1528 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001529 def test_pass_fds(self):
1530 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1531
1532 open_fds = set()
1533
1534 for x in range(5):
1535 fds = os.pipe()
1536 self.addCleanup(os.close, fds[0])
1537 self.addCleanup(os.close, fds[1])
1538 open_fds.update(fds)
1539
1540 for fd in open_fds:
1541 p = subprocess.Popen([sys.executable, fd_status],
1542 stdout=subprocess.PIPE, close_fds=True,
1543 pass_fds=(fd, ))
1544 output, ignored = p.communicate()
1545
1546 remaining_fds = set(map(int, output.split(b',')))
1547 to_be_closed = open_fds - {fd}
1548
1549 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1550 self.assertFalse(remaining_fds & to_be_closed,
1551 "fd to be closed passed")
1552
1553 # pass_fds overrides close_fds with a warning.
1554 with self.assertWarns(RuntimeWarning) as context:
1555 self.assertFalse(subprocess.call(
1556 [sys.executable, "-c", "import sys; sys.exit(0)"],
1557 close_fds=False, pass_fds=(fd, )))
1558 self.assertIn('overriding close_fds', str(context.warning))
1559
Gregory P. Smithe14e9c22011-03-15 14:55:17 -04001560 def test_stdout_stdin_are_single_inout_fd(self):
1561 with io.open(os.devnull, "r+") as inout:
1562 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1563 stdout=inout, stdin=inout)
1564 p.wait()
1565
1566 def test_stdout_stderr_are_single_inout_fd(self):
1567 with io.open(os.devnull, "r+") as inout:
1568 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1569 stdout=inout, stderr=inout)
1570 p.wait()
1571
1572 def test_stderr_stdin_are_single_inout_fd(self):
1573 with io.open(os.devnull, "r+") as inout:
1574 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1575 stderr=inout, stdin=inout)
1576 p.wait()
1577
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001578 def test_wait_when_sigchild_ignored(self):
1579 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1580 sigchild_ignore = support.findfile("sigchild_ignore.py",
1581 subdir="subprocessdata")
1582 p = subprocess.Popen([sys.executable, sigchild_ignore],
1583 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1584 stdout, stderr = p.communicate()
1585 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001586 " non-zero with this error:\n%s" %
1587 stderr.decode('utf8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001588
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001589 def test_select_unbuffered(self):
1590 # Issue #11459: bufsize=0 should really set the pipes as
1591 # unbuffered (and therefore let select() work properly).
1592 select = support.import_module("select")
1593 p = subprocess.Popen([sys.executable, "-c",
1594 'import sys;'
1595 'sys.stdout.write("apple")'],
1596 stdout=subprocess.PIPE,
1597 bufsize=0)
1598 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001599 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001600 try:
1601 self.assertEqual(f.read(4), b"appl")
1602 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1603 finally:
1604 p.wait()
1605
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001606 def test_zombie_fast_process_del(self):
1607 # Issue #12650: on Unix, if Popen.__del__() was called before the
1608 # process exited, it wouldn't be added to subprocess._active, and would
1609 # remain a zombie.
1610 # spawn a Popen, and delete its reference before it exits
1611 p = subprocess.Popen([sys.executable, "-c",
1612 'import sys, time;'
1613 'time.sleep(0.2)'],
1614 stdout=subprocess.PIPE,
1615 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001616 self.addCleanup(p.stdout.close)
1617 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001618 ident = id(p)
1619 pid = p.pid
1620 del p
1621 # check that p is in the active processes list
1622 self.assertIn(ident, [id(o) for o in subprocess._active])
1623
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001624 def test_leak_fast_process_del_killed(self):
1625 # Issue #12650: on Unix, if Popen.__del__() was called before the
1626 # process exited, and the process got killed by a signal, it would never
1627 # be removed from subprocess._active, which triggered a FD and memory
1628 # leak.
1629 # spawn a Popen, delete its reference and kill it
1630 p = subprocess.Popen([sys.executable, "-c",
1631 'import time;'
1632 'time.sleep(3)'],
1633 stdout=subprocess.PIPE,
1634 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001635 self.addCleanup(p.stdout.close)
1636 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001637 ident = id(p)
1638 pid = p.pid
1639 del p
1640 os.kill(pid, signal.SIGKILL)
1641 # check that p is in the active processes list
1642 self.assertIn(ident, [id(o) for o in subprocess._active])
1643
1644 # let some time for the process to exit, and create a new Popen: this
1645 # should trigger the wait() of p
1646 time.sleep(0.2)
1647 with self.assertRaises(EnvironmentError) as c:
1648 with subprocess.Popen(['nonexisting_i_hope'],
1649 stdout=subprocess.PIPE,
1650 stderr=subprocess.PIPE) as proc:
1651 pass
1652 # p should have been wait()ed on, and removed from the _active list
1653 self.assertRaises(OSError, os.waitpid, pid, 0)
1654 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1655
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001656
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001657@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001658class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001659
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001660 def test_startupinfo(self):
1661 # startupinfo argument
1662 # We uses hardcoded constants, because we do not want to
1663 # depend on win32all.
1664 STARTF_USESHOWWINDOW = 1
1665 SW_MAXIMIZE = 3
1666 startupinfo = subprocess.STARTUPINFO()
1667 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1668 startupinfo.wShowWindow = SW_MAXIMIZE
1669 # Since Python is a console process, it won't be affected
1670 # by wShowWindow, but the argument should be silently
1671 # ignored
1672 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001673 startupinfo=startupinfo)
1674
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001675 def test_creationflags(self):
1676 # creationflags argument
1677 CREATE_NEW_CONSOLE = 16
1678 sys.stderr.write(" a DOS box should flash briefly ...\n")
1679 subprocess.call(sys.executable +
1680 ' -c "import time; time.sleep(0.25)"',
1681 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001682
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001683 def test_invalid_args(self):
1684 # invalid arguments should raise ValueError
1685 self.assertRaises(ValueError, subprocess.call,
1686 [sys.executable, "-c",
1687 "import sys; sys.exit(47)"],
1688 preexec_fn=lambda: 1)
1689 self.assertRaises(ValueError, subprocess.call,
1690 [sys.executable, "-c",
1691 "import sys; sys.exit(47)"],
1692 stdout=subprocess.PIPE,
1693 close_fds=True)
1694
1695 def test_close_fds(self):
1696 # close file descriptors
1697 rc = subprocess.call([sys.executable, "-c",
1698 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001699 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001700 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001701
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001702 def test_shell_sequence(self):
1703 # Run command through the shell (sequence)
1704 newenv = os.environ.copy()
1705 newenv["FRUIT"] = "physalis"
1706 p = subprocess.Popen(["set"], shell=1,
1707 stdout=subprocess.PIPE,
1708 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001709 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001710 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001711
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001712 def test_shell_string(self):
1713 # Run command through the shell (string)
1714 newenv = os.environ.copy()
1715 newenv["FRUIT"] = "physalis"
1716 p = subprocess.Popen("set", shell=1,
1717 stdout=subprocess.PIPE,
1718 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001719 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001720 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001721
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001722 def test_call_string(self):
1723 # call() function with string argument on Windows
1724 rc = subprocess.call(sys.executable +
1725 ' -c "import sys; sys.exit(47)"')
1726 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001727
Florent Xicluna4886d242010-03-08 13:27:26 +00001728 def _kill_process(self, method, *args):
1729 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001730 p = subprocess.Popen([sys.executable, "-c", """if 1:
1731 import sys, time
1732 sys.stdout.write('x\\n')
1733 sys.stdout.flush()
1734 time.sleep(30)
1735 """],
1736 stdin=subprocess.PIPE,
1737 stdout=subprocess.PIPE,
1738 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001739 self.addCleanup(p.stdout.close)
1740 self.addCleanup(p.stderr.close)
1741 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001742 # Wait for the interpreter to be completely initialized before
1743 # sending any signal.
1744 p.stdout.read(1)
1745 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001746 _, stderr = p.communicate()
1747 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001748 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001749 self.assertNotEqual(returncode, 0)
1750
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001751 def _kill_dead_process(self, method, *args):
1752 p = subprocess.Popen([sys.executable, "-c", """if 1:
1753 import sys, time
1754 sys.stdout.write('x\\n')
1755 sys.stdout.flush()
1756 sys.exit(42)
1757 """],
1758 stdin=subprocess.PIPE,
1759 stdout=subprocess.PIPE,
1760 stderr=subprocess.PIPE)
1761 self.addCleanup(p.stdout.close)
1762 self.addCleanup(p.stderr.close)
1763 self.addCleanup(p.stdin.close)
1764 # Wait for the interpreter to be completely initialized before
1765 # sending any signal.
1766 p.stdout.read(1)
1767 # The process should end after this
1768 time.sleep(1)
1769 # This shouldn't raise even though the child is now dead
1770 getattr(p, method)(*args)
1771 _, stderr = p.communicate()
1772 self.assertStderrEqual(stderr, b'')
1773 rc = p.wait()
1774 self.assertEqual(rc, 42)
1775
Florent Xicluna4886d242010-03-08 13:27:26 +00001776 def test_send_signal(self):
1777 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001778
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001779 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001780 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001781
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001782 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001783 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001784
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001785 def test_send_signal_dead(self):
1786 self._kill_dead_process('send_signal', signal.SIGTERM)
1787
1788 def test_kill_dead(self):
1789 self._kill_dead_process('kill')
1790
1791 def test_terminate_dead(self):
1792 self._kill_dead_process('terminate')
1793
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001794
Brett Cannona23810f2008-05-26 19:04:21 +00001795# The module says:
1796# "NB This only works (and is only relevant) for UNIX."
1797#
1798# Actually, getoutput should work on any platform with an os.popen, but
1799# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001800@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001801class CommandTests(unittest.TestCase):
1802 def test_getoutput(self):
1803 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1804 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1805 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001806
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001807 # we use mkdtemp in the next line to create an empty directory
1808 # under our exclusive control; from that, we can invent a pathname
1809 # that we _know_ won't exist. This is guaranteed to fail.
1810 dir = None
1811 try:
1812 dir = tempfile.mkdtemp()
1813 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001814
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001815 status, output = subprocess.getstatusoutput('cat ' + name)
1816 self.assertNotEqual(status, 0)
1817 finally:
1818 if dir is not None:
1819 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001820
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001821
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001822@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1823 "poll system call not supported")
1824class ProcessTestCaseNoPoll(ProcessTestCase):
1825 def setUp(self):
1826 subprocess._has_poll = False
1827 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001828
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001829 def tearDown(self):
1830 subprocess._has_poll = True
1831 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001832
1833
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001834@unittest.skipUnless(getattr(subprocess, '_posixsubprocess', False),
1835 "_posixsubprocess extension module not found.")
1836class ProcessTestCasePOSIXPurePython(ProcessTestCase, POSIXProcessTestCase):
Gregory P. Smith7439e7b2011-05-28 09:06:02 -07001837 @classmethod
1838 def setUpClass(cls):
1839 global subprocess
1840 assert subprocess._posixsubprocess
1841 # Reimport subprocess while forcing _posixsubprocess to not exist.
1842 with support.check_warnings(('.*_posixsubprocess .* not being used.*',
1843 RuntimeWarning)):
1844 subprocess = support.import_fresh_module(
1845 'subprocess', blocked=['_posixsubprocess'])
1846 assert not subprocess._posixsubprocess
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001847
Gregory P. Smith7439e7b2011-05-28 09:06:02 -07001848 @classmethod
1849 def tearDownClass(cls):
1850 global subprocess
1851 # Reimport subprocess as it should be, restoring order to the universe.
1852 subprocess = support.import_fresh_module('subprocess')
1853 assert subprocess._posixsubprocess
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001854
1855
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001856class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001857 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001858 def test_eintr_retry_call(self):
1859 record_calls = []
1860 def fake_os_func(*args):
1861 record_calls.append(args)
1862 if len(record_calls) == 2:
1863 raise OSError(errno.EINTR, "fake interrupted system call")
1864 return tuple(reversed(args))
1865
1866 self.assertEqual((999, 256),
1867 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1868 self.assertEqual([(256, 999)], record_calls)
1869 # This time there will be an EINTR so it will loop once.
1870 self.assertEqual((666,),
1871 subprocess._eintr_retry_call(fake_os_func, 666))
1872 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1873
1874
Tim Golden126c2962010-08-11 14:20:40 +00001875@unittest.skipUnless(mswindows, "Windows-specific tests")
1876class CommandsWithSpaces (BaseTestCase):
1877
1878 def setUp(self):
1879 super().setUp()
1880 f, fname = mkstemp(".py", "te st")
1881 self.fname = fname.lower ()
1882 os.write(f, b"import sys;"
1883 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1884 )
1885 os.close(f)
1886
1887 def tearDown(self):
1888 os.remove(self.fname)
1889 super().tearDown()
1890
1891 def with_spaces(self, *args, **kwargs):
1892 kwargs['stdout'] = subprocess.PIPE
1893 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001894 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001895 self.assertEqual(
1896 p.stdout.read ().decode("mbcs"),
1897 "2 [%r, 'ab cd']" % self.fname
1898 )
1899
1900 def test_shell_string_with_spaces(self):
1901 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001902 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1903 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001904
1905 def test_shell_sequence_with_spaces(self):
1906 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001907 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001908
1909 def test_noshell_string_with_spaces(self):
1910 # call() function with string argument with spaces on Windows
1911 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1912 "ab cd"))
1913
1914 def test_noshell_sequence_with_spaces(self):
1915 # call() function with sequence argument with spaces on Windows
1916 self.with_spaces([sys.executable, self.fname, "ab cd"])
1917
Brian Curtin79cdb662010-12-03 02:46:02 +00001918
Georg Brandla86b2622012-02-20 21:34:57 +01001919class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00001920
1921 def test_pipe(self):
1922 with subprocess.Popen([sys.executable, "-c",
1923 "import sys;"
1924 "sys.stdout.write('stdout');"
1925 "sys.stderr.write('stderr');"],
1926 stdout=subprocess.PIPE,
1927 stderr=subprocess.PIPE) as proc:
1928 self.assertEqual(proc.stdout.read(), b"stdout")
1929 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1930
1931 self.assertTrue(proc.stdout.closed)
1932 self.assertTrue(proc.stderr.closed)
1933
1934 def test_returncode(self):
1935 with subprocess.Popen([sys.executable, "-c",
1936 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smithc9557af2011-05-11 22:18:23 -07001937 pass
1938 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00001939 self.assertEqual(proc.returncode, 100)
1940
1941 def test_communicate_stdin(self):
1942 with subprocess.Popen([sys.executable, "-c",
1943 "import sys;"
1944 "sys.exit(sys.stdin.read() == 'context')"],
1945 stdin=subprocess.PIPE) as proc:
1946 proc.communicate(b"context")
1947 self.assertEqual(proc.returncode, 1)
1948
1949 def test_invalid_args(self):
1950 with self.assertRaises(EnvironmentError) as c:
1951 with subprocess.Popen(['nonexisting_i_hope'],
1952 stdout=subprocess.PIPE,
1953 stderr=subprocess.PIPE) as proc:
1954 pass
1955
1956 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1957 raise c.exception
1958
1959
Gregory P. Smith961e0e82011-03-15 15:43:39 -04001960def test_main():
1961 unit_tests = (ProcessTestCase,
1962 POSIXProcessTestCase,
1963 Win32ProcessTestCase,
1964 ProcessTestCasePOSIXPurePython,
1965 CommandTests,
1966 ProcessTestCaseNoPoll,
1967 HelperFunctionTests,
1968 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02001969 ContextManagerTests,
1970 )
Gregory P. Smith961e0e82011-03-15 15:43:39 -04001971
1972 support.run_unittest(*unit_tests)
1973 support.reap_children()
1974
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001975if __name__ == "__main__":
Gregory P. Smithe14e9c22011-03-15 14:55:17 -04001976 unittest.main()