blob: b52d8e8f84abd3c53a8f9c6ec9bf908960471418 [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",
Victor Stinner149b1c72011-06-06 23:43:02 +0200130 "import sys, time\n"
131 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400132 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200133 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400134 # Some heavily loaded buildbots (sparc Debian 3.x) require
135 # this much time to start and print.
136 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400137 self.fail("Expected TimeoutExpired.")
138 self.assertEqual(c.exception.output, b'BDFL')
139
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000140 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000141 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000142 newenv = os.environ.copy()
143 newenv["FRUIT"] = "banana"
144 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000145 'import sys, os;'
146 'sys.exit(os.getenv("FRUIT")=="banana")'],
147 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000148 self.assertEqual(rc, 1)
149
Victor Stinner87b9bc32011-06-01 00:57:47 +0200150 def test_invalid_args(self):
151 # Popen() called with invalid arguments should raise TypeError
152 # but Popen.__del__ should not complain (issue #12085)
153 with support.captured_stderr() as s:
154 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
155 argcount = subprocess.Popen.__init__.__code__.co_argcount
156 too_many_args = [0] * (argcount + 1)
157 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
158 self.assertEqual(s.getvalue(), '')
159
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000160 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000161 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000162 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000163 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000164 self.addCleanup(p.stdout.close)
165 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000166 p.wait()
167 self.assertEqual(p.stdin, None)
168
169 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000170 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000171 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000172 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000173 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000174 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000175 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000176 self.addCleanup(p.stdin.close)
177 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000178 p.wait()
179 self.assertEqual(p.stdout, None)
180
181 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000182 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000183 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000184 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000185 self.addCleanup(p.stdout.close)
186 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000187 p.wait()
188 self.assertEqual(p.stderr, None)
189
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000190 def test_executable_with_cwd(self):
Florent Xicluna1d1ab972010-03-11 01:53:10 +0000191 python_dir = os.path.dirname(os.path.realpath(sys.executable))
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000192 p = subprocess.Popen(["somethingyoudonthave", "-c",
193 "import sys; sys.exit(47)"],
194 executable=sys.executable, cwd=python_dir)
195 p.wait()
196 self.assertEqual(p.returncode, 47)
197
198 @unittest.skipIf(sysconfig.is_python_build(),
199 "need an installed Python. See #7774")
200 def test_executable_without_cwd(self):
201 # For a normal installation, it should work without 'cwd'
202 # argument. For test runs in the build directory, see #7774.
203 p = subprocess.Popen(["somethingyoudonthave", "-c",
204 "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000205 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000206 p.wait()
207 self.assertEqual(p.returncode, 47)
208
209 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000210 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000211 p = subprocess.Popen([sys.executable, "-c",
212 'import sys; sys.exit(sys.stdin.read() == "pear")'],
213 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000214 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000215 p.stdin.close()
216 p.wait()
217 self.assertEqual(p.returncode, 1)
218
219 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000220 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000221 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000222 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000223 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000224 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000225 os.lseek(d, 0, 0)
226 p = subprocess.Popen([sys.executable, "-c",
227 'import sys; sys.exit(sys.stdin.read() == "pear")'],
228 stdin=d)
229 p.wait()
230 self.assertEqual(p.returncode, 1)
231
232 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000233 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000234 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000235 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000236 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000237 tf.seek(0)
238 p = subprocess.Popen([sys.executable, "-c",
239 'import sys; sys.exit(sys.stdin.read() == "pear")'],
240 stdin=tf)
241 p.wait()
242 self.assertEqual(p.returncode, 1)
243
244 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000245 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000246 p = subprocess.Popen([sys.executable, "-c",
247 'import sys; sys.stdout.write("orange")'],
248 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000249 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000250 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000251
252 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000253 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000254 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000255 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000256 d = tf.fileno()
257 p = subprocess.Popen([sys.executable, "-c",
258 'import sys; sys.stdout.write("orange")'],
259 stdout=d)
260 p.wait()
261 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000262 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000263
264 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000265 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000266 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000267 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000268 p = subprocess.Popen([sys.executable, "-c",
269 'import sys; sys.stdout.write("orange")'],
270 stdout=tf)
271 p.wait()
272 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000273 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000274
275 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000276 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000277 p = subprocess.Popen([sys.executable, "-c",
278 'import sys; sys.stderr.write("strawberry")'],
279 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000280 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000281 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000282
283 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000284 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000285 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000286 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000287 d = tf.fileno()
288 p = subprocess.Popen([sys.executable, "-c",
289 'import sys; sys.stderr.write("strawberry")'],
290 stderr=d)
291 p.wait()
292 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000293 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000294
295 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000296 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000297 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000298 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000299 p = subprocess.Popen([sys.executable, "-c",
300 'import sys; sys.stderr.write("strawberry")'],
301 stderr=tf)
302 p.wait()
303 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000304 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000305
306 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000307 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000308 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000309 'import sys;'
310 'sys.stdout.write("apple");'
311 'sys.stdout.flush();'
312 'sys.stderr.write("orange")'],
313 stdout=subprocess.PIPE,
314 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000315 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000316 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000317
318 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000319 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000320 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000321 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000322 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000323 'import sys;'
324 'sys.stdout.write("apple");'
325 'sys.stdout.flush();'
326 'sys.stderr.write("orange")'],
327 stdout=tf,
328 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000329 p.wait()
330 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000331 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000332
Thomas Wouters89f507f2006-12-13 04:49:30 +0000333 def test_stdout_filedes_of_stdout(self):
334 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000335 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000336 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000337 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000338
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200339 def test_stdout_devnull(self):
340 p = subprocess.Popen([sys.executable, "-c",
341 'for i in range(10240):'
342 'print("x" * 1024)'],
343 stdout=subprocess.DEVNULL)
344 p.wait()
345 self.assertEqual(p.stdout, None)
346
347 def test_stderr_devnull(self):
348 p = subprocess.Popen([sys.executable, "-c",
349 'import sys\n'
350 'for i in range(10240):'
351 'sys.stderr.write("x" * 1024)'],
352 stderr=subprocess.DEVNULL)
353 p.wait()
354 self.assertEqual(p.stderr, None)
355
356 def test_stdin_devnull(self):
357 p = subprocess.Popen([sys.executable, "-c",
358 'import sys;'
359 'sys.stdin.read(1)'],
360 stdin=subprocess.DEVNULL)
361 p.wait()
362 self.assertEqual(p.stdin, None)
363
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000364 def test_cwd(self):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000365 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000366 # We cannot use os.path.realpath to canonicalize the path,
367 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
368 cwd = os.getcwd()
369 os.chdir(tmpdir)
370 tmpdir = os.getcwd()
371 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000372 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000373 'import sys,os;'
374 'sys.stdout.write(os.getcwd())'],
375 stdout=subprocess.PIPE,
376 cwd=tmpdir)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000377 self.addCleanup(p.stdout.close)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000378 normcase = os.path.normcase
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000379 self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
380 normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000381
382 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000383 newenv = os.environ.copy()
384 newenv["FRUIT"] = "orange"
385 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000386 'import sys,os;'
387 'sys.stdout.write(os.getenv("FRUIT"))'],
388 stdout=subprocess.PIPE,
389 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000390 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000391 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000392
Peter Astrandcbac93c2005-03-03 20:24:28 +0000393 def test_communicate_stdin(self):
394 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000395 'import sys;'
396 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000397 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000398 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000399 self.assertEqual(p.returncode, 1)
400
401 def test_communicate_stdout(self):
402 p = subprocess.Popen([sys.executable, "-c",
403 'import sys; sys.stdout.write("pineapple")'],
404 stdout=subprocess.PIPE)
405 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000406 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000407 self.assertEqual(stderr, None)
408
409 def test_communicate_stderr(self):
410 p = subprocess.Popen([sys.executable, "-c",
411 'import sys; sys.stderr.write("pineapple")'],
412 stderr=subprocess.PIPE)
413 (stdout, stderr) = p.communicate()
414 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000415 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000416
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000417 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000418 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000419 'import sys,os;'
420 'sys.stderr.write("pineapple");'
421 'sys.stdout.write(sys.stdin.read())'],
422 stdin=subprocess.PIPE,
423 stdout=subprocess.PIPE,
424 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000425 self.addCleanup(p.stdout.close)
426 self.addCleanup(p.stderr.close)
427 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000428 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000429 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000430 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000431
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400432 def test_communicate_timeout(self):
433 p = subprocess.Popen([sys.executable, "-c",
434 'import sys,os,time;'
435 'sys.stderr.write("pineapple\\n");'
436 'time.sleep(1);'
437 'sys.stderr.write("pear\\n");'
438 'sys.stdout.write(sys.stdin.read())'],
439 universal_newlines=True,
440 stdin=subprocess.PIPE,
441 stdout=subprocess.PIPE,
442 stderr=subprocess.PIPE)
443 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
444 timeout=0.3)
445 # Make sure we can keep waiting for it, and that we get the whole output
446 # after it completes.
447 (stdout, stderr) = p.communicate()
448 self.assertEqual(stdout, "banana")
449 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
450
451 def test_communicate_timeout_large_ouput(self):
452 # Test a expring timeout while the child is outputting lots of data.
453 p = subprocess.Popen([sys.executable, "-c",
454 'import sys,os,time;'
455 'sys.stdout.write("a" * (64 * 1024));'
456 'time.sleep(0.2);'
457 'sys.stdout.write("a" * (64 * 1024));'
458 'time.sleep(0.2);'
459 'sys.stdout.write("a" * (64 * 1024));'
460 'time.sleep(0.2);'
461 'sys.stdout.write("a" * (64 * 1024));'],
462 stdout=subprocess.PIPE)
463 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
464 (stdout, _) = p.communicate()
465 self.assertEqual(len(stdout), 4 * 64 * 1024)
466
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000467 # Test for the fd leak reported in http://bugs.python.org/issue2791.
468 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000469 for stdin_pipe in (False, True):
470 for stdout_pipe in (False, True):
471 for stderr_pipe in (False, True):
472 options = {}
473 if stdin_pipe:
474 options['stdin'] = subprocess.PIPE
475 if stdout_pipe:
476 options['stdout'] = subprocess.PIPE
477 if stderr_pipe:
478 options['stderr'] = subprocess.PIPE
479 if not options:
480 continue
481 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
482 p.communicate()
483 if p.stdin is not None:
484 self.assertTrue(p.stdin.closed)
485 if p.stdout is not None:
486 self.assertTrue(p.stdout.closed)
487 if p.stderr is not None:
488 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000489
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000490 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000491 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000492 p = subprocess.Popen([sys.executable, "-c",
493 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000494 (stdout, stderr) = p.communicate()
495 self.assertEqual(stdout, None)
496 self.assertEqual(stderr, None)
497
498 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000499 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000500 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000501 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000502 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000503 os.close(x)
504 os.close(y)
505 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000506 'import sys,os;'
507 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200508 'sys.stderr.write("x" * %d);'
509 'sys.stdout.write(sys.stdin.read())' %
510 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000511 stdin=subprocess.PIPE,
512 stdout=subprocess.PIPE,
513 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000514 self.addCleanup(p.stdout.close)
515 self.addCleanup(p.stderr.close)
516 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200517 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000518 (stdout, stderr) = p.communicate(string_to_write)
519 self.assertEqual(stdout, string_to_write)
520
521 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000522 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000523 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000524 'import sys,os;'
525 'sys.stdout.write(sys.stdin.read())'],
526 stdin=subprocess.PIPE,
527 stdout=subprocess.PIPE,
528 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000529 self.addCleanup(p.stdout.close)
530 self.addCleanup(p.stderr.close)
531 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000532 p.stdin.write(b"banana")
533 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000534 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000535 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000536
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000537 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000538 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000539 'import sys,os;' + SETBINARY +
540 'sys.stdout.write("line1\\n");'
541 'sys.stdout.flush();'
542 'sys.stdout.write("line2\\n");'
543 'sys.stdout.flush();'
544 'sys.stdout.write("line3\\r\\n");'
545 'sys.stdout.flush();'
546 'sys.stdout.write("line4\\r");'
547 'sys.stdout.flush();'
548 'sys.stdout.write("\\nline5");'
549 'sys.stdout.flush();'
550 'sys.stdout.write("\\nline6");'],
551 stdout=subprocess.PIPE,
552 universal_newlines=1)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000553 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000554 stdout = p.stdout.read()
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000555 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000556
557 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000558 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000559 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000560 'import sys,os;' + SETBINARY +
561 'sys.stdout.write("line1\\n");'
562 'sys.stdout.flush();'
563 'sys.stdout.write("line2\\n");'
564 'sys.stdout.flush();'
565 'sys.stdout.write("line3\\r\\n");'
566 'sys.stdout.flush();'
567 'sys.stdout.write("line4\\r");'
568 'sys.stdout.flush();'
569 'sys.stdout.write("\\nline5");'
570 'sys.stdout.flush();'
571 'sys.stdout.write("\\nline6");'],
572 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
573 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000574 self.addCleanup(p.stdout.close)
575 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000576 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000577 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000578
579 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000580 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000581 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000582 max_handles = 1026 # too much for most UNIX systems
583 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000584 max_handles = 2050 # too much for (at least some) Windows setups
585 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400586 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000587 try:
588 for i in range(max_handles):
589 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400590 tmpfile = os.path.join(tmpdir, support.TESTFN)
591 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000592 except OSError as e:
593 if e.errno != errno.EMFILE:
594 raise
595 break
596 else:
597 self.skipTest("failed to reach the file descriptor limit "
598 "(tried %d)" % max_handles)
599 # Close a couple of them (should be enough for a subprocess)
600 for i in range(10):
601 os.close(handles.pop())
602 # Loop creating some subprocesses. If one of them leaks some fds,
603 # the next loop iteration will fail by reaching the max fd limit.
604 for i in range(15):
605 p = subprocess.Popen([sys.executable, "-c",
606 "import sys;"
607 "sys.stdout.write(sys.stdin.read())"],
608 stdin=subprocess.PIPE,
609 stdout=subprocess.PIPE,
610 stderr=subprocess.PIPE)
611 data = p.communicate(b"lime")[0]
612 self.assertEqual(data, b"lime")
613 finally:
614 for h in handles:
615 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400616 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000617
618 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000619 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
620 '"a b c" d e')
621 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
622 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000623 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
624 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000625 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
626 'a\\\\\\b "de fg" h')
627 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
628 'a\\\\\\"b c d')
629 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
630 '"a\\\\b c" d e')
631 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
632 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000633 self.assertEqual(subprocess.list2cmdline(['ab', '']),
634 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000635
636
637 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000638 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000639 "-c", "import time; time.sleep(1)"])
640 count = 0
641 while p.poll() is None:
642 time.sleep(0.1)
643 count += 1
644 # We expect that the poll loop probably went around about 10 times,
645 # but, based on system scheduling we can't control, it's possible
646 # poll() never returned None. It "should be" very rare that it
647 # didn't go around at least twice.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000648 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000649 # Subsequent invocations should just return the returncode
650 self.assertEqual(p.poll(), 0)
651
652
653 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000654 p = subprocess.Popen([sys.executable,
655 "-c", "import time; time.sleep(2)"])
656 self.assertEqual(p.wait(), 0)
657 # Subsequent invocations should just return the returncode
658 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000659
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400660 def test_wait_timeout(self):
661 p = subprocess.Popen([sys.executable,
Reid Kleckner93479cc2011-03-14 19:32:41 -0400662 "-c", "import time; time.sleep(0.1)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -0400663 with self.assertRaises(subprocess.TimeoutExpired) as c:
664 p.wait(timeout=0.01)
665 self.assertIn("0.01", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -0400666 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
667 # time to start.
668 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400669
Peter Astrand738131d2004-11-30 21:04:45 +0000670 def test_invalid_bufsize(self):
671 # an invalid type of the bufsize argument should raise
672 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000673 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000674 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000675
Guido van Rossum46a05a72007-06-07 21:56:45 +0000676 def test_bufsize_is_none(self):
677 # bufsize=None should be the same as bufsize=0.
678 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
679 self.assertEqual(p.wait(), 0)
680 # Again with keyword arg
681 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
682 self.assertEqual(p.wait(), 0)
683
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000684 def test_leaking_fds_on_error(self):
685 # see bug #5179: Popen leaks file descriptors to PIPEs if
686 # the child fails to execute; this will eventually exhaust
687 # the maximum number of open fds. 1024 seems a very common
688 # value for that limit, but Windows has 2048, so we loop
689 # 1024 times (each call leaked two fds).
690 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000691 # Windows raises IOError. Others raise OSError.
692 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000693 subprocess.Popen(['nonexisting_i_hope'],
694 stdout=subprocess.PIPE,
695 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400696 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400697 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000698 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000699
Victor Stinnerb3693582010-05-21 20:13:12 +0000700 def test_issue8780(self):
701 # Ensure that stdout is inherited from the parent
702 # if stdout=PIPE is not used
703 code = ';'.join((
704 'import subprocess, sys',
705 'retcode = subprocess.call('
706 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
707 'assert retcode == 0'))
708 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000709 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000710
Tim Goldenaf5ac392010-08-06 13:03:56 +0000711 def test_handles_closed_on_exception(self):
712 # If CreateProcess exits with an error, ensure the
713 # duplicate output handles are released
714 ifhandle, ifname = mkstemp()
715 ofhandle, ofname = mkstemp()
716 efhandle, efname = mkstemp()
717 try:
718 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
719 stderr=efhandle)
720 except OSError:
721 os.close(ifhandle)
722 os.remove(ifname)
723 os.close(ofhandle)
724 os.remove(ofname)
725 os.close(efhandle)
726 os.remove(efname)
727 self.assertFalse(os.path.exists(ifname))
728 self.assertFalse(os.path.exists(ofname))
729 self.assertFalse(os.path.exists(efname))
730
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200731 def test_communicate_epipe(self):
732 # Issue 10963: communicate() should hide EPIPE
733 p = subprocess.Popen([sys.executable, "-c", 'pass'],
734 stdin=subprocess.PIPE,
735 stdout=subprocess.PIPE,
736 stderr=subprocess.PIPE)
737 self.addCleanup(p.stdout.close)
738 self.addCleanup(p.stderr.close)
739 self.addCleanup(p.stdin.close)
740 p.communicate(b"x" * 2**20)
741
742 def test_communicate_epipe_only_stdin(self):
743 # Issue 10963: communicate() should hide EPIPE
744 p = subprocess.Popen([sys.executable, "-c", 'pass'],
745 stdin=subprocess.PIPE)
746 self.addCleanup(p.stdin.close)
747 time.sleep(2)
748 p.communicate(b"x" * 2**20)
749
Tim Peterse718f612004-10-12 21:51:32 +0000750
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000751# context manager
752class _SuppressCoreFiles(object):
753 """Try to prevent core files from being created."""
754 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000755
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000756 def __enter__(self):
757 """Try to save previous ulimit, then set it to (0, 0)."""
758 try:
759 import resource
760 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
761 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
762 except (ImportError, ValueError, resource.error):
763 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000764
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000765 if sys.platform == 'darwin':
766 # Check if the 'Crash Reporter' on OSX was configured
767 # in 'Developer' mode and warn that it will get triggered
768 # when it is.
769 #
770 # This assumes that this context manager is used in tests
771 # that might trigger the next manager.
772 value = subprocess.Popen(['/usr/bin/defaults', 'read',
773 'com.apple.CrashReporter', 'DialogType'],
774 stdout=subprocess.PIPE).communicate()[0]
775 if value.strip() == b'developer':
776 print("this tests triggers the Crash Reporter, "
777 "that is intentional", end='')
778 sys.stdout.flush()
779
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000780 def __exit__(self, *args):
781 """Return core file behavior to default."""
782 if self.old_limit is None:
783 return
784 try:
785 import resource
786 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
787 except (ImportError, ValueError, resource.error):
788 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000789
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000790
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000791@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000792class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000793
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000794 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000795 nonexistent_dir = "/_this/pa.th/does/not/exist"
796 try:
797 os.chdir(nonexistent_dir)
798 except OSError as e:
799 # This avoids hard coding the errno value or the OS perror()
800 # string and instead capture the exception that we want to see
801 # below for comparison.
802 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000803 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000804 else:
805 self.fail("chdir to nonexistant directory %s succeeded." %
806 nonexistent_dir)
807
808 # Error in the child re-raised in the parent.
809 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000810 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000811 cwd=nonexistent_dir)
812 except OSError as e:
813 # Test that the child process chdir failure actually makes
814 # it up to the parent process as the correct exception.
815 self.assertEqual(desired_exception.errno, e.errno)
816 self.assertEqual(desired_exception.strerror, e.strerror)
817 else:
818 self.fail("Expected OSError: %s" % desired_exception)
819
820 def test_restore_signals(self):
821 # Code coverage for both values of restore_signals to make sure it
822 # at least does not blow up.
823 # A test for behavior would be complex. Contributions welcome.
824 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
825 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
826
827 def test_start_new_session(self):
828 # For code coverage of calling setsid(). We don't care if we get an
829 # EPERM error from it depending on the test execution environment, that
830 # still indicates that it was called.
831 try:
832 output = subprocess.check_output(
833 [sys.executable, "-c",
834 "import os; print(os.getpgid(os.getpid()))"],
835 start_new_session=True)
836 except OSError as e:
837 if e.errno != errno.EPERM:
838 raise
839 else:
840 parent_pgid = os.getpgid(os.getpid())
841 child_pgid = int(output)
842 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000843
844 def test_run_abort(self):
845 # returncode handles signal termination
846 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000847 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000848 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000849 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000850 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000851
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000852 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000853 # DISCLAIMER: Setting environment variables is *not* a good use
854 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000855 p = subprocess.Popen([sys.executable, "-c",
856 'import sys,os;'
857 'sys.stdout.write(os.getenv("FRUIT"))'],
858 stdout=subprocess.PIPE,
859 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000860 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000861 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000862
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000863 def test_preexec_exception(self):
864 def raise_it():
865 raise ValueError("What if two swallows carried a coconut?")
866 try:
867 p = subprocess.Popen([sys.executable, "-c", ""],
868 preexec_fn=raise_it)
869 except RuntimeError as e:
870 self.assertTrue(
871 subprocess._posixsubprocess,
872 "Expected a ValueError from the preexec_fn")
873 except ValueError as e:
874 self.assertIn("coconut", e.args[0])
875 else:
876 self.fail("Exception raised by preexec_fn did not make it "
877 "to the parent process.")
878
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000879 @unittest.skipUnless(gc, "Requires a gc module.")
880 def test_preexec_gc_module_failure(self):
881 # This tests the code that disables garbage collection if the child
882 # process will execute any Python.
883 def raise_runtime_error():
884 raise RuntimeError("this shouldn't escape")
885 enabled = gc.isenabled()
886 orig_gc_disable = gc.disable
887 orig_gc_isenabled = gc.isenabled
888 try:
889 gc.disable()
890 self.assertFalse(gc.isenabled())
891 subprocess.call([sys.executable, '-c', ''],
892 preexec_fn=lambda: None)
893 self.assertFalse(gc.isenabled(),
894 "Popen enabled gc when it shouldn't.")
895
896 gc.enable()
897 self.assertTrue(gc.isenabled())
898 subprocess.call([sys.executable, '-c', ''],
899 preexec_fn=lambda: None)
900 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
901
902 gc.disable = raise_runtime_error
903 self.assertRaises(RuntimeError, subprocess.Popen,
904 [sys.executable, '-c', ''],
905 preexec_fn=lambda: None)
906
907 del gc.isenabled # force an AttributeError
908 self.assertRaises(AttributeError, subprocess.Popen,
909 [sys.executable, '-c', ''],
910 preexec_fn=lambda: None)
911 finally:
912 gc.disable = orig_gc_disable
913 gc.isenabled = orig_gc_isenabled
914 if not enabled:
915 gc.disable()
916
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000917 def test_args_string(self):
918 # args is a string
919 fd, fname = mkstemp()
920 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000921 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000922 fobj.write("#!/bin/sh\n")
923 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
924 sys.executable)
925 os.chmod(fname, 0o700)
926 p = subprocess.Popen(fname)
927 p.wait()
928 os.remove(fname)
929 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000930
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000931 def test_invalid_args(self):
932 # invalid arguments should raise ValueError
933 self.assertRaises(ValueError, subprocess.call,
934 [sys.executable, "-c",
935 "import sys; sys.exit(47)"],
936 startupinfo=47)
937 self.assertRaises(ValueError, subprocess.call,
938 [sys.executable, "-c",
939 "import sys; sys.exit(47)"],
940 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000941
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000942 def test_shell_sequence(self):
943 # Run command through the shell (sequence)
944 newenv = os.environ.copy()
945 newenv["FRUIT"] = "apple"
946 p = subprocess.Popen(["echo $FRUIT"], shell=1,
947 stdout=subprocess.PIPE,
948 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000949 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000950 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000951
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000952 def test_shell_string(self):
953 # Run command through the shell (string)
954 newenv = os.environ.copy()
955 newenv["FRUIT"] = "apple"
956 p = subprocess.Popen("echo $FRUIT", shell=1,
957 stdout=subprocess.PIPE,
958 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000959 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000960 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +0000961
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000962 def test_call_string(self):
963 # call() function with string argument on UNIX
964 fd, fname = mkstemp()
965 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000966 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000967 fobj.write("#!/bin/sh\n")
968 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
969 sys.executable)
970 os.chmod(fname, 0o700)
971 rc = subprocess.call(fname)
972 os.remove(fname)
973 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +0000974
Stefan Krah9542cc62010-07-19 14:20:53 +0000975 def test_specific_shell(self):
976 # Issue #9265: Incorrect name passed as arg[0].
977 shells = []
978 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
979 for name in ['bash', 'ksh']:
980 sh = os.path.join(prefix, name)
981 if os.path.isfile(sh):
982 shells.append(sh)
983 if not shells: # Will probably work for any shell but csh.
984 self.skipTest("bash or ksh required for this test")
985 sh = '/bin/sh'
986 if os.path.isfile(sh) and not os.path.islink(sh):
987 # Test will fail if /bin/sh is a symlink to csh.
988 shells.append(sh)
989 for sh in shells:
990 p = subprocess.Popen("echo $0", executable=sh, shell=True,
991 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000992 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +0000993 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
994
Florent Xicluna4886d242010-03-08 13:27:26 +0000995 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +0000996 # Do not inherit file handles from the parent.
997 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +0000998 p = subprocess.Popen([sys.executable, "-c", """if 1:
999 import sys, time
1000 sys.stdout.write('x\\n')
1001 sys.stdout.flush()
1002 time.sleep(30)
1003 """],
1004 close_fds=True,
1005 stdin=subprocess.PIPE,
1006 stdout=subprocess.PIPE,
1007 stderr=subprocess.PIPE)
1008 # Wait for the interpreter to be completely initialized before
1009 # sending any signal.
1010 p.stdout.read(1)
1011 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001012 return p
1013
1014 def test_send_signal(self):
1015 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001016 _, stderr = p.communicate()
1017 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001018 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001019
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001020 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001021 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001022 _, stderr = p.communicate()
1023 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001024 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001025
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001026 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001027 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001028 _, stderr = p.communicate()
1029 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001030 self.assertEqual(p.wait(), -signal.SIGTERM)
1031
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001032 def check_close_std_fds(self, fds):
1033 # Issue #9905: test that subprocess pipes still work properly with
1034 # some standard fds closed
1035 stdin = 0
1036 newfds = []
1037 for a in fds:
1038 b = os.dup(a)
1039 newfds.append(b)
1040 if a == 0:
1041 stdin = b
1042 try:
1043 for fd in fds:
1044 os.close(fd)
1045 out, err = subprocess.Popen([sys.executable, "-c",
1046 'import sys;'
1047 'sys.stdout.write("apple");'
1048 'sys.stdout.flush();'
1049 'sys.stderr.write("orange")'],
1050 stdin=stdin,
1051 stdout=subprocess.PIPE,
1052 stderr=subprocess.PIPE).communicate()
1053 err = support.strip_python_stderr(err)
1054 self.assertEqual((out, err), (b'apple', b'orange'))
1055 finally:
1056 for b, a in zip(newfds, fds):
1057 os.dup2(b, a)
1058 for b in newfds:
1059 os.close(b)
1060
1061 def test_close_fd_0(self):
1062 self.check_close_std_fds([0])
1063
1064 def test_close_fd_1(self):
1065 self.check_close_std_fds([1])
1066
1067 def test_close_fd_2(self):
1068 self.check_close_std_fds([2])
1069
1070 def test_close_fds_0_1(self):
1071 self.check_close_std_fds([0, 1])
1072
1073 def test_close_fds_0_2(self):
1074 self.check_close_std_fds([0, 2])
1075
1076 def test_close_fds_1_2(self):
1077 self.check_close_std_fds([1, 2])
1078
1079 def test_close_fds_0_1_2(self):
1080 # Issue #10806: test that subprocess pipes still work properly with
1081 # all standard fds closed.
1082 self.check_close_std_fds([0, 1, 2])
1083
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001084 def test_remapping_std_fds(self):
1085 # open up some temporary files
1086 temps = [mkstemp() for i in range(3)]
1087 try:
1088 temp_fds = [fd for fd, fname in temps]
1089
1090 # unlink the files -- we won't need to reopen them
1091 for fd, fname in temps:
1092 os.unlink(fname)
1093
1094 # write some data to what will become stdin, and rewind
1095 os.write(temp_fds[1], b"STDIN")
1096 os.lseek(temp_fds[1], 0, 0)
1097
1098 # move the standard file descriptors out of the way
1099 saved_fds = [os.dup(fd) for fd in range(3)]
1100 try:
1101 # duplicate the file objects over the standard fd's
1102 for fd, temp_fd in enumerate(temp_fds):
1103 os.dup2(temp_fd, fd)
1104
1105 # now use those files in the "wrong" order, so that subprocess
1106 # has to rearrange them in the child
1107 p = subprocess.Popen([sys.executable, "-c",
1108 'import sys; got = sys.stdin.read();'
1109 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1110 stdin=temp_fds[1],
1111 stdout=temp_fds[2],
1112 stderr=temp_fds[0])
1113 p.wait()
1114 finally:
1115 # restore the original fd's underneath sys.stdin, etc.
1116 for std, saved in enumerate(saved_fds):
1117 os.dup2(saved, std)
1118 os.close(saved)
1119
1120 for fd in temp_fds:
1121 os.lseek(fd, 0, 0)
1122
1123 out = os.read(temp_fds[2], 1024)
1124 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1125 self.assertEqual(out, b"got STDIN")
1126 self.assertEqual(err, b"err")
1127
1128 finally:
1129 for fd in temp_fds:
1130 os.close(fd)
1131
Victor Stinner13bb71c2010-04-23 21:41:56 +00001132 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001133 def prepare():
1134 raise ValueError("surrogate:\uDCff")
1135
1136 try:
1137 subprocess.call(
1138 [sys.executable, "-c", "pass"],
1139 preexec_fn=prepare)
1140 except ValueError as err:
1141 # Pure Python implementations keeps the message
1142 self.assertIsNone(subprocess._posixsubprocess)
1143 self.assertEqual(str(err), "surrogate:\uDCff")
1144 except RuntimeError as err:
1145 # _posixsubprocess uses a default message
1146 self.assertIsNotNone(subprocess._posixsubprocess)
1147 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1148 else:
1149 self.fail("Expected ValueError or RuntimeError")
1150
Victor Stinner13bb71c2010-04-23 21:41:56 +00001151 def test_undecodable_env(self):
1152 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001153 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001154 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001155 env = os.environ.copy()
1156 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001157 # Use C locale to get ascii for the locale encoding to force
1158 # surrogate-escaping of \xFF in the child process; otherwise it can
1159 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001160 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001161 stdout = subprocess.check_output(
1162 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001163 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001164 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001165 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001166
1167 # test bytes
1168 key = key.encode("ascii", "surrogateescape")
1169 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001170 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001171 env = os.environ.copy()
1172 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001173 stdout = subprocess.check_output(
1174 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001175 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001176 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001177 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001178
Victor Stinnerb745a742010-05-18 17:17:23 +00001179 def test_bytes_program(self):
1180 abs_program = os.fsencode(sys.executable)
1181 path, program = os.path.split(sys.executable)
1182 program = os.fsencode(program)
1183
1184 # absolute bytes path
1185 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001186 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001187
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001188 # absolute bytes path as a string
1189 cmd = b"'" + abs_program + b"' -c pass"
1190 exitcode = subprocess.call(cmd, shell=True)
1191 self.assertEqual(exitcode, 0)
1192
Victor Stinnerb745a742010-05-18 17:17:23 +00001193 # bytes program, unicode PATH
1194 env = os.environ.copy()
1195 env["PATH"] = path
1196 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001197 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001198
1199 # bytes program, bytes PATH
1200 envb = os.environb.copy()
1201 envb[b"PATH"] = os.fsencode(path)
1202 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001203 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001204
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001205 def test_pipe_cloexec(self):
1206 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1207 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1208
1209 p1 = subprocess.Popen([sys.executable, sleeper],
1210 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1211 stderr=subprocess.PIPE, close_fds=False)
1212
1213 self.addCleanup(p1.communicate, b'')
1214
1215 p2 = subprocess.Popen([sys.executable, fd_status],
1216 stdout=subprocess.PIPE, close_fds=False)
1217
1218 output, error = p2.communicate()
1219 result_fds = set(map(int, output.split(b',')))
1220 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1221 p1.stderr.fileno()])
1222
1223 self.assertFalse(result_fds & unwanted_fds,
1224 "Expected no fds from %r to be open in child, "
1225 "found %r" %
1226 (unwanted_fds, result_fds & unwanted_fds))
1227
1228 def test_pipe_cloexec_real_tools(self):
1229 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1230 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1231
1232 subdata = b'zxcvbn'
1233 data = subdata * 4 + b'\n'
1234
1235 p1 = subprocess.Popen([sys.executable, qcat],
1236 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1237 close_fds=False)
1238
1239 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1240 stdin=p1.stdout, stdout=subprocess.PIPE,
1241 close_fds=False)
1242
1243 self.addCleanup(p1.wait)
1244 self.addCleanup(p2.wait)
1245 self.addCleanup(p1.terminate)
1246 self.addCleanup(p2.terminate)
1247
1248 p1.stdin.write(data)
1249 p1.stdin.close()
1250
1251 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1252
1253 self.assertTrue(readfiles, "The child hung")
1254 self.assertEqual(p2.stdout.read(), data)
1255
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001256 p1.stdout.close()
1257 p2.stdout.close()
1258
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001259 def test_close_fds(self):
1260 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1261
1262 fds = os.pipe()
1263 self.addCleanup(os.close, fds[0])
1264 self.addCleanup(os.close, fds[1])
1265
1266 open_fds = set(fds)
1267
1268 p = subprocess.Popen([sys.executable, fd_status],
1269 stdout=subprocess.PIPE, close_fds=False)
1270 output, ignored = p.communicate()
1271 remaining_fds = set(map(int, output.split(b',')))
1272
1273 self.assertEqual(remaining_fds & open_fds, open_fds,
1274 "Some fds were closed")
1275
1276 p = subprocess.Popen([sys.executable, fd_status],
1277 stdout=subprocess.PIPE, close_fds=True)
1278 output, ignored = p.communicate()
1279 remaining_fds = set(map(int, output.split(b',')))
1280
1281 self.assertFalse(remaining_fds & open_fds,
1282 "Some fds were left open")
1283 self.assertIn(1, remaining_fds, "Subprocess failed")
1284
Victor Stinner88701e22011-06-01 13:13:04 +02001285 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1286 # descriptor of a pipe closed in the parent process is valid in the
1287 # child process according to fstat(), but the mode of the file
1288 # descriptor is invalid, and read or write raise an error.
1289 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001290 def test_pass_fds(self):
1291 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1292
1293 open_fds = set()
1294
1295 for x in range(5):
1296 fds = os.pipe()
1297 self.addCleanup(os.close, fds[0])
1298 self.addCleanup(os.close, fds[1])
1299 open_fds.update(fds)
1300
1301 for fd in open_fds:
1302 p = subprocess.Popen([sys.executable, fd_status],
1303 stdout=subprocess.PIPE, close_fds=True,
1304 pass_fds=(fd, ))
1305 output, ignored = p.communicate()
1306
1307 remaining_fds = set(map(int, output.split(b',')))
1308 to_be_closed = open_fds - {fd}
1309
1310 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1311 self.assertFalse(remaining_fds & to_be_closed,
1312 "fd to be closed passed")
1313
1314 # pass_fds overrides close_fds with a warning.
1315 with self.assertWarns(RuntimeWarning) as context:
1316 self.assertFalse(subprocess.call(
1317 [sys.executable, "-c", "import sys; sys.exit(0)"],
1318 close_fds=False, pass_fds=(fd, )))
1319 self.assertIn('overriding close_fds', str(context.warning))
1320
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001321 def test_stdout_stdin_are_single_inout_fd(self):
1322 with io.open(os.devnull, "r+") as inout:
1323 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1324 stdout=inout, stdin=inout)
1325 p.wait()
1326
1327 def test_stdout_stderr_are_single_inout_fd(self):
1328 with io.open(os.devnull, "r+") as inout:
1329 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1330 stdout=inout, stderr=inout)
1331 p.wait()
1332
1333 def test_stderr_stdin_are_single_inout_fd(self):
1334 with io.open(os.devnull, "r+") as inout:
1335 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1336 stderr=inout, stdin=inout)
1337 p.wait()
1338
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001339 def test_wait_when_sigchild_ignored(self):
1340 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1341 sigchild_ignore = support.findfile("sigchild_ignore.py",
1342 subdir="subprocessdata")
1343 p = subprocess.Popen([sys.executable, sigchild_ignore],
1344 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1345 stdout, stderr = p.communicate()
1346 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001347 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001348 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001349
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001350 def test_select_unbuffered(self):
1351 # Issue #11459: bufsize=0 should really set the pipes as
1352 # unbuffered (and therefore let select() work properly).
1353 select = support.import_module("select")
1354 p = subprocess.Popen([sys.executable, "-c",
1355 'import sys;'
1356 'sys.stdout.write("apple")'],
1357 stdout=subprocess.PIPE,
1358 bufsize=0)
1359 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001360 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001361 try:
1362 self.assertEqual(f.read(4), b"appl")
1363 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1364 finally:
1365 p.wait()
1366
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001367
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001368@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001369class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001370
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001371 def test_startupinfo(self):
1372 # startupinfo argument
1373 # We uses hardcoded constants, because we do not want to
1374 # depend on win32all.
1375 STARTF_USESHOWWINDOW = 1
1376 SW_MAXIMIZE = 3
1377 startupinfo = subprocess.STARTUPINFO()
1378 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1379 startupinfo.wShowWindow = SW_MAXIMIZE
1380 # Since Python is a console process, it won't be affected
1381 # by wShowWindow, but the argument should be silently
1382 # ignored
1383 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001384 startupinfo=startupinfo)
1385
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001386 def test_creationflags(self):
1387 # creationflags argument
1388 CREATE_NEW_CONSOLE = 16
1389 sys.stderr.write(" a DOS box should flash briefly ...\n")
1390 subprocess.call(sys.executable +
1391 ' -c "import time; time.sleep(0.25)"',
1392 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001393
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001394 def test_invalid_args(self):
1395 # invalid arguments should raise ValueError
1396 self.assertRaises(ValueError, subprocess.call,
1397 [sys.executable, "-c",
1398 "import sys; sys.exit(47)"],
1399 preexec_fn=lambda: 1)
1400 self.assertRaises(ValueError, subprocess.call,
1401 [sys.executable, "-c",
1402 "import sys; sys.exit(47)"],
1403 stdout=subprocess.PIPE,
1404 close_fds=True)
1405
1406 def test_close_fds(self):
1407 # close file descriptors
1408 rc = subprocess.call([sys.executable, "-c",
1409 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001410 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001411 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001412
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001413 def test_shell_sequence(self):
1414 # Run command through the shell (sequence)
1415 newenv = os.environ.copy()
1416 newenv["FRUIT"] = "physalis"
1417 p = subprocess.Popen(["set"], shell=1,
1418 stdout=subprocess.PIPE,
1419 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001420 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001421 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001422
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001423 def test_shell_string(self):
1424 # Run command through the shell (string)
1425 newenv = os.environ.copy()
1426 newenv["FRUIT"] = "physalis"
1427 p = subprocess.Popen("set", shell=1,
1428 stdout=subprocess.PIPE,
1429 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001430 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001431 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001432
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001433 def test_call_string(self):
1434 # call() function with string argument on Windows
1435 rc = subprocess.call(sys.executable +
1436 ' -c "import sys; sys.exit(47)"')
1437 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001438
Florent Xicluna4886d242010-03-08 13:27:26 +00001439 def _kill_process(self, method, *args):
1440 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001441 p = subprocess.Popen([sys.executable, "-c", """if 1:
1442 import sys, time
1443 sys.stdout.write('x\\n')
1444 sys.stdout.flush()
1445 time.sleep(30)
1446 """],
1447 stdin=subprocess.PIPE,
1448 stdout=subprocess.PIPE,
1449 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001450 self.addCleanup(p.stdout.close)
1451 self.addCleanup(p.stderr.close)
1452 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001453 # Wait for the interpreter to be completely initialized before
1454 # sending any signal.
1455 p.stdout.read(1)
1456 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001457 _, stderr = p.communicate()
1458 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001459 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001460 self.assertNotEqual(returncode, 0)
1461
1462 def test_send_signal(self):
1463 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001464
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001465 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001466 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001467
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001468 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001469 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001470
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001471
Brett Cannona23810f2008-05-26 19:04:21 +00001472# The module says:
1473# "NB This only works (and is only relevant) for UNIX."
1474#
1475# Actually, getoutput should work on any platform with an os.popen, but
1476# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001477@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001478class CommandTests(unittest.TestCase):
1479 def test_getoutput(self):
1480 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1481 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1482 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001483
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001484 # we use mkdtemp in the next line to create an empty directory
1485 # under our exclusive control; from that, we can invent a pathname
1486 # that we _know_ won't exist. This is guaranteed to fail.
1487 dir = None
1488 try:
1489 dir = tempfile.mkdtemp()
1490 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001491
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001492 status, output = subprocess.getstatusoutput('cat ' + name)
1493 self.assertNotEqual(status, 0)
1494 finally:
1495 if dir is not None:
1496 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001497
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001498
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001499@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1500 "poll system call not supported")
1501class ProcessTestCaseNoPoll(ProcessTestCase):
1502 def setUp(self):
1503 subprocess._has_poll = False
1504 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001505
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001506 def tearDown(self):
1507 subprocess._has_poll = True
1508 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001509
1510
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001511class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001512 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001513 def test_eintr_retry_call(self):
1514 record_calls = []
1515 def fake_os_func(*args):
1516 record_calls.append(args)
1517 if len(record_calls) == 2:
1518 raise OSError(errno.EINTR, "fake interrupted system call")
1519 return tuple(reversed(args))
1520
1521 self.assertEqual((999, 256),
1522 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1523 self.assertEqual([(256, 999)], record_calls)
1524 # This time there will be an EINTR so it will loop once.
1525 self.assertEqual((666,),
1526 subprocess._eintr_retry_call(fake_os_func, 666))
1527 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1528
1529
Tim Golden126c2962010-08-11 14:20:40 +00001530@unittest.skipUnless(mswindows, "Windows-specific tests")
1531class CommandsWithSpaces (BaseTestCase):
1532
1533 def setUp(self):
1534 super().setUp()
1535 f, fname = mkstemp(".py", "te st")
1536 self.fname = fname.lower ()
1537 os.write(f, b"import sys;"
1538 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1539 )
1540 os.close(f)
1541
1542 def tearDown(self):
1543 os.remove(self.fname)
1544 super().tearDown()
1545
1546 def with_spaces(self, *args, **kwargs):
1547 kwargs['stdout'] = subprocess.PIPE
1548 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001549 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001550 self.assertEqual(
1551 p.stdout.read ().decode("mbcs"),
1552 "2 [%r, 'ab cd']" % self.fname
1553 )
1554
1555 def test_shell_string_with_spaces(self):
1556 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001557 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1558 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001559
1560 def test_shell_sequence_with_spaces(self):
1561 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001562 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001563
1564 def test_noshell_string_with_spaces(self):
1565 # call() function with string argument with spaces on Windows
1566 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1567 "ab cd"))
1568
1569 def test_noshell_sequence_with_spaces(self):
1570 # call() function with sequence argument with spaces on Windows
1571 self.with_spaces([sys.executable, self.fname, "ab cd"])
1572
Brian Curtin79cdb662010-12-03 02:46:02 +00001573
1574class ContextManagerTests(ProcessTestCase):
1575
1576 def test_pipe(self):
1577 with subprocess.Popen([sys.executable, "-c",
1578 "import sys;"
1579 "sys.stdout.write('stdout');"
1580 "sys.stderr.write('stderr');"],
1581 stdout=subprocess.PIPE,
1582 stderr=subprocess.PIPE) as proc:
1583 self.assertEqual(proc.stdout.read(), b"stdout")
1584 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1585
1586 self.assertTrue(proc.stdout.closed)
1587 self.assertTrue(proc.stderr.closed)
1588
1589 def test_returncode(self):
1590 with subprocess.Popen([sys.executable, "-c",
1591 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07001592 pass
1593 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00001594 self.assertEqual(proc.returncode, 100)
1595
1596 def test_communicate_stdin(self):
1597 with subprocess.Popen([sys.executable, "-c",
1598 "import sys;"
1599 "sys.exit(sys.stdin.read() == 'context')"],
1600 stdin=subprocess.PIPE) as proc:
1601 proc.communicate(b"context")
1602 self.assertEqual(proc.returncode, 1)
1603
1604 def test_invalid_args(self):
1605 with self.assertRaises(EnvironmentError) as c:
1606 with subprocess.Popen(['nonexisting_i_hope'],
1607 stdout=subprocess.PIPE,
1608 stderr=subprocess.PIPE) as proc:
1609 pass
1610
1611 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1612 raise c.exception
1613
1614
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001615def test_main():
1616 unit_tests = (ProcessTestCase,
1617 POSIXProcessTestCase,
1618 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001619 CommandTests,
1620 ProcessTestCaseNoPoll,
1621 HelperFunctionTests,
1622 CommandsWithSpaces,
1623 ContextManagerTests)
1624
1625 support.run_unittest(*unit_tests)
1626 support.reap_children()
1627
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001628if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001629 unittest.main()