blob: 7d4ca2cd00dfef4ed0e784f80164fac35fd3ffc7 [file] [log] [blame]
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002from test import support
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00003import subprocess
4import sys
5import signal
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04006import io
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00007import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00008import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00009import tempfile
10import time
Tim Peters3761e8d2004-10-13 04:07:12 +000011import re
Ezio Melotti184bdfb2010-02-18 09:37:05 +000012import sysconfig
Gregory P. Smithd23047b2010-12-04 09:10:44 +000013import warnings
Gregory P. Smith51ee2702010-12-13 07:59:39 +000014import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040015import shutil
Gregory P. Smith32ec9da2010-03-19 16:53:08 +000016try:
17 import gc
18except ImportError:
19 gc = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000020
21mswindows = (sys.platform == "win32")
22
23#
24# Depends on the following external programs: Python
25#
26
27if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000028 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
29 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000030else:
31 SETBINARY = ''
32
Florent Xiclunab1e94e82010-02-27 22:12:37 +000033
34try:
35 mkstemp = tempfile.mkstemp
36except AttributeError:
37 # tempfile.mkstemp is not available
38 def mkstemp():
39 """Replacement for mkstemp, calling mktemp."""
40 fname = tempfile.mktemp()
41 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
42
Tim Peters3761e8d2004-10-13 04:07:12 +000043
Florent Xiclunac049d872010-03-27 22:47:23 +000044class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000045 def setUp(self):
46 # Try to minimize the number of children we have so this test
47 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000048 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000049
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000050 def tearDown(self):
51 for inst in subprocess._active:
52 inst.wait()
53 subprocess._cleanup()
54 self.assertFalse(subprocess._active, "subprocess._active not empty")
55
Florent Xiclunab1e94e82010-02-27 22:12:37 +000056 def assertStderrEqual(self, stderr, expected, msg=None):
57 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
58 # shutdown time. That frustrates tests trying to check stderr produced
59 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000060 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040061 # strip_python_stderr also strips whitespace, so we do too.
62 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000063 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000064
Florent Xiclunac049d872010-03-27 22:47:23 +000065
66class ProcessTestCase(BaseTestCase):
67
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000068 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000069 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000070 rc = subprocess.call([sys.executable, "-c",
71 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000072 self.assertEqual(rc, 47)
73
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040074 def test_call_timeout(self):
75 # call() function with timeout argument; we want to test that the child
76 # process gets killed when the timeout expires. If the child isn't
77 # killed, this call will deadlock since subprocess.call waits for the
78 # child.
79 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
80 [sys.executable, "-c", "while True: pass"],
81 timeout=0.1)
82
Peter Astrand454f7672005-01-01 09:36:35 +000083 def test_check_call_zero(self):
84 # check_call() function with zero return code
85 rc = subprocess.check_call([sys.executable, "-c",
86 "import sys; sys.exit(0)"])
87 self.assertEqual(rc, 0)
88
89 def test_check_call_nonzero(self):
90 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000091 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +000092 subprocess.check_call([sys.executable, "-c",
93 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000094 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000095
Georg Brandlf9734072008-12-07 15:30:06 +000096 def test_check_output(self):
97 # check_output() function with zero return code
98 output = subprocess.check_output(
99 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000100 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000101
102 def test_check_output_nonzero(self):
103 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000104 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000105 subprocess.check_output(
106 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000107 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000108
109 def test_check_output_stderr(self):
110 # check_output() function stderr redirected to stdout
111 output = subprocess.check_output(
112 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
113 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000114 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000115
116 def test_check_output_stdout_arg(self):
117 # check_output() function stderr redirected to stdout
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000118 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000119 output = subprocess.check_output(
120 [sys.executable, "-c", "print('will not be run')"],
121 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000122 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000123 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000124
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400125 def test_check_output_timeout(self):
126 # check_output() function with timeout arg
127 with self.assertRaises(subprocess.TimeoutExpired) as c:
128 output = subprocess.check_output(
129 [sys.executable, "-c",
130 "import sys; sys.stdout.write('BDFL')\n"
131 "sys.stdout.flush()\n"
132 "while True: pass"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400133 # Some heavily loaded buildbots (sparc Debian 3.x) require
134 # this much time to start and print.
135 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400136 self.fail("Expected TimeoutExpired.")
137 self.assertEqual(c.exception.output, b'BDFL')
138
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000139 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000140 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000141 newenv = os.environ.copy()
142 newenv["FRUIT"] = "banana"
143 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000144 'import sys, os;'
145 'sys.exit(os.getenv("FRUIT")=="banana")'],
146 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000147 self.assertEqual(rc, 1)
148
Victor Stinner87b9bc32011-06-01 00:57:47 +0200149 def test_invalid_args(self):
150 # Popen() called with invalid arguments should raise TypeError
151 # but Popen.__del__ should not complain (issue #12085)
152 with support.captured_stderr() as s:
153 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
154 argcount = subprocess.Popen.__init__.__code__.co_argcount
155 too_many_args = [0] * (argcount + 1)
156 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
157 self.assertEqual(s.getvalue(), '')
158
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000159 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000160 # .stdin 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 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000163 self.addCleanup(p.stdout.close)
164 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000165 p.wait()
166 self.assertEqual(p.stdin, None)
167
168 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000169 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000170 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000171 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000172 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000173 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000174 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000175 self.addCleanup(p.stdin.close)
176 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000177 p.wait()
178 self.assertEqual(p.stdout, None)
179
180 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000181 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000182 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000183 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000184 self.addCleanup(p.stdout.close)
185 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000186 p.wait()
187 self.assertEqual(p.stderr, None)
188
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000189 def test_executable_with_cwd(self):
Florent Xicluna1d1ab972010-03-11 01:53:10 +0000190 python_dir = os.path.dirname(os.path.realpath(sys.executable))
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000191 p = subprocess.Popen(["somethingyoudonthave", "-c",
192 "import sys; sys.exit(47)"],
193 executable=sys.executable, cwd=python_dir)
194 p.wait()
195 self.assertEqual(p.returncode, 47)
196
197 @unittest.skipIf(sysconfig.is_python_build(),
198 "need an installed Python. See #7774")
199 def test_executable_without_cwd(self):
200 # For a normal installation, it should work without 'cwd'
201 # argument. For test runs in the build directory, see #7774.
202 p = subprocess.Popen(["somethingyoudonthave", "-c",
203 "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000204 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000205 p.wait()
206 self.assertEqual(p.returncode, 47)
207
208 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000209 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000210 p = subprocess.Popen([sys.executable, "-c",
211 'import sys; sys.exit(sys.stdin.read() == "pear")'],
212 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000213 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000214 p.stdin.close()
215 p.wait()
216 self.assertEqual(p.returncode, 1)
217
218 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000219 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000220 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000221 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000222 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000223 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000224 os.lseek(d, 0, 0)
225 p = subprocess.Popen([sys.executable, "-c",
226 'import sys; sys.exit(sys.stdin.read() == "pear")'],
227 stdin=d)
228 p.wait()
229 self.assertEqual(p.returncode, 1)
230
231 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000232 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000233 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000234 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000235 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000236 tf.seek(0)
237 p = subprocess.Popen([sys.executable, "-c",
238 'import sys; sys.exit(sys.stdin.read() == "pear")'],
239 stdin=tf)
240 p.wait()
241 self.assertEqual(p.returncode, 1)
242
243 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000244 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000245 p = subprocess.Popen([sys.executable, "-c",
246 'import sys; sys.stdout.write("orange")'],
247 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000248 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000249 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000250
251 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000252 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000253 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000254 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000255 d = tf.fileno()
256 p = subprocess.Popen([sys.executable, "-c",
257 'import sys; sys.stdout.write("orange")'],
258 stdout=d)
259 p.wait()
260 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000261 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000262
263 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000264 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000265 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000266 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000267 p = subprocess.Popen([sys.executable, "-c",
268 'import sys; sys.stdout.write("orange")'],
269 stdout=tf)
270 p.wait()
271 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000272 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000273
274 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000275 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000276 p = subprocess.Popen([sys.executable, "-c",
277 'import sys; sys.stderr.write("strawberry")'],
278 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000279 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000280 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000281
282 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000283 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000284 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000285 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000286 d = tf.fileno()
287 p = subprocess.Popen([sys.executable, "-c",
288 'import sys; sys.stderr.write("strawberry")'],
289 stderr=d)
290 p.wait()
291 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000292 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000293
294 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000295 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000296 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000297 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000298 p = subprocess.Popen([sys.executable, "-c",
299 'import sys; sys.stderr.write("strawberry")'],
300 stderr=tf)
301 p.wait()
302 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000303 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000304
305 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000306 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000307 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000308 'import sys;'
309 'sys.stdout.write("apple");'
310 'sys.stdout.flush();'
311 'sys.stderr.write("orange")'],
312 stdout=subprocess.PIPE,
313 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000314 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000315 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000316
317 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000318 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000319 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000320 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000321 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000322 'import sys;'
323 'sys.stdout.write("apple");'
324 'sys.stdout.flush();'
325 'sys.stderr.write("orange")'],
326 stdout=tf,
327 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000328 p.wait()
329 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000330 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000331
Thomas Wouters89f507f2006-12-13 04:49:30 +0000332 def test_stdout_filedes_of_stdout(self):
333 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000334 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000335 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000336 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000337
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200338 def test_stdout_devnull(self):
339 p = subprocess.Popen([sys.executable, "-c",
340 'for i in range(10240):'
341 'print("x" * 1024)'],
342 stdout=subprocess.DEVNULL)
343 p.wait()
344 self.assertEqual(p.stdout, None)
345
346 def test_stderr_devnull(self):
347 p = subprocess.Popen([sys.executable, "-c",
348 'import sys\n'
349 'for i in range(10240):'
350 'sys.stderr.write("x" * 1024)'],
351 stderr=subprocess.DEVNULL)
352 p.wait()
353 self.assertEqual(p.stderr, None)
354
355 def test_stdin_devnull(self):
356 p = subprocess.Popen([sys.executable, "-c",
357 'import sys;'
358 'sys.stdin.read(1)'],
359 stdin=subprocess.DEVNULL)
360 p.wait()
361 self.assertEqual(p.stdin, None)
362
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000363 def test_cwd(self):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000364 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000365 # We cannot use os.path.realpath to canonicalize the path,
366 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
367 cwd = os.getcwd()
368 os.chdir(tmpdir)
369 tmpdir = os.getcwd()
370 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000371 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000372 'import sys,os;'
373 'sys.stdout.write(os.getcwd())'],
374 stdout=subprocess.PIPE,
375 cwd=tmpdir)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000376 self.addCleanup(p.stdout.close)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000377 normcase = os.path.normcase
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000378 self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
379 normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000380
381 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000382 newenv = os.environ.copy()
383 newenv["FRUIT"] = "orange"
384 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000385 'import sys,os;'
386 'sys.stdout.write(os.getenv("FRUIT"))'],
387 stdout=subprocess.PIPE,
388 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000389 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000390 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000391
Peter Astrandcbac93c2005-03-03 20:24:28 +0000392 def test_communicate_stdin(self):
393 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000394 'import sys;'
395 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000396 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000397 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000398 self.assertEqual(p.returncode, 1)
399
400 def test_communicate_stdout(self):
401 p = subprocess.Popen([sys.executable, "-c",
402 'import sys; sys.stdout.write("pineapple")'],
403 stdout=subprocess.PIPE)
404 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000405 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000406 self.assertEqual(stderr, None)
407
408 def test_communicate_stderr(self):
409 p = subprocess.Popen([sys.executable, "-c",
410 'import sys; sys.stderr.write("pineapple")'],
411 stderr=subprocess.PIPE)
412 (stdout, stderr) = p.communicate()
413 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000414 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000415
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000416 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000417 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000418 'import sys,os;'
419 'sys.stderr.write("pineapple");'
420 'sys.stdout.write(sys.stdin.read())'],
421 stdin=subprocess.PIPE,
422 stdout=subprocess.PIPE,
423 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000424 self.addCleanup(p.stdout.close)
425 self.addCleanup(p.stderr.close)
426 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000427 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000428 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000429 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000430
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400431 def test_communicate_timeout(self):
432 p = subprocess.Popen([sys.executable, "-c",
433 'import sys,os,time;'
434 'sys.stderr.write("pineapple\\n");'
435 'time.sleep(1);'
436 'sys.stderr.write("pear\\n");'
437 'sys.stdout.write(sys.stdin.read())'],
438 universal_newlines=True,
439 stdin=subprocess.PIPE,
440 stdout=subprocess.PIPE,
441 stderr=subprocess.PIPE)
442 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
443 timeout=0.3)
444 # Make sure we can keep waiting for it, and that we get the whole output
445 # after it completes.
446 (stdout, stderr) = p.communicate()
447 self.assertEqual(stdout, "banana")
448 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
449
450 def test_communicate_timeout_large_ouput(self):
451 # Test a expring timeout while the child is outputting lots of data.
452 p = subprocess.Popen([sys.executable, "-c",
453 'import sys,os,time;'
454 'sys.stdout.write("a" * (64 * 1024));'
455 'time.sleep(0.2);'
456 'sys.stdout.write("a" * (64 * 1024));'
457 'time.sleep(0.2);'
458 'sys.stdout.write("a" * (64 * 1024));'
459 'time.sleep(0.2);'
460 'sys.stdout.write("a" * (64 * 1024));'],
461 stdout=subprocess.PIPE)
462 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
463 (stdout, _) = p.communicate()
464 self.assertEqual(len(stdout), 4 * 64 * 1024)
465
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000466 # Test for the fd leak reported in http://bugs.python.org/issue2791.
467 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000468 for stdin_pipe in (False, True):
469 for stdout_pipe in (False, True):
470 for stderr_pipe in (False, True):
471 options = {}
472 if stdin_pipe:
473 options['stdin'] = subprocess.PIPE
474 if stdout_pipe:
475 options['stdout'] = subprocess.PIPE
476 if stderr_pipe:
477 options['stderr'] = subprocess.PIPE
478 if not options:
479 continue
480 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
481 p.communicate()
482 if p.stdin is not None:
483 self.assertTrue(p.stdin.closed)
484 if p.stdout is not None:
485 self.assertTrue(p.stdout.closed)
486 if p.stderr is not None:
487 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000488
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000489 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000490 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000491 p = subprocess.Popen([sys.executable, "-c",
492 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000493 (stdout, stderr) = p.communicate()
494 self.assertEqual(stdout, None)
495 self.assertEqual(stderr, None)
496
497 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000498 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000499 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000500 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000501 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000502 os.close(x)
503 os.close(y)
504 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000505 'import sys,os;'
506 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200507 'sys.stderr.write("x" * %d);'
508 'sys.stdout.write(sys.stdin.read())' %
509 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000510 stdin=subprocess.PIPE,
511 stdout=subprocess.PIPE,
512 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000513 self.addCleanup(p.stdout.close)
514 self.addCleanup(p.stderr.close)
515 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200516 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000517 (stdout, stderr) = p.communicate(string_to_write)
518 self.assertEqual(stdout, string_to_write)
519
520 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000521 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000522 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000523 'import sys,os;'
524 'sys.stdout.write(sys.stdin.read())'],
525 stdin=subprocess.PIPE,
526 stdout=subprocess.PIPE,
527 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000528 self.addCleanup(p.stdout.close)
529 self.addCleanup(p.stderr.close)
530 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000531 p.stdin.write(b"banana")
532 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000533 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000534 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000535
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000536 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000537 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000538 'import sys,os;' + SETBINARY +
539 'sys.stdout.write("line1\\n");'
540 'sys.stdout.flush();'
541 'sys.stdout.write("line2\\n");'
542 'sys.stdout.flush();'
543 'sys.stdout.write("line3\\r\\n");'
544 'sys.stdout.flush();'
545 'sys.stdout.write("line4\\r");'
546 'sys.stdout.flush();'
547 'sys.stdout.write("\\nline5");'
548 'sys.stdout.flush();'
549 'sys.stdout.write("\\nline6");'],
550 stdout=subprocess.PIPE,
551 universal_newlines=1)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000552 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000553 stdout = p.stdout.read()
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000554 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000555
556 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000557 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000558 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000559 'import sys,os;' + SETBINARY +
560 'sys.stdout.write("line1\\n");'
561 'sys.stdout.flush();'
562 'sys.stdout.write("line2\\n");'
563 'sys.stdout.flush();'
564 'sys.stdout.write("line3\\r\\n");'
565 'sys.stdout.flush();'
566 'sys.stdout.write("line4\\r");'
567 'sys.stdout.flush();'
568 'sys.stdout.write("\\nline5");'
569 'sys.stdout.flush();'
570 'sys.stdout.write("\\nline6");'],
571 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
572 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000573 self.addCleanup(p.stdout.close)
574 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000575 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000576 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000577
578 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000579 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000580 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000581 max_handles = 1026 # too much for most UNIX systems
582 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000583 max_handles = 2050 # too much for (at least some) Windows setups
584 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400585 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000586 try:
587 for i in range(max_handles):
588 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400589 tmpfile = os.path.join(tmpdir, support.TESTFN)
590 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000591 except OSError as e:
592 if e.errno != errno.EMFILE:
593 raise
594 break
595 else:
596 self.skipTest("failed to reach the file descriptor limit "
597 "(tried %d)" % max_handles)
598 # Close a couple of them (should be enough for a subprocess)
599 for i in range(10):
600 os.close(handles.pop())
601 # Loop creating some subprocesses. If one of them leaks some fds,
602 # the next loop iteration will fail by reaching the max fd limit.
603 for i in range(15):
604 p = subprocess.Popen([sys.executable, "-c",
605 "import sys;"
606 "sys.stdout.write(sys.stdin.read())"],
607 stdin=subprocess.PIPE,
608 stdout=subprocess.PIPE,
609 stderr=subprocess.PIPE)
610 data = p.communicate(b"lime")[0]
611 self.assertEqual(data, b"lime")
612 finally:
613 for h in handles:
614 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400615 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000616
617 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000618 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
619 '"a b c" d e')
620 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
621 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000622 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
623 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000624 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
625 'a\\\\\\b "de fg" h')
626 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
627 'a\\\\\\"b c d')
628 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
629 '"a\\\\b c" d e')
630 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
631 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000632 self.assertEqual(subprocess.list2cmdline(['ab', '']),
633 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000634
635
636 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000637 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000638 "-c", "import time; time.sleep(1)"])
639 count = 0
640 while p.poll() is None:
641 time.sleep(0.1)
642 count += 1
643 # We expect that the poll loop probably went around about 10 times,
644 # but, based on system scheduling we can't control, it's possible
645 # poll() never returned None. It "should be" very rare that it
646 # didn't go around at least twice.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000647 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000648 # Subsequent invocations should just return the returncode
649 self.assertEqual(p.poll(), 0)
650
651
652 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000653 p = subprocess.Popen([sys.executable,
654 "-c", "import time; time.sleep(2)"])
655 self.assertEqual(p.wait(), 0)
656 # Subsequent invocations should just return the returncode
657 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000658
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400659 def test_wait_timeout(self):
660 p = subprocess.Popen([sys.executable,
Reid Kleckner93479cc2011-03-14 19:32:41 -0400661 "-c", "import time; time.sleep(0.1)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -0400662 with self.assertRaises(subprocess.TimeoutExpired) as c:
663 p.wait(timeout=0.01)
664 self.assertIn("0.01", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -0400665 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
666 # time to start.
667 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400668
Peter Astrand738131d2004-11-30 21:04:45 +0000669 def test_invalid_bufsize(self):
670 # an invalid type of the bufsize argument should raise
671 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000672 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000673 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000674
Guido van Rossum46a05a72007-06-07 21:56:45 +0000675 def test_bufsize_is_none(self):
676 # bufsize=None should be the same as bufsize=0.
677 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
678 self.assertEqual(p.wait(), 0)
679 # Again with keyword arg
680 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
681 self.assertEqual(p.wait(), 0)
682
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000683 def test_leaking_fds_on_error(self):
684 # see bug #5179: Popen leaks file descriptors to PIPEs if
685 # the child fails to execute; this will eventually exhaust
686 # the maximum number of open fds. 1024 seems a very common
687 # value for that limit, but Windows has 2048, so we loop
688 # 1024 times (each call leaked two fds).
689 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000690 # Windows raises IOError. Others raise OSError.
691 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000692 subprocess.Popen(['nonexisting_i_hope'],
693 stdout=subprocess.PIPE,
694 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400695 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400696 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000697 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000698
Victor Stinnerb3693582010-05-21 20:13:12 +0000699 def test_issue8780(self):
700 # Ensure that stdout is inherited from the parent
701 # if stdout=PIPE is not used
702 code = ';'.join((
703 'import subprocess, sys',
704 'retcode = subprocess.call('
705 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
706 'assert retcode == 0'))
707 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000708 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000709
Tim Goldenaf5ac392010-08-06 13:03:56 +0000710 def test_handles_closed_on_exception(self):
711 # If CreateProcess exits with an error, ensure the
712 # duplicate output handles are released
713 ifhandle, ifname = mkstemp()
714 ofhandle, ofname = mkstemp()
715 efhandle, efname = mkstemp()
716 try:
717 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
718 stderr=efhandle)
719 except OSError:
720 os.close(ifhandle)
721 os.remove(ifname)
722 os.close(ofhandle)
723 os.remove(ofname)
724 os.close(efhandle)
725 os.remove(efname)
726 self.assertFalse(os.path.exists(ifname))
727 self.assertFalse(os.path.exists(ofname))
728 self.assertFalse(os.path.exists(efname))
729
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200730 def test_communicate_epipe(self):
731 # Issue 10963: communicate() should hide EPIPE
732 p = subprocess.Popen([sys.executable, "-c", 'pass'],
733 stdin=subprocess.PIPE,
734 stdout=subprocess.PIPE,
735 stderr=subprocess.PIPE)
736 self.addCleanup(p.stdout.close)
737 self.addCleanup(p.stderr.close)
738 self.addCleanup(p.stdin.close)
739 p.communicate(b"x" * 2**20)
740
741 def test_communicate_epipe_only_stdin(self):
742 # Issue 10963: communicate() should hide EPIPE
743 p = subprocess.Popen([sys.executable, "-c", 'pass'],
744 stdin=subprocess.PIPE)
745 self.addCleanup(p.stdin.close)
746 time.sleep(2)
747 p.communicate(b"x" * 2**20)
748
Tim Peterse718f612004-10-12 21:51:32 +0000749
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000750# context manager
751class _SuppressCoreFiles(object):
752 """Try to prevent core files from being created."""
753 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000754
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000755 def __enter__(self):
756 """Try to save previous ulimit, then set it to (0, 0)."""
757 try:
758 import resource
759 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
760 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
761 except (ImportError, ValueError, resource.error):
762 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000763
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000764 if sys.platform == 'darwin':
765 # Check if the 'Crash Reporter' on OSX was configured
766 # in 'Developer' mode and warn that it will get triggered
767 # when it is.
768 #
769 # This assumes that this context manager is used in tests
770 # that might trigger the next manager.
771 value = subprocess.Popen(['/usr/bin/defaults', 'read',
772 'com.apple.CrashReporter', 'DialogType'],
773 stdout=subprocess.PIPE).communicate()[0]
774 if value.strip() == b'developer':
775 print("this tests triggers the Crash Reporter, "
776 "that is intentional", end='')
777 sys.stdout.flush()
778
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000779 def __exit__(self, *args):
780 """Return core file behavior to default."""
781 if self.old_limit is None:
782 return
783 try:
784 import resource
785 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
786 except (ImportError, ValueError, resource.error):
787 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000788
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000789
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000790@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000791class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000792
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000793 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000794 nonexistent_dir = "/_this/pa.th/does/not/exist"
795 try:
796 os.chdir(nonexistent_dir)
797 except OSError as e:
798 # This avoids hard coding the errno value or the OS perror()
799 # string and instead capture the exception that we want to see
800 # below for comparison.
801 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000802 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000803 else:
804 self.fail("chdir to nonexistant directory %s succeeded." %
805 nonexistent_dir)
806
807 # Error in the child re-raised in the parent.
808 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000809 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000810 cwd=nonexistent_dir)
811 except OSError as e:
812 # Test that the child process chdir failure actually makes
813 # it up to the parent process as the correct exception.
814 self.assertEqual(desired_exception.errno, e.errno)
815 self.assertEqual(desired_exception.strerror, e.strerror)
816 else:
817 self.fail("Expected OSError: %s" % desired_exception)
818
819 def test_restore_signals(self):
820 # Code coverage for both values of restore_signals to make sure it
821 # at least does not blow up.
822 # A test for behavior would be complex. Contributions welcome.
823 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
824 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
825
826 def test_start_new_session(self):
827 # For code coverage of calling setsid(). We don't care if we get an
828 # EPERM error from it depending on the test execution environment, that
829 # still indicates that it was called.
830 try:
831 output = subprocess.check_output(
832 [sys.executable, "-c",
833 "import os; print(os.getpgid(os.getpid()))"],
834 start_new_session=True)
835 except OSError as e:
836 if e.errno != errno.EPERM:
837 raise
838 else:
839 parent_pgid = os.getpgid(os.getpid())
840 child_pgid = int(output)
841 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000842
843 def test_run_abort(self):
844 # returncode handles signal termination
845 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000846 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000847 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000848 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000849 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000850
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000851 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000852 # DISCLAIMER: Setting environment variables is *not* a good use
853 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000854 p = subprocess.Popen([sys.executable, "-c",
855 'import sys,os;'
856 'sys.stdout.write(os.getenv("FRUIT"))'],
857 stdout=subprocess.PIPE,
858 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000859 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000860 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000861
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000862 def test_preexec_exception(self):
863 def raise_it():
864 raise ValueError("What if two swallows carried a coconut?")
865 try:
866 p = subprocess.Popen([sys.executable, "-c", ""],
867 preexec_fn=raise_it)
868 except RuntimeError as e:
869 self.assertTrue(
870 subprocess._posixsubprocess,
871 "Expected a ValueError from the preexec_fn")
872 except ValueError as e:
873 self.assertIn("coconut", e.args[0])
874 else:
875 self.fail("Exception raised by preexec_fn did not make it "
876 "to the parent process.")
877
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000878 @unittest.skipUnless(gc, "Requires a gc module.")
879 def test_preexec_gc_module_failure(self):
880 # This tests the code that disables garbage collection if the child
881 # process will execute any Python.
882 def raise_runtime_error():
883 raise RuntimeError("this shouldn't escape")
884 enabled = gc.isenabled()
885 orig_gc_disable = gc.disable
886 orig_gc_isenabled = gc.isenabled
887 try:
888 gc.disable()
889 self.assertFalse(gc.isenabled())
890 subprocess.call([sys.executable, '-c', ''],
891 preexec_fn=lambda: None)
892 self.assertFalse(gc.isenabled(),
893 "Popen enabled gc when it shouldn't.")
894
895 gc.enable()
896 self.assertTrue(gc.isenabled())
897 subprocess.call([sys.executable, '-c', ''],
898 preexec_fn=lambda: None)
899 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
900
901 gc.disable = raise_runtime_error
902 self.assertRaises(RuntimeError, subprocess.Popen,
903 [sys.executable, '-c', ''],
904 preexec_fn=lambda: None)
905
906 del gc.isenabled # force an AttributeError
907 self.assertRaises(AttributeError, subprocess.Popen,
908 [sys.executable, '-c', ''],
909 preexec_fn=lambda: None)
910 finally:
911 gc.disable = orig_gc_disable
912 gc.isenabled = orig_gc_isenabled
913 if not enabled:
914 gc.disable()
915
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000916 def test_args_string(self):
917 # args is a string
918 fd, fname = mkstemp()
919 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000920 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000921 fobj.write("#!/bin/sh\n")
922 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
923 sys.executable)
924 os.chmod(fname, 0o700)
925 p = subprocess.Popen(fname)
926 p.wait()
927 os.remove(fname)
928 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000929
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000930 def test_invalid_args(self):
931 # invalid arguments should raise ValueError
932 self.assertRaises(ValueError, subprocess.call,
933 [sys.executable, "-c",
934 "import sys; sys.exit(47)"],
935 startupinfo=47)
936 self.assertRaises(ValueError, subprocess.call,
937 [sys.executable, "-c",
938 "import sys; sys.exit(47)"],
939 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000940
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000941 def test_shell_sequence(self):
942 # Run command through the shell (sequence)
943 newenv = os.environ.copy()
944 newenv["FRUIT"] = "apple"
945 p = subprocess.Popen(["echo $FRUIT"], shell=1,
946 stdout=subprocess.PIPE,
947 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000948 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000949 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000950
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000951 def test_shell_string(self):
952 # Run command through the shell (string)
953 newenv = os.environ.copy()
954 newenv["FRUIT"] = "apple"
955 p = subprocess.Popen("echo $FRUIT", shell=1,
956 stdout=subprocess.PIPE,
957 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000958 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000959 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +0000960
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000961 def test_call_string(self):
962 # call() function with string argument on UNIX
963 fd, fname = mkstemp()
964 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000965 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000966 fobj.write("#!/bin/sh\n")
967 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
968 sys.executable)
969 os.chmod(fname, 0o700)
970 rc = subprocess.call(fname)
971 os.remove(fname)
972 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +0000973
Stefan Krah9542cc62010-07-19 14:20:53 +0000974 def test_specific_shell(self):
975 # Issue #9265: Incorrect name passed as arg[0].
976 shells = []
977 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
978 for name in ['bash', 'ksh']:
979 sh = os.path.join(prefix, name)
980 if os.path.isfile(sh):
981 shells.append(sh)
982 if not shells: # Will probably work for any shell but csh.
983 self.skipTest("bash or ksh required for this test")
984 sh = '/bin/sh'
985 if os.path.isfile(sh) and not os.path.islink(sh):
986 # Test will fail if /bin/sh is a symlink to csh.
987 shells.append(sh)
988 for sh in shells:
989 p = subprocess.Popen("echo $0", executable=sh, shell=True,
990 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000991 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +0000992 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
993
Florent Xicluna4886d242010-03-08 13:27:26 +0000994 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +0000995 # Do not inherit file handles from the parent.
996 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +0000997 p = subprocess.Popen([sys.executable, "-c", """if 1:
998 import sys, time
999 sys.stdout.write('x\\n')
1000 sys.stdout.flush()
1001 time.sleep(30)
1002 """],
1003 close_fds=True,
1004 stdin=subprocess.PIPE,
1005 stdout=subprocess.PIPE,
1006 stderr=subprocess.PIPE)
1007 # Wait for the interpreter to be completely initialized before
1008 # sending any signal.
1009 p.stdout.read(1)
1010 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001011 return p
1012
1013 def test_send_signal(self):
1014 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001015 _, stderr = p.communicate()
1016 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001017 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001018
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001019 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001020 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001021 _, stderr = p.communicate()
1022 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001023 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001024
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001025 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001026 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001027 _, stderr = p.communicate()
1028 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001029 self.assertEqual(p.wait(), -signal.SIGTERM)
1030
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001031 def check_close_std_fds(self, fds):
1032 # Issue #9905: test that subprocess pipes still work properly with
1033 # some standard fds closed
1034 stdin = 0
1035 newfds = []
1036 for a in fds:
1037 b = os.dup(a)
1038 newfds.append(b)
1039 if a == 0:
1040 stdin = b
1041 try:
1042 for fd in fds:
1043 os.close(fd)
1044 out, err = subprocess.Popen([sys.executable, "-c",
1045 'import sys;'
1046 'sys.stdout.write("apple");'
1047 'sys.stdout.flush();'
1048 'sys.stderr.write("orange")'],
1049 stdin=stdin,
1050 stdout=subprocess.PIPE,
1051 stderr=subprocess.PIPE).communicate()
1052 err = support.strip_python_stderr(err)
1053 self.assertEqual((out, err), (b'apple', b'orange'))
1054 finally:
1055 for b, a in zip(newfds, fds):
1056 os.dup2(b, a)
1057 for b in newfds:
1058 os.close(b)
1059
1060 def test_close_fd_0(self):
1061 self.check_close_std_fds([0])
1062
1063 def test_close_fd_1(self):
1064 self.check_close_std_fds([1])
1065
1066 def test_close_fd_2(self):
1067 self.check_close_std_fds([2])
1068
1069 def test_close_fds_0_1(self):
1070 self.check_close_std_fds([0, 1])
1071
1072 def test_close_fds_0_2(self):
1073 self.check_close_std_fds([0, 2])
1074
1075 def test_close_fds_1_2(self):
1076 self.check_close_std_fds([1, 2])
1077
1078 def test_close_fds_0_1_2(self):
1079 # Issue #10806: test that subprocess pipes still work properly with
1080 # all standard fds closed.
1081 self.check_close_std_fds([0, 1, 2])
1082
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001083 def test_remapping_std_fds(self):
1084 # open up some temporary files
1085 temps = [mkstemp() for i in range(3)]
1086 try:
1087 temp_fds = [fd for fd, fname in temps]
1088
1089 # unlink the files -- we won't need to reopen them
1090 for fd, fname in temps:
1091 os.unlink(fname)
1092
1093 # write some data to what will become stdin, and rewind
1094 os.write(temp_fds[1], b"STDIN")
1095 os.lseek(temp_fds[1], 0, 0)
1096
1097 # move the standard file descriptors out of the way
1098 saved_fds = [os.dup(fd) for fd in range(3)]
1099 try:
1100 # duplicate the file objects over the standard fd's
1101 for fd, temp_fd in enumerate(temp_fds):
1102 os.dup2(temp_fd, fd)
1103
1104 # now use those files in the "wrong" order, so that subprocess
1105 # has to rearrange them in the child
1106 p = subprocess.Popen([sys.executable, "-c",
1107 'import sys; got = sys.stdin.read();'
1108 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1109 stdin=temp_fds[1],
1110 stdout=temp_fds[2],
1111 stderr=temp_fds[0])
1112 p.wait()
1113 finally:
1114 # restore the original fd's underneath sys.stdin, etc.
1115 for std, saved in enumerate(saved_fds):
1116 os.dup2(saved, std)
1117 os.close(saved)
1118
1119 for fd in temp_fds:
1120 os.lseek(fd, 0, 0)
1121
1122 out = os.read(temp_fds[2], 1024)
1123 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1124 self.assertEqual(out, b"got STDIN")
1125 self.assertEqual(err, b"err")
1126
1127 finally:
1128 for fd in temp_fds:
1129 os.close(fd)
1130
Victor Stinner13bb71c2010-04-23 21:41:56 +00001131 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001132 def prepare():
1133 raise ValueError("surrogate:\uDCff")
1134
1135 try:
1136 subprocess.call(
1137 [sys.executable, "-c", "pass"],
1138 preexec_fn=prepare)
1139 except ValueError as err:
1140 # Pure Python implementations keeps the message
1141 self.assertIsNone(subprocess._posixsubprocess)
1142 self.assertEqual(str(err), "surrogate:\uDCff")
1143 except RuntimeError as err:
1144 # _posixsubprocess uses a default message
1145 self.assertIsNotNone(subprocess._posixsubprocess)
1146 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1147 else:
1148 self.fail("Expected ValueError or RuntimeError")
1149
Victor Stinner13bb71c2010-04-23 21:41:56 +00001150 def test_undecodable_env(self):
1151 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001152 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001153 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001154 env = os.environ.copy()
1155 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001156 # Use C locale to get ascii for the locale encoding to force
1157 # surrogate-escaping of \xFF in the child process; otherwise it can
1158 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001159 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001160 stdout = subprocess.check_output(
1161 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001162 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001163 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001164 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001165
1166 # test bytes
1167 key = key.encode("ascii", "surrogateescape")
1168 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001169 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001170 env = os.environ.copy()
1171 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001172 stdout = subprocess.check_output(
1173 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001174 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001175 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001176 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001177
Victor Stinnerb745a742010-05-18 17:17:23 +00001178 def test_bytes_program(self):
1179 abs_program = os.fsencode(sys.executable)
1180 path, program = os.path.split(sys.executable)
1181 program = os.fsencode(program)
1182
1183 # absolute bytes path
1184 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001185 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001186
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001187 # absolute bytes path as a string
1188 cmd = b"'" + abs_program + b"' -c pass"
1189 exitcode = subprocess.call(cmd, shell=True)
1190 self.assertEqual(exitcode, 0)
1191
Victor Stinnerb745a742010-05-18 17:17:23 +00001192 # bytes program, unicode PATH
1193 env = os.environ.copy()
1194 env["PATH"] = path
1195 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001196 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001197
1198 # bytes program, bytes PATH
1199 envb = os.environb.copy()
1200 envb[b"PATH"] = os.fsencode(path)
1201 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001202 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001203
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001204 def test_pipe_cloexec(self):
1205 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1206 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1207
1208 p1 = subprocess.Popen([sys.executable, sleeper],
1209 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1210 stderr=subprocess.PIPE, close_fds=False)
1211
1212 self.addCleanup(p1.communicate, b'')
1213
1214 p2 = subprocess.Popen([sys.executable, fd_status],
1215 stdout=subprocess.PIPE, close_fds=False)
1216
1217 output, error = p2.communicate()
1218 result_fds = set(map(int, output.split(b',')))
1219 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1220 p1.stderr.fileno()])
1221
1222 self.assertFalse(result_fds & unwanted_fds,
1223 "Expected no fds from %r to be open in child, "
1224 "found %r" %
1225 (unwanted_fds, result_fds & unwanted_fds))
1226
1227 def test_pipe_cloexec_real_tools(self):
1228 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1229 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1230
1231 subdata = b'zxcvbn'
1232 data = subdata * 4 + b'\n'
1233
1234 p1 = subprocess.Popen([sys.executable, qcat],
1235 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1236 close_fds=False)
1237
1238 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1239 stdin=p1.stdout, stdout=subprocess.PIPE,
1240 close_fds=False)
1241
1242 self.addCleanup(p1.wait)
1243 self.addCleanup(p2.wait)
1244 self.addCleanup(p1.terminate)
1245 self.addCleanup(p2.terminate)
1246
1247 p1.stdin.write(data)
1248 p1.stdin.close()
1249
1250 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1251
1252 self.assertTrue(readfiles, "The child hung")
1253 self.assertEqual(p2.stdout.read(), data)
1254
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001255 p1.stdout.close()
1256 p2.stdout.close()
1257
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001258 def test_close_fds(self):
1259 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1260
1261 fds = os.pipe()
1262 self.addCleanup(os.close, fds[0])
1263 self.addCleanup(os.close, fds[1])
1264
1265 open_fds = set(fds)
1266
1267 p = subprocess.Popen([sys.executable, fd_status],
1268 stdout=subprocess.PIPE, close_fds=False)
1269 output, ignored = p.communicate()
1270 remaining_fds = set(map(int, output.split(b',')))
1271
1272 self.assertEqual(remaining_fds & open_fds, open_fds,
1273 "Some fds were closed")
1274
1275 p = subprocess.Popen([sys.executable, fd_status],
1276 stdout=subprocess.PIPE, close_fds=True)
1277 output, ignored = p.communicate()
1278 remaining_fds = set(map(int, output.split(b',')))
1279
1280 self.assertFalse(remaining_fds & open_fds,
1281 "Some fds were left open")
1282 self.assertIn(1, remaining_fds, "Subprocess failed")
1283
Victor Stinner88701e22011-06-01 13:13:04 +02001284 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1285 # descriptor of a pipe closed in the parent process is valid in the
1286 # child process according to fstat(), but the mode of the file
1287 # descriptor is invalid, and read or write raise an error.
1288 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001289 def test_pass_fds(self):
1290 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1291
1292 open_fds = set()
1293
1294 for x in range(5):
1295 fds = os.pipe()
1296 self.addCleanup(os.close, fds[0])
1297 self.addCleanup(os.close, fds[1])
1298 open_fds.update(fds)
1299
1300 for fd in open_fds:
1301 p = subprocess.Popen([sys.executable, fd_status],
1302 stdout=subprocess.PIPE, close_fds=True,
1303 pass_fds=(fd, ))
1304 output, ignored = p.communicate()
1305
1306 remaining_fds = set(map(int, output.split(b',')))
1307 to_be_closed = open_fds - {fd}
1308
1309 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1310 self.assertFalse(remaining_fds & to_be_closed,
1311 "fd to be closed passed")
1312
1313 # pass_fds overrides close_fds with a warning.
1314 with self.assertWarns(RuntimeWarning) as context:
1315 self.assertFalse(subprocess.call(
1316 [sys.executable, "-c", "import sys; sys.exit(0)"],
1317 close_fds=False, pass_fds=(fd, )))
1318 self.assertIn('overriding close_fds', str(context.warning))
1319
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001320 def test_stdout_stdin_are_single_inout_fd(self):
1321 with io.open(os.devnull, "r+") as inout:
1322 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1323 stdout=inout, stdin=inout)
1324 p.wait()
1325
1326 def test_stdout_stderr_are_single_inout_fd(self):
1327 with io.open(os.devnull, "r+") as inout:
1328 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1329 stdout=inout, stderr=inout)
1330 p.wait()
1331
1332 def test_stderr_stdin_are_single_inout_fd(self):
1333 with io.open(os.devnull, "r+") as inout:
1334 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1335 stderr=inout, stdin=inout)
1336 p.wait()
1337
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001338 def test_wait_when_sigchild_ignored(self):
1339 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1340 sigchild_ignore = support.findfile("sigchild_ignore.py",
1341 subdir="subprocessdata")
1342 p = subprocess.Popen([sys.executable, sigchild_ignore],
1343 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1344 stdout, stderr = p.communicate()
1345 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001346 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001347 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001348
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001349 def test_select_unbuffered(self):
1350 # Issue #11459: bufsize=0 should really set the pipes as
1351 # unbuffered (and therefore let select() work properly).
1352 select = support.import_module("select")
1353 p = subprocess.Popen([sys.executable, "-c",
1354 'import sys;'
1355 'sys.stdout.write("apple")'],
1356 stdout=subprocess.PIPE,
1357 bufsize=0)
1358 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001359 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001360 try:
1361 self.assertEqual(f.read(4), b"appl")
1362 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1363 finally:
1364 p.wait()
1365
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001366
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001367@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001368class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001369
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001370 def test_startupinfo(self):
1371 # startupinfo argument
1372 # We uses hardcoded constants, because we do not want to
1373 # depend on win32all.
1374 STARTF_USESHOWWINDOW = 1
1375 SW_MAXIMIZE = 3
1376 startupinfo = subprocess.STARTUPINFO()
1377 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1378 startupinfo.wShowWindow = SW_MAXIMIZE
1379 # Since Python is a console process, it won't be affected
1380 # by wShowWindow, but the argument should be silently
1381 # ignored
1382 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001383 startupinfo=startupinfo)
1384
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001385 def test_creationflags(self):
1386 # creationflags argument
1387 CREATE_NEW_CONSOLE = 16
1388 sys.stderr.write(" a DOS box should flash briefly ...\n")
1389 subprocess.call(sys.executable +
1390 ' -c "import time; time.sleep(0.25)"',
1391 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001392
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001393 def test_invalid_args(self):
1394 # invalid arguments should raise ValueError
1395 self.assertRaises(ValueError, subprocess.call,
1396 [sys.executable, "-c",
1397 "import sys; sys.exit(47)"],
1398 preexec_fn=lambda: 1)
1399 self.assertRaises(ValueError, subprocess.call,
1400 [sys.executable, "-c",
1401 "import sys; sys.exit(47)"],
1402 stdout=subprocess.PIPE,
1403 close_fds=True)
1404
1405 def test_close_fds(self):
1406 # close file descriptors
1407 rc = subprocess.call([sys.executable, "-c",
1408 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001409 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001410 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001411
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001412 def test_shell_sequence(self):
1413 # Run command through the shell (sequence)
1414 newenv = os.environ.copy()
1415 newenv["FRUIT"] = "physalis"
1416 p = subprocess.Popen(["set"], shell=1,
1417 stdout=subprocess.PIPE,
1418 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001419 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001420 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001421
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001422 def test_shell_string(self):
1423 # Run command through the shell (string)
1424 newenv = os.environ.copy()
1425 newenv["FRUIT"] = "physalis"
1426 p = subprocess.Popen("set", shell=1,
1427 stdout=subprocess.PIPE,
1428 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001429 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001430 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001431
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001432 def test_call_string(self):
1433 # call() function with string argument on Windows
1434 rc = subprocess.call(sys.executable +
1435 ' -c "import sys; sys.exit(47)"')
1436 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001437
Florent Xicluna4886d242010-03-08 13:27:26 +00001438 def _kill_process(self, method, *args):
1439 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001440 p = subprocess.Popen([sys.executable, "-c", """if 1:
1441 import sys, time
1442 sys.stdout.write('x\\n')
1443 sys.stdout.flush()
1444 time.sleep(30)
1445 """],
1446 stdin=subprocess.PIPE,
1447 stdout=subprocess.PIPE,
1448 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001449 self.addCleanup(p.stdout.close)
1450 self.addCleanup(p.stderr.close)
1451 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001452 # Wait for the interpreter to be completely initialized before
1453 # sending any signal.
1454 p.stdout.read(1)
1455 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001456 _, stderr = p.communicate()
1457 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001458 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001459 self.assertNotEqual(returncode, 0)
1460
1461 def test_send_signal(self):
1462 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001463
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001464 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001465 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001466
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001467 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001468 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001469
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001470
Brett Cannona23810f2008-05-26 19:04:21 +00001471# The module says:
1472# "NB This only works (and is only relevant) for UNIX."
1473#
1474# Actually, getoutput should work on any platform with an os.popen, but
1475# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001476@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001477class CommandTests(unittest.TestCase):
1478 def test_getoutput(self):
1479 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1480 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1481 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001482
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001483 # we use mkdtemp in the next line to create an empty directory
1484 # under our exclusive control; from that, we can invent a pathname
1485 # that we _know_ won't exist. This is guaranteed to fail.
1486 dir = None
1487 try:
1488 dir = tempfile.mkdtemp()
1489 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001490
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001491 status, output = subprocess.getstatusoutput('cat ' + name)
1492 self.assertNotEqual(status, 0)
1493 finally:
1494 if dir is not None:
1495 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001496
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001497
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001498@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1499 "poll system call not supported")
1500class ProcessTestCaseNoPoll(ProcessTestCase):
1501 def setUp(self):
1502 subprocess._has_poll = False
1503 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001504
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001505 def tearDown(self):
1506 subprocess._has_poll = True
1507 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001508
1509
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001510class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001511 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001512 def test_eintr_retry_call(self):
1513 record_calls = []
1514 def fake_os_func(*args):
1515 record_calls.append(args)
1516 if len(record_calls) == 2:
1517 raise OSError(errno.EINTR, "fake interrupted system call")
1518 return tuple(reversed(args))
1519
1520 self.assertEqual((999, 256),
1521 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1522 self.assertEqual([(256, 999)], record_calls)
1523 # This time there will be an EINTR so it will loop once.
1524 self.assertEqual((666,),
1525 subprocess._eintr_retry_call(fake_os_func, 666))
1526 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1527
1528
Tim Golden126c2962010-08-11 14:20:40 +00001529@unittest.skipUnless(mswindows, "Windows-specific tests")
1530class CommandsWithSpaces (BaseTestCase):
1531
1532 def setUp(self):
1533 super().setUp()
1534 f, fname = mkstemp(".py", "te st")
1535 self.fname = fname.lower ()
1536 os.write(f, b"import sys;"
1537 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1538 )
1539 os.close(f)
1540
1541 def tearDown(self):
1542 os.remove(self.fname)
1543 super().tearDown()
1544
1545 def with_spaces(self, *args, **kwargs):
1546 kwargs['stdout'] = subprocess.PIPE
1547 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001548 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001549 self.assertEqual(
1550 p.stdout.read ().decode("mbcs"),
1551 "2 [%r, 'ab cd']" % self.fname
1552 )
1553
1554 def test_shell_string_with_spaces(self):
1555 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001556 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1557 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001558
1559 def test_shell_sequence_with_spaces(self):
1560 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001561 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001562
1563 def test_noshell_string_with_spaces(self):
1564 # call() function with string argument with spaces on Windows
1565 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1566 "ab cd"))
1567
1568 def test_noshell_sequence_with_spaces(self):
1569 # call() function with sequence argument with spaces on Windows
1570 self.with_spaces([sys.executable, self.fname, "ab cd"])
1571
Brian Curtin79cdb662010-12-03 02:46:02 +00001572
1573class ContextManagerTests(ProcessTestCase):
1574
1575 def test_pipe(self):
1576 with subprocess.Popen([sys.executable, "-c",
1577 "import sys;"
1578 "sys.stdout.write('stdout');"
1579 "sys.stderr.write('stderr');"],
1580 stdout=subprocess.PIPE,
1581 stderr=subprocess.PIPE) as proc:
1582 self.assertEqual(proc.stdout.read(), b"stdout")
1583 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1584
1585 self.assertTrue(proc.stdout.closed)
1586 self.assertTrue(proc.stderr.closed)
1587
1588 def test_returncode(self):
1589 with subprocess.Popen([sys.executable, "-c",
1590 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07001591 pass
1592 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00001593 self.assertEqual(proc.returncode, 100)
1594
1595 def test_communicate_stdin(self):
1596 with subprocess.Popen([sys.executable, "-c",
1597 "import sys;"
1598 "sys.exit(sys.stdin.read() == 'context')"],
1599 stdin=subprocess.PIPE) as proc:
1600 proc.communicate(b"context")
1601 self.assertEqual(proc.returncode, 1)
1602
1603 def test_invalid_args(self):
1604 with self.assertRaises(EnvironmentError) as c:
1605 with subprocess.Popen(['nonexisting_i_hope'],
1606 stdout=subprocess.PIPE,
1607 stderr=subprocess.PIPE) as proc:
1608 pass
1609
1610 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1611 raise c.exception
1612
1613
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001614def test_main():
1615 unit_tests = (ProcessTestCase,
1616 POSIXProcessTestCase,
1617 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001618 CommandTests,
1619 ProcessTestCaseNoPoll,
1620 HelperFunctionTests,
1621 CommandsWithSpaces,
1622 ContextManagerTests)
1623
1624 support.run_unittest(*unit_tests)
1625 support.reap_children()
1626
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001627if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001628 unittest.main()