blob: 287964111068a527cae3637eeca4945c025eb6b7 [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
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000887 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000888 nonexistent_dir = "/_this/pa.th/does/not/exist"
889 try:
890 os.chdir(nonexistent_dir)
891 except OSError as e:
892 # This avoids hard coding the errno value or the OS perror()
893 # string and instead capture the exception that we want to see
894 # below for comparison.
895 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000896 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000897 else:
898 self.fail("chdir to nonexistant directory %s succeeded." %
899 nonexistent_dir)
900
901 # Error in the child re-raised in the parent.
902 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000903 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000904 cwd=nonexistent_dir)
905 except OSError as e:
906 # Test that the child process chdir failure actually makes
907 # it up to the parent process as the correct exception.
908 self.assertEqual(desired_exception.errno, e.errno)
909 self.assertEqual(desired_exception.strerror, e.strerror)
910 else:
911 self.fail("Expected OSError: %s" % desired_exception)
912
913 def test_restore_signals(self):
914 # Code coverage for both values of restore_signals to make sure it
915 # at least does not blow up.
916 # A test for behavior would be complex. Contributions welcome.
917 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
918 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
919
920 def test_start_new_session(self):
921 # For code coverage of calling setsid(). We don't care if we get an
922 # EPERM error from it depending on the test execution environment, that
923 # still indicates that it was called.
924 try:
925 output = subprocess.check_output(
926 [sys.executable, "-c",
927 "import os; print(os.getpgid(os.getpid()))"],
928 start_new_session=True)
929 except OSError as e:
930 if e.errno != errno.EPERM:
931 raise
932 else:
933 parent_pgid = os.getpgid(os.getpid())
934 child_pgid = int(output)
935 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000936
937 def test_run_abort(self):
938 # returncode handles signal termination
939 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000940 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000941 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000942 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000943 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000944
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000945 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000946 # DISCLAIMER: Setting environment variables is *not* a good use
947 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000948 p = subprocess.Popen([sys.executable, "-c",
949 'import sys,os;'
950 'sys.stdout.write(os.getenv("FRUIT"))'],
951 stdout=subprocess.PIPE,
952 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000953 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000954 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000955
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000956 def test_preexec_exception(self):
957 def raise_it():
958 raise ValueError("What if two swallows carried a coconut?")
959 try:
960 p = subprocess.Popen([sys.executable, "-c", ""],
961 preexec_fn=raise_it)
962 except RuntimeError as e:
963 self.assertTrue(
964 subprocess._posixsubprocess,
965 "Expected a ValueError from the preexec_fn")
966 except ValueError as e:
967 self.assertIn("coconut", e.args[0])
968 else:
969 self.fail("Exception raised by preexec_fn did not make it "
970 "to the parent process.")
971
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000972 def test_preexec_gc_module_failure(self):
973 # This tests the code that disables garbage collection if the child
974 # process will execute any Python.
975 def raise_runtime_error():
976 raise RuntimeError("this shouldn't escape")
977 enabled = gc.isenabled()
978 orig_gc_disable = gc.disable
979 orig_gc_isenabled = gc.isenabled
980 try:
981 gc.disable()
982 self.assertFalse(gc.isenabled())
983 subprocess.call([sys.executable, '-c', ''],
984 preexec_fn=lambda: None)
985 self.assertFalse(gc.isenabled(),
986 "Popen enabled gc when it shouldn't.")
987
988 gc.enable()
989 self.assertTrue(gc.isenabled())
990 subprocess.call([sys.executable, '-c', ''],
991 preexec_fn=lambda: None)
992 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
993
994 gc.disable = raise_runtime_error
995 self.assertRaises(RuntimeError, subprocess.Popen,
996 [sys.executable, '-c', ''],
997 preexec_fn=lambda: None)
998
999 del gc.isenabled # force an AttributeError
1000 self.assertRaises(AttributeError, subprocess.Popen,
1001 [sys.executable, '-c', ''],
1002 preexec_fn=lambda: None)
1003 finally:
1004 gc.disable = orig_gc_disable
1005 gc.isenabled = orig_gc_isenabled
1006 if not enabled:
1007 gc.disable()
1008
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001009 def test_args_string(self):
1010 # args is a string
1011 fd, fname = mkstemp()
1012 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001013 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001014 fobj.write("#!/bin/sh\n")
1015 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1016 sys.executable)
1017 os.chmod(fname, 0o700)
1018 p = subprocess.Popen(fname)
1019 p.wait()
1020 os.remove(fname)
1021 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001022
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001023 def test_invalid_args(self):
1024 # invalid arguments should raise ValueError
1025 self.assertRaises(ValueError, subprocess.call,
1026 [sys.executable, "-c",
1027 "import sys; sys.exit(47)"],
1028 startupinfo=47)
1029 self.assertRaises(ValueError, subprocess.call,
1030 [sys.executable, "-c",
1031 "import sys; sys.exit(47)"],
1032 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001033
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001034 def test_shell_sequence(self):
1035 # Run command through the shell (sequence)
1036 newenv = os.environ.copy()
1037 newenv["FRUIT"] = "apple"
1038 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1039 stdout=subprocess.PIPE,
1040 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001041 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001042 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001043
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001044 def test_shell_string(self):
1045 # Run command through the shell (string)
1046 newenv = os.environ.copy()
1047 newenv["FRUIT"] = "apple"
1048 p = subprocess.Popen("echo $FRUIT", shell=1,
1049 stdout=subprocess.PIPE,
1050 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001051 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001052 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001053
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001054 def test_call_string(self):
1055 # call() function with string argument on UNIX
1056 fd, fname = mkstemp()
1057 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001058 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001059 fobj.write("#!/bin/sh\n")
1060 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1061 sys.executable)
1062 os.chmod(fname, 0o700)
1063 rc = subprocess.call(fname)
1064 os.remove(fname)
1065 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001066
Stefan Krah9542cc62010-07-19 14:20:53 +00001067 def test_specific_shell(self):
1068 # Issue #9265: Incorrect name passed as arg[0].
1069 shells = []
1070 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1071 for name in ['bash', 'ksh']:
1072 sh = os.path.join(prefix, name)
1073 if os.path.isfile(sh):
1074 shells.append(sh)
1075 if not shells: # Will probably work for any shell but csh.
1076 self.skipTest("bash or ksh required for this test")
1077 sh = '/bin/sh'
1078 if os.path.isfile(sh) and not os.path.islink(sh):
1079 # Test will fail if /bin/sh is a symlink to csh.
1080 shells.append(sh)
1081 for sh in shells:
1082 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1083 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001084 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001085 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1086
Florent Xicluna4886d242010-03-08 13:27:26 +00001087 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001088 # Do not inherit file handles from the parent.
1089 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001090 p = subprocess.Popen([sys.executable, "-c", """if 1:
1091 import sys, time
1092 sys.stdout.write('x\\n')
1093 sys.stdout.flush()
1094 time.sleep(30)
1095 """],
1096 close_fds=True,
1097 stdin=subprocess.PIPE,
1098 stdout=subprocess.PIPE,
1099 stderr=subprocess.PIPE)
1100 # Wait for the interpreter to be completely initialized before
1101 # sending any signal.
1102 p.stdout.read(1)
1103 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001104 return p
1105
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001106 def _kill_dead_process(self, method, *args):
1107 # Do not inherit file handles from the parent.
1108 # It should fix failures on some platforms.
1109 p = subprocess.Popen([sys.executable, "-c", """if 1:
1110 import sys, time
1111 sys.stdout.write('x\\n')
1112 sys.stdout.flush()
1113 """],
1114 close_fds=True,
1115 stdin=subprocess.PIPE,
1116 stdout=subprocess.PIPE,
1117 stderr=subprocess.PIPE)
1118 # Wait for the interpreter to be completely initialized before
1119 # sending any signal.
1120 p.stdout.read(1)
1121 # The process should end after this
1122 time.sleep(1)
1123 # This shouldn't raise even though the child is now dead
1124 getattr(p, method)(*args)
1125 p.communicate()
1126
Florent Xicluna4886d242010-03-08 13:27:26 +00001127 def test_send_signal(self):
1128 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001129 _, stderr = p.communicate()
1130 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001131 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001132
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001133 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001134 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001135 _, stderr = p.communicate()
1136 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001137 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001138
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001139 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001140 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001141 _, stderr = p.communicate()
1142 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001143 self.assertEqual(p.wait(), -signal.SIGTERM)
1144
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001145 def test_send_signal_dead(self):
1146 # Sending a signal to a dead process
1147 self._kill_dead_process('send_signal', signal.SIGINT)
1148
1149 def test_kill_dead(self):
1150 # Killing a dead process
1151 self._kill_dead_process('kill')
1152
1153 def test_terminate_dead(self):
1154 # Terminating a dead process
1155 self._kill_dead_process('terminate')
1156
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001157 def check_close_std_fds(self, fds):
1158 # Issue #9905: test that subprocess pipes still work properly with
1159 # some standard fds closed
1160 stdin = 0
1161 newfds = []
1162 for a in fds:
1163 b = os.dup(a)
1164 newfds.append(b)
1165 if a == 0:
1166 stdin = b
1167 try:
1168 for fd in fds:
1169 os.close(fd)
1170 out, err = subprocess.Popen([sys.executable, "-c",
1171 'import sys;'
1172 'sys.stdout.write("apple");'
1173 'sys.stdout.flush();'
1174 'sys.stderr.write("orange")'],
1175 stdin=stdin,
1176 stdout=subprocess.PIPE,
1177 stderr=subprocess.PIPE).communicate()
1178 err = support.strip_python_stderr(err)
1179 self.assertEqual((out, err), (b'apple', b'orange'))
1180 finally:
1181 for b, a in zip(newfds, fds):
1182 os.dup2(b, a)
1183 for b in newfds:
1184 os.close(b)
1185
1186 def test_close_fd_0(self):
1187 self.check_close_std_fds([0])
1188
1189 def test_close_fd_1(self):
1190 self.check_close_std_fds([1])
1191
1192 def test_close_fd_2(self):
1193 self.check_close_std_fds([2])
1194
1195 def test_close_fds_0_1(self):
1196 self.check_close_std_fds([0, 1])
1197
1198 def test_close_fds_0_2(self):
1199 self.check_close_std_fds([0, 2])
1200
1201 def test_close_fds_1_2(self):
1202 self.check_close_std_fds([1, 2])
1203
1204 def test_close_fds_0_1_2(self):
1205 # Issue #10806: test that subprocess pipes still work properly with
1206 # all standard fds closed.
1207 self.check_close_std_fds([0, 1, 2])
1208
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001209 def test_remapping_std_fds(self):
1210 # open up some temporary files
1211 temps = [mkstemp() for i in range(3)]
1212 try:
1213 temp_fds = [fd for fd, fname in temps]
1214
1215 # unlink the files -- we won't need to reopen them
1216 for fd, fname in temps:
1217 os.unlink(fname)
1218
1219 # write some data to what will become stdin, and rewind
1220 os.write(temp_fds[1], b"STDIN")
1221 os.lseek(temp_fds[1], 0, 0)
1222
1223 # move the standard file descriptors out of the way
1224 saved_fds = [os.dup(fd) for fd in range(3)]
1225 try:
1226 # duplicate the file objects over the standard fd's
1227 for fd, temp_fd in enumerate(temp_fds):
1228 os.dup2(temp_fd, fd)
1229
1230 # now use those files in the "wrong" order, so that subprocess
1231 # has to rearrange them in the child
1232 p = subprocess.Popen([sys.executable, "-c",
1233 'import sys; got = sys.stdin.read();'
1234 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1235 stdin=temp_fds[1],
1236 stdout=temp_fds[2],
1237 stderr=temp_fds[0])
1238 p.wait()
1239 finally:
1240 # restore the original fd's underneath sys.stdin, etc.
1241 for std, saved in enumerate(saved_fds):
1242 os.dup2(saved, std)
1243 os.close(saved)
1244
1245 for fd in temp_fds:
1246 os.lseek(fd, 0, 0)
1247
1248 out = os.read(temp_fds[2], 1024)
1249 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1250 self.assertEqual(out, b"got STDIN")
1251 self.assertEqual(err, b"err")
1252
1253 finally:
1254 for fd in temp_fds:
1255 os.close(fd)
1256
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001257 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1258 # open up some temporary files
1259 temps = [mkstemp() for i in range(3)]
1260 temp_fds = [fd for fd, fname in temps]
1261 try:
1262 # unlink the files -- we won't need to reopen them
1263 for fd, fname in temps:
1264 os.unlink(fname)
1265
1266 # save a copy of the standard file descriptors
1267 saved_fds = [os.dup(fd) for fd in range(3)]
1268 try:
1269 # duplicate the temp files over the standard fd's 0, 1, 2
1270 for fd, temp_fd in enumerate(temp_fds):
1271 os.dup2(temp_fd, fd)
1272
1273 # write some data to what will become stdin, and rewind
1274 os.write(stdin_no, b"STDIN")
1275 os.lseek(stdin_no, 0, 0)
1276
1277 # now use those files in the given order, so that subprocess
1278 # has to rearrange them in the child
1279 p = subprocess.Popen([sys.executable, "-c",
1280 'import sys; got = sys.stdin.read();'
1281 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1282 stdin=stdin_no,
1283 stdout=stdout_no,
1284 stderr=stderr_no)
1285 p.wait()
1286
1287 for fd in temp_fds:
1288 os.lseek(fd, 0, 0)
1289
1290 out = os.read(stdout_no, 1024)
1291 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1292 finally:
1293 for std, saved in enumerate(saved_fds):
1294 os.dup2(saved, std)
1295 os.close(saved)
1296
1297 self.assertEqual(out, b"got STDIN")
1298 self.assertEqual(err, b"err")
1299
1300 finally:
1301 for fd in temp_fds:
1302 os.close(fd)
1303
1304 # When duping fds, if there arises a situation where one of the fds is
1305 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1306 # This tests all combinations of this.
1307 def test_swap_fds(self):
1308 self.check_swap_fds(0, 1, 2)
1309 self.check_swap_fds(0, 2, 1)
1310 self.check_swap_fds(1, 0, 2)
1311 self.check_swap_fds(1, 2, 0)
1312 self.check_swap_fds(2, 0, 1)
1313 self.check_swap_fds(2, 1, 0)
1314
Victor Stinner13bb71c2010-04-23 21:41:56 +00001315 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001316 def prepare():
1317 raise ValueError("surrogate:\uDCff")
1318
1319 try:
1320 subprocess.call(
1321 [sys.executable, "-c", "pass"],
1322 preexec_fn=prepare)
1323 except ValueError as err:
1324 # Pure Python implementations keeps the message
1325 self.assertIsNone(subprocess._posixsubprocess)
1326 self.assertEqual(str(err), "surrogate:\uDCff")
1327 except RuntimeError as err:
1328 # _posixsubprocess uses a default message
1329 self.assertIsNotNone(subprocess._posixsubprocess)
1330 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1331 else:
1332 self.fail("Expected ValueError or RuntimeError")
1333
Victor Stinner13bb71c2010-04-23 21:41:56 +00001334 def test_undecodable_env(self):
1335 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001336 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001337 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001338 env = os.environ.copy()
1339 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001340 # Use C locale to get ascii for the locale encoding to force
1341 # surrogate-escaping of \xFF in the child process; otherwise it can
1342 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001343 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001344 stdout = subprocess.check_output(
1345 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001346 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001347 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001348 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001349
1350 # test bytes
1351 key = key.encode("ascii", "surrogateescape")
1352 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001353 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001354 env = os.environ.copy()
1355 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001356 stdout = subprocess.check_output(
1357 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001358 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001359 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001360 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001361
Victor Stinnerb745a742010-05-18 17:17:23 +00001362 def test_bytes_program(self):
1363 abs_program = os.fsencode(sys.executable)
1364 path, program = os.path.split(sys.executable)
1365 program = os.fsencode(program)
1366
1367 # absolute bytes path
1368 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001369 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001370
1371 # bytes program, unicode PATH
1372 env = os.environ.copy()
1373 env["PATH"] = path
1374 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001375 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001376
1377 # bytes program, bytes PATH
1378 envb = os.environb.copy()
1379 envb[b"PATH"] = os.fsencode(path)
1380 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001381 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001382
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001383 def test_pipe_cloexec(self):
1384 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1385 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1386
1387 p1 = subprocess.Popen([sys.executable, sleeper],
1388 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1389 stderr=subprocess.PIPE, close_fds=False)
1390
1391 self.addCleanup(p1.communicate, b'')
1392
1393 p2 = subprocess.Popen([sys.executable, fd_status],
1394 stdout=subprocess.PIPE, close_fds=False)
1395
1396 output, error = p2.communicate()
1397 result_fds = set(map(int, output.split(b',')))
1398 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1399 p1.stderr.fileno()])
1400
1401 self.assertFalse(result_fds & unwanted_fds,
1402 "Expected no fds from %r to be open in child, "
1403 "found %r" %
1404 (unwanted_fds, result_fds & unwanted_fds))
1405
1406 def test_pipe_cloexec_real_tools(self):
1407 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1408 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1409
1410 subdata = b'zxcvbn'
1411 data = subdata * 4 + b'\n'
1412
1413 p1 = subprocess.Popen([sys.executable, qcat],
1414 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1415 close_fds=False)
1416
1417 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1418 stdin=p1.stdout, stdout=subprocess.PIPE,
1419 close_fds=False)
1420
1421 self.addCleanup(p1.wait)
1422 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001423 def kill_p1():
1424 try:
1425 p1.terminate()
1426 except ProcessLookupError:
1427 pass
1428 def kill_p2():
1429 try:
1430 p2.terminate()
1431 except ProcessLookupError:
1432 pass
1433 self.addCleanup(kill_p1)
1434 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001435
1436 p1.stdin.write(data)
1437 p1.stdin.close()
1438
1439 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1440
1441 self.assertTrue(readfiles, "The child hung")
1442 self.assertEqual(p2.stdout.read(), data)
1443
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001444 p1.stdout.close()
1445 p2.stdout.close()
1446
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001447 def test_close_fds(self):
1448 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1449
1450 fds = os.pipe()
1451 self.addCleanup(os.close, fds[0])
1452 self.addCleanup(os.close, fds[1])
1453
1454 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001455 # add a bunch more fds
1456 for _ in range(9):
1457 fd = os.open("/dev/null", os.O_RDONLY)
1458 self.addCleanup(os.close, fd)
1459 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001460
1461 p = subprocess.Popen([sys.executable, fd_status],
1462 stdout=subprocess.PIPE, close_fds=False)
1463 output, ignored = p.communicate()
1464 remaining_fds = set(map(int, output.split(b',')))
1465
1466 self.assertEqual(remaining_fds & open_fds, open_fds,
1467 "Some fds were closed")
1468
1469 p = subprocess.Popen([sys.executable, fd_status],
1470 stdout=subprocess.PIPE, close_fds=True)
1471 output, ignored = p.communicate()
1472 remaining_fds = set(map(int, output.split(b',')))
1473
1474 self.assertFalse(remaining_fds & open_fds,
1475 "Some fds were left open")
1476 self.assertIn(1, remaining_fds, "Subprocess failed")
1477
Gregory P. Smith8facece2012-01-21 14:01:08 -08001478 # Keep some of the fd's we opened open in the subprocess.
1479 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1480 fds_to_keep = set(open_fds.pop() for _ in range(8))
1481 p = subprocess.Popen([sys.executable, fd_status],
1482 stdout=subprocess.PIPE, close_fds=True,
1483 pass_fds=())
1484 output, ignored = p.communicate()
1485 remaining_fds = set(map(int, output.split(b',')))
1486
1487 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1488 "Some fds not in pass_fds were left open")
1489 self.assertIn(1, remaining_fds, "Subprocess failed")
1490
Victor Stinner88701e22011-06-01 13:13:04 +02001491 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1492 # descriptor of a pipe closed in the parent process is valid in the
1493 # child process according to fstat(), but the mode of the file
1494 # descriptor is invalid, and read or write raise an error.
1495 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001496 def test_pass_fds(self):
1497 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1498
1499 open_fds = set()
1500
1501 for x in range(5):
1502 fds = os.pipe()
1503 self.addCleanup(os.close, fds[0])
1504 self.addCleanup(os.close, fds[1])
1505 open_fds.update(fds)
1506
1507 for fd in open_fds:
1508 p = subprocess.Popen([sys.executable, fd_status],
1509 stdout=subprocess.PIPE, close_fds=True,
1510 pass_fds=(fd, ))
1511 output, ignored = p.communicate()
1512
1513 remaining_fds = set(map(int, output.split(b',')))
1514 to_be_closed = open_fds - {fd}
1515
1516 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1517 self.assertFalse(remaining_fds & to_be_closed,
1518 "fd to be closed passed")
1519
1520 # pass_fds overrides close_fds with a warning.
1521 with self.assertWarns(RuntimeWarning) as context:
1522 self.assertFalse(subprocess.call(
1523 [sys.executable, "-c", "import sys; sys.exit(0)"],
1524 close_fds=False, pass_fds=(fd, )))
1525 self.assertIn('overriding close_fds', str(context.warning))
1526
Gregory P. Smithe14e9c22011-03-15 14:55:17 -04001527 def test_stdout_stdin_are_single_inout_fd(self):
1528 with io.open(os.devnull, "r+") as inout:
1529 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1530 stdout=inout, stdin=inout)
1531 p.wait()
1532
1533 def test_stdout_stderr_are_single_inout_fd(self):
1534 with io.open(os.devnull, "r+") as inout:
1535 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1536 stdout=inout, stderr=inout)
1537 p.wait()
1538
1539 def test_stderr_stdin_are_single_inout_fd(self):
1540 with io.open(os.devnull, "r+") as inout:
1541 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1542 stderr=inout, stdin=inout)
1543 p.wait()
1544
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001545 def test_wait_when_sigchild_ignored(self):
1546 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1547 sigchild_ignore = support.findfile("sigchild_ignore.py",
1548 subdir="subprocessdata")
1549 p = subprocess.Popen([sys.executable, sigchild_ignore],
1550 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1551 stdout, stderr = p.communicate()
1552 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001553 " non-zero with this error:\n%s" %
1554 stderr.decode('utf8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001555
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001556 def test_select_unbuffered(self):
1557 # Issue #11459: bufsize=0 should really set the pipes as
1558 # unbuffered (and therefore let select() work properly).
1559 select = support.import_module("select")
1560 p = subprocess.Popen([sys.executable, "-c",
1561 'import sys;'
1562 'sys.stdout.write("apple")'],
1563 stdout=subprocess.PIPE,
1564 bufsize=0)
1565 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001566 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001567 try:
1568 self.assertEqual(f.read(4), b"appl")
1569 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1570 finally:
1571 p.wait()
1572
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001573 def test_zombie_fast_process_del(self):
1574 # Issue #12650: on Unix, if Popen.__del__() was called before the
1575 # process exited, it wouldn't be added to subprocess._active, and would
1576 # remain a zombie.
1577 # spawn a Popen, and delete its reference before it exits
1578 p = subprocess.Popen([sys.executable, "-c",
1579 'import sys, time;'
1580 'time.sleep(0.2)'],
1581 stdout=subprocess.PIPE,
1582 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001583 self.addCleanup(p.stdout.close)
1584 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001585 ident = id(p)
1586 pid = p.pid
1587 del p
1588 # check that p is in the active processes list
1589 self.assertIn(ident, [id(o) for o in subprocess._active])
1590
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001591 def test_leak_fast_process_del_killed(self):
1592 # Issue #12650: on Unix, if Popen.__del__() was called before the
1593 # process exited, and the process got killed by a signal, it would never
1594 # be removed from subprocess._active, which triggered a FD and memory
1595 # leak.
1596 # spawn a Popen, delete its reference and kill it
1597 p = subprocess.Popen([sys.executable, "-c",
1598 'import time;'
1599 'time.sleep(3)'],
1600 stdout=subprocess.PIPE,
1601 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001602 self.addCleanup(p.stdout.close)
1603 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001604 ident = id(p)
1605 pid = p.pid
1606 del p
1607 os.kill(pid, signal.SIGKILL)
1608 # check that p is in the active processes list
1609 self.assertIn(ident, [id(o) for o in subprocess._active])
1610
1611 # let some time for the process to exit, and create a new Popen: this
1612 # should trigger the wait() of p
1613 time.sleep(0.2)
1614 with self.assertRaises(EnvironmentError) as c:
1615 with subprocess.Popen(['nonexisting_i_hope'],
1616 stdout=subprocess.PIPE,
1617 stderr=subprocess.PIPE) as proc:
1618 pass
1619 # p should have been wait()ed on, and removed from the _active list
1620 self.assertRaises(OSError, os.waitpid, pid, 0)
1621 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1622
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001623
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001624@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001625class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001626
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001627 def test_startupinfo(self):
1628 # startupinfo argument
1629 # We uses hardcoded constants, because we do not want to
1630 # depend on win32all.
1631 STARTF_USESHOWWINDOW = 1
1632 SW_MAXIMIZE = 3
1633 startupinfo = subprocess.STARTUPINFO()
1634 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1635 startupinfo.wShowWindow = SW_MAXIMIZE
1636 # Since Python is a console process, it won't be affected
1637 # by wShowWindow, but the argument should be silently
1638 # ignored
1639 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001640 startupinfo=startupinfo)
1641
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001642 def test_creationflags(self):
1643 # creationflags argument
1644 CREATE_NEW_CONSOLE = 16
1645 sys.stderr.write(" a DOS box should flash briefly ...\n")
1646 subprocess.call(sys.executable +
1647 ' -c "import time; time.sleep(0.25)"',
1648 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001649
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001650 def test_invalid_args(self):
1651 # invalid arguments should raise ValueError
1652 self.assertRaises(ValueError, subprocess.call,
1653 [sys.executable, "-c",
1654 "import sys; sys.exit(47)"],
1655 preexec_fn=lambda: 1)
1656 self.assertRaises(ValueError, subprocess.call,
1657 [sys.executable, "-c",
1658 "import sys; sys.exit(47)"],
1659 stdout=subprocess.PIPE,
1660 close_fds=True)
1661
1662 def test_close_fds(self):
1663 # close file descriptors
1664 rc = subprocess.call([sys.executable, "-c",
1665 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001666 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001667 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001668
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001669 def test_shell_sequence(self):
1670 # Run command through the shell (sequence)
1671 newenv = os.environ.copy()
1672 newenv["FRUIT"] = "physalis"
1673 p = subprocess.Popen(["set"], shell=1,
1674 stdout=subprocess.PIPE,
1675 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001676 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001677 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001678
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001679 def test_shell_string(self):
1680 # Run command through the shell (string)
1681 newenv = os.environ.copy()
1682 newenv["FRUIT"] = "physalis"
1683 p = subprocess.Popen("set", shell=1,
1684 stdout=subprocess.PIPE,
1685 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001686 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001687 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001688
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001689 def test_call_string(self):
1690 # call() function with string argument on Windows
1691 rc = subprocess.call(sys.executable +
1692 ' -c "import sys; sys.exit(47)"')
1693 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001694
Florent Xicluna4886d242010-03-08 13:27:26 +00001695 def _kill_process(self, method, *args):
1696 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001697 p = subprocess.Popen([sys.executable, "-c", """if 1:
1698 import sys, time
1699 sys.stdout.write('x\\n')
1700 sys.stdout.flush()
1701 time.sleep(30)
1702 """],
1703 stdin=subprocess.PIPE,
1704 stdout=subprocess.PIPE,
1705 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001706 self.addCleanup(p.stdout.close)
1707 self.addCleanup(p.stderr.close)
1708 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001709 # Wait for the interpreter to be completely initialized before
1710 # sending any signal.
1711 p.stdout.read(1)
1712 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001713 _, stderr = p.communicate()
1714 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001715 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001716 self.assertNotEqual(returncode, 0)
1717
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001718 def _kill_dead_process(self, method, *args):
1719 p = subprocess.Popen([sys.executable, "-c", """if 1:
1720 import sys, time
1721 sys.stdout.write('x\\n')
1722 sys.stdout.flush()
1723 sys.exit(42)
1724 """],
1725 stdin=subprocess.PIPE,
1726 stdout=subprocess.PIPE,
1727 stderr=subprocess.PIPE)
1728 self.addCleanup(p.stdout.close)
1729 self.addCleanup(p.stderr.close)
1730 self.addCleanup(p.stdin.close)
1731 # Wait for the interpreter to be completely initialized before
1732 # sending any signal.
1733 p.stdout.read(1)
1734 # The process should end after this
1735 time.sleep(1)
1736 # This shouldn't raise even though the child is now dead
1737 getattr(p, method)(*args)
1738 _, stderr = p.communicate()
1739 self.assertStderrEqual(stderr, b'')
1740 rc = p.wait()
1741 self.assertEqual(rc, 42)
1742
Florent Xicluna4886d242010-03-08 13:27:26 +00001743 def test_send_signal(self):
1744 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001745
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001746 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001747 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001748
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001749 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001750 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001751
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001752 def test_send_signal_dead(self):
1753 self._kill_dead_process('send_signal', signal.SIGTERM)
1754
1755 def test_kill_dead(self):
1756 self._kill_dead_process('kill')
1757
1758 def test_terminate_dead(self):
1759 self._kill_dead_process('terminate')
1760
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001761
Brett Cannona23810f2008-05-26 19:04:21 +00001762# The module says:
1763# "NB This only works (and is only relevant) for UNIX."
1764#
1765# Actually, getoutput should work on any platform with an os.popen, but
1766# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001767@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001768class CommandTests(unittest.TestCase):
1769 def test_getoutput(self):
1770 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1771 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1772 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001773
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001774 # we use mkdtemp in the next line to create an empty directory
1775 # under our exclusive control; from that, we can invent a pathname
1776 # that we _know_ won't exist. This is guaranteed to fail.
1777 dir = None
1778 try:
1779 dir = tempfile.mkdtemp()
1780 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001781
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001782 status, output = subprocess.getstatusoutput('cat ' + name)
1783 self.assertNotEqual(status, 0)
1784 finally:
1785 if dir is not None:
1786 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001787
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001788
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001789@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1790 "poll system call not supported")
1791class ProcessTestCaseNoPoll(ProcessTestCase):
1792 def setUp(self):
1793 subprocess._has_poll = False
1794 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001795
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001796 def tearDown(self):
1797 subprocess._has_poll = True
1798 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001799
1800
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001801@unittest.skipUnless(getattr(subprocess, '_posixsubprocess', False),
1802 "_posixsubprocess extension module not found.")
1803class ProcessTestCasePOSIXPurePython(ProcessTestCase, POSIXProcessTestCase):
Gregory P. Smith7439e7b2011-05-28 09:06:02 -07001804 @classmethod
1805 def setUpClass(cls):
1806 global subprocess
1807 assert subprocess._posixsubprocess
1808 # Reimport subprocess while forcing _posixsubprocess to not exist.
1809 with support.check_warnings(('.*_posixsubprocess .* not being used.*',
1810 RuntimeWarning)):
1811 subprocess = support.import_fresh_module(
1812 'subprocess', blocked=['_posixsubprocess'])
1813 assert not subprocess._posixsubprocess
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001814
Gregory P. Smith7439e7b2011-05-28 09:06:02 -07001815 @classmethod
1816 def tearDownClass(cls):
1817 global subprocess
1818 # Reimport subprocess as it should be, restoring order to the universe.
1819 subprocess = support.import_fresh_module('subprocess')
1820 assert subprocess._posixsubprocess
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001821
1822
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001823class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001824 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001825 def test_eintr_retry_call(self):
1826 record_calls = []
1827 def fake_os_func(*args):
1828 record_calls.append(args)
1829 if len(record_calls) == 2:
1830 raise OSError(errno.EINTR, "fake interrupted system call")
1831 return tuple(reversed(args))
1832
1833 self.assertEqual((999, 256),
1834 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1835 self.assertEqual([(256, 999)], record_calls)
1836 # This time there will be an EINTR so it will loop once.
1837 self.assertEqual((666,),
1838 subprocess._eintr_retry_call(fake_os_func, 666))
1839 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1840
1841
Tim Golden126c2962010-08-11 14:20:40 +00001842@unittest.skipUnless(mswindows, "Windows-specific tests")
1843class CommandsWithSpaces (BaseTestCase):
1844
1845 def setUp(self):
1846 super().setUp()
1847 f, fname = mkstemp(".py", "te st")
1848 self.fname = fname.lower ()
1849 os.write(f, b"import sys;"
1850 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1851 )
1852 os.close(f)
1853
1854 def tearDown(self):
1855 os.remove(self.fname)
1856 super().tearDown()
1857
1858 def with_spaces(self, *args, **kwargs):
1859 kwargs['stdout'] = subprocess.PIPE
1860 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001861 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001862 self.assertEqual(
1863 p.stdout.read ().decode("mbcs"),
1864 "2 [%r, 'ab cd']" % self.fname
1865 )
1866
1867 def test_shell_string_with_spaces(self):
1868 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001869 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1870 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001871
1872 def test_shell_sequence_with_spaces(self):
1873 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001874 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001875
1876 def test_noshell_string_with_spaces(self):
1877 # call() function with string argument with spaces on Windows
1878 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1879 "ab cd"))
1880
1881 def test_noshell_sequence_with_spaces(self):
1882 # call() function with sequence argument with spaces on Windows
1883 self.with_spaces([sys.executable, self.fname, "ab cd"])
1884
Brian Curtin79cdb662010-12-03 02:46:02 +00001885
Georg Brandla86b2622012-02-20 21:34:57 +01001886class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00001887
1888 def test_pipe(self):
1889 with subprocess.Popen([sys.executable, "-c",
1890 "import sys;"
1891 "sys.stdout.write('stdout');"
1892 "sys.stderr.write('stderr');"],
1893 stdout=subprocess.PIPE,
1894 stderr=subprocess.PIPE) as proc:
1895 self.assertEqual(proc.stdout.read(), b"stdout")
1896 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1897
1898 self.assertTrue(proc.stdout.closed)
1899 self.assertTrue(proc.stderr.closed)
1900
1901 def test_returncode(self):
1902 with subprocess.Popen([sys.executable, "-c",
1903 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smithc9557af2011-05-11 22:18:23 -07001904 pass
1905 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00001906 self.assertEqual(proc.returncode, 100)
1907
1908 def test_communicate_stdin(self):
1909 with subprocess.Popen([sys.executable, "-c",
1910 "import sys;"
1911 "sys.exit(sys.stdin.read() == 'context')"],
1912 stdin=subprocess.PIPE) as proc:
1913 proc.communicate(b"context")
1914 self.assertEqual(proc.returncode, 1)
1915
1916 def test_invalid_args(self):
1917 with self.assertRaises(EnvironmentError) as c:
1918 with subprocess.Popen(['nonexisting_i_hope'],
1919 stdout=subprocess.PIPE,
1920 stderr=subprocess.PIPE) as proc:
1921 pass
1922
1923 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1924 raise c.exception
1925
1926
Gregory P. Smith961e0e82011-03-15 15:43:39 -04001927def test_main():
1928 unit_tests = (ProcessTestCase,
1929 POSIXProcessTestCase,
1930 Win32ProcessTestCase,
1931 ProcessTestCasePOSIXPurePython,
1932 CommandTests,
1933 ProcessTestCaseNoPoll,
1934 HelperFunctionTests,
1935 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02001936 ContextManagerTests,
1937 )
Gregory P. Smith961e0e82011-03-15 15:43:39 -04001938
1939 support.run_unittest(*unit_tests)
1940 support.reap_children()
1941
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001942if __name__ == "__main__":
Gregory P. Smithe14e9c22011-03-15 14:55:17 -04001943 unittest.main()