blob: 6e31fe7f7f39581b4cc124bb40f972b7b476dff7 [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"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200385 with subprocess.Popen([sys.executable, "-c",
386 'import sys,os;'
387 'sys.stdout.write(os.getenv("FRUIT"))'],
388 stdout=subprocess.PIPE,
389 env=newenv) as p:
390 stdout, stderr = p.communicate()
391 self.assertEqual(stdout, b"orange")
392
Victor Stinner62d51182011-06-23 01:02:25 +0200393 # Windows requires at least the SYSTEMROOT environment variable to start
394 # Python
395 @unittest.skipIf(sys.platform == 'win32',
396 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200397 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200398 'the python library cannot be loaded '
399 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200400 def test_empty_env(self):
401 with subprocess.Popen([sys.executable, "-c",
402 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200403 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200404 stdout=subprocess.PIPE,
405 env={}) as p:
406 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200407 self.assertIn(stdout.strip(),
408 (b"[]",
409 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
410 # environment
411 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000412
Peter Astrandcbac93c2005-03-03 20:24:28 +0000413 def test_communicate_stdin(self):
414 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000415 'import sys;'
416 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000417 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000418 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000419 self.assertEqual(p.returncode, 1)
420
421 def test_communicate_stdout(self):
422 p = subprocess.Popen([sys.executable, "-c",
423 'import sys; sys.stdout.write("pineapple")'],
424 stdout=subprocess.PIPE)
425 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000426 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000427 self.assertEqual(stderr, None)
428
429 def test_communicate_stderr(self):
430 p = subprocess.Popen([sys.executable, "-c",
431 'import sys; sys.stderr.write("pineapple")'],
432 stderr=subprocess.PIPE)
433 (stdout, stderr) = p.communicate()
434 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000435 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000436
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000437 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000438 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000439 'import sys,os;'
440 'sys.stderr.write("pineapple");'
441 'sys.stdout.write(sys.stdin.read())'],
442 stdin=subprocess.PIPE,
443 stdout=subprocess.PIPE,
444 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000445 self.addCleanup(p.stdout.close)
446 self.addCleanup(p.stderr.close)
447 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000448 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000449 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000450 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000451
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400452 def test_communicate_timeout(self):
453 p = subprocess.Popen([sys.executable, "-c",
454 'import sys,os,time;'
455 'sys.stderr.write("pineapple\\n");'
456 'time.sleep(1);'
457 'sys.stderr.write("pear\\n");'
458 'sys.stdout.write(sys.stdin.read())'],
459 universal_newlines=True,
460 stdin=subprocess.PIPE,
461 stdout=subprocess.PIPE,
462 stderr=subprocess.PIPE)
463 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
464 timeout=0.3)
465 # Make sure we can keep waiting for it, and that we get the whole output
466 # after it completes.
467 (stdout, stderr) = p.communicate()
468 self.assertEqual(stdout, "banana")
469 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
470
471 def test_communicate_timeout_large_ouput(self):
472 # Test a expring timeout while the child is outputting lots of data.
473 p = subprocess.Popen([sys.executable, "-c",
474 'import sys,os,time;'
475 'sys.stdout.write("a" * (64 * 1024));'
476 'time.sleep(0.2);'
477 'sys.stdout.write("a" * (64 * 1024));'
478 'time.sleep(0.2);'
479 'sys.stdout.write("a" * (64 * 1024));'
480 'time.sleep(0.2);'
481 'sys.stdout.write("a" * (64 * 1024));'],
482 stdout=subprocess.PIPE)
483 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
484 (stdout, _) = p.communicate()
485 self.assertEqual(len(stdout), 4 * 64 * 1024)
486
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000487 # Test for the fd leak reported in http://bugs.python.org/issue2791.
488 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000489 for stdin_pipe in (False, True):
490 for stdout_pipe in (False, True):
491 for stderr_pipe in (False, True):
492 options = {}
493 if stdin_pipe:
494 options['stdin'] = subprocess.PIPE
495 if stdout_pipe:
496 options['stdout'] = subprocess.PIPE
497 if stderr_pipe:
498 options['stderr'] = subprocess.PIPE
499 if not options:
500 continue
501 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
502 p.communicate()
503 if p.stdin is not None:
504 self.assertTrue(p.stdin.closed)
505 if p.stdout is not None:
506 self.assertTrue(p.stdout.closed)
507 if p.stderr is not None:
508 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000509
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000510 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000511 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000512 p = subprocess.Popen([sys.executable, "-c",
513 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000514 (stdout, stderr) = p.communicate()
515 self.assertEqual(stdout, None)
516 self.assertEqual(stderr, None)
517
518 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000519 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000520 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000521 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000522 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000523 os.close(x)
524 os.close(y)
525 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000526 'import sys,os;'
527 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200528 'sys.stderr.write("x" * %d);'
529 'sys.stdout.write(sys.stdin.read())' %
530 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000531 stdin=subprocess.PIPE,
532 stdout=subprocess.PIPE,
533 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000534 self.addCleanup(p.stdout.close)
535 self.addCleanup(p.stderr.close)
536 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200537 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000538 (stdout, stderr) = p.communicate(string_to_write)
539 self.assertEqual(stdout, string_to_write)
540
541 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000542 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000543 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000544 'import sys,os;'
545 'sys.stdout.write(sys.stdin.read())'],
546 stdin=subprocess.PIPE,
547 stdout=subprocess.PIPE,
548 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000549 self.addCleanup(p.stdout.close)
550 self.addCleanup(p.stderr.close)
551 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000552 p.stdin.write(b"banana")
553 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000554 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000555 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000556
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000557 def test_universal_newlines(self):
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,
572 universal_newlines=1)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000573 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000574 stdout = p.stdout.read()
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000575 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000576
577 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000578 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000579 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000580 'import sys,os;' + SETBINARY +
581 'sys.stdout.write("line1\\n");'
582 'sys.stdout.flush();'
583 'sys.stdout.write("line2\\n");'
584 'sys.stdout.flush();'
585 'sys.stdout.write("line3\\r\\n");'
586 'sys.stdout.flush();'
587 'sys.stdout.write("line4\\r");'
588 'sys.stdout.flush();'
589 'sys.stdout.write("\\nline5");'
590 'sys.stdout.flush();'
591 'sys.stdout.write("\\nline6");'],
592 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
593 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000594 self.addCleanup(p.stdout.close)
595 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000596 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000597 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000598
599 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000600 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000601 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000602 max_handles = 1026 # too much for most UNIX systems
603 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000604 max_handles = 2050 # too much for (at least some) Windows setups
605 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400606 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000607 try:
608 for i in range(max_handles):
609 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400610 tmpfile = os.path.join(tmpdir, support.TESTFN)
611 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000612 except OSError as e:
613 if e.errno != errno.EMFILE:
614 raise
615 break
616 else:
617 self.skipTest("failed to reach the file descriptor limit "
618 "(tried %d)" % max_handles)
619 # Close a couple of them (should be enough for a subprocess)
620 for i in range(10):
621 os.close(handles.pop())
622 # Loop creating some subprocesses. If one of them leaks some fds,
623 # the next loop iteration will fail by reaching the max fd limit.
624 for i in range(15):
625 p = subprocess.Popen([sys.executable, "-c",
626 "import sys;"
627 "sys.stdout.write(sys.stdin.read())"],
628 stdin=subprocess.PIPE,
629 stdout=subprocess.PIPE,
630 stderr=subprocess.PIPE)
631 data = p.communicate(b"lime")[0]
632 self.assertEqual(data, b"lime")
633 finally:
634 for h in handles:
635 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400636 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000637
638 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000639 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
640 '"a b c" d e')
641 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
642 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000643 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
644 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000645 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
646 'a\\\\\\b "de fg" h')
647 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
648 'a\\\\\\"b c d')
649 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
650 '"a\\\\b c" d e')
651 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
652 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000653 self.assertEqual(subprocess.list2cmdline(['ab', '']),
654 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000655
656
657 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000658 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000659 "-c", "import time; time.sleep(1)"])
660 count = 0
661 while p.poll() is None:
662 time.sleep(0.1)
663 count += 1
664 # We expect that the poll loop probably went around about 10 times,
665 # but, based on system scheduling we can't control, it's possible
666 # poll() never returned None. It "should be" very rare that it
667 # didn't go around at least twice.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000668 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000669 # Subsequent invocations should just return the returncode
670 self.assertEqual(p.poll(), 0)
671
672
673 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000674 p = subprocess.Popen([sys.executable,
675 "-c", "import time; time.sleep(2)"])
676 self.assertEqual(p.wait(), 0)
677 # Subsequent invocations should just return the returncode
678 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000679
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400680 def test_wait_timeout(self):
681 p = subprocess.Popen([sys.executable,
Reid Kleckner93479cc2011-03-14 19:32:41 -0400682 "-c", "import time; time.sleep(0.1)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -0400683 with self.assertRaises(subprocess.TimeoutExpired) as c:
684 p.wait(timeout=0.01)
685 self.assertIn("0.01", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -0400686 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
687 # time to start.
688 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400689
Peter Astrand738131d2004-11-30 21:04:45 +0000690 def test_invalid_bufsize(self):
691 # an invalid type of the bufsize argument should raise
692 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000693 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000694 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000695
Guido van Rossum46a05a72007-06-07 21:56:45 +0000696 def test_bufsize_is_none(self):
697 # bufsize=None should be the same as bufsize=0.
698 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
699 self.assertEqual(p.wait(), 0)
700 # Again with keyword arg
701 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
702 self.assertEqual(p.wait(), 0)
703
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000704 def test_leaking_fds_on_error(self):
705 # see bug #5179: Popen leaks file descriptors to PIPEs if
706 # the child fails to execute; this will eventually exhaust
707 # the maximum number of open fds. 1024 seems a very common
708 # value for that limit, but Windows has 2048, so we loop
709 # 1024 times (each call leaked two fds).
710 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000711 # Windows raises IOError. Others raise OSError.
712 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000713 subprocess.Popen(['nonexisting_i_hope'],
714 stdout=subprocess.PIPE,
715 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400716 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400717 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000718 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000719
Victor Stinnerb3693582010-05-21 20:13:12 +0000720 def test_issue8780(self):
721 # Ensure that stdout is inherited from the parent
722 # if stdout=PIPE is not used
723 code = ';'.join((
724 'import subprocess, sys',
725 'retcode = subprocess.call('
726 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
727 'assert retcode == 0'))
728 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000729 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000730
Tim Goldenaf5ac392010-08-06 13:03:56 +0000731 def test_handles_closed_on_exception(self):
732 # If CreateProcess exits with an error, ensure the
733 # duplicate output handles are released
734 ifhandle, ifname = mkstemp()
735 ofhandle, ofname = mkstemp()
736 efhandle, efname = mkstemp()
737 try:
738 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
739 stderr=efhandle)
740 except OSError:
741 os.close(ifhandle)
742 os.remove(ifname)
743 os.close(ofhandle)
744 os.remove(ofname)
745 os.close(efhandle)
746 os.remove(efname)
747 self.assertFalse(os.path.exists(ifname))
748 self.assertFalse(os.path.exists(ofname))
749 self.assertFalse(os.path.exists(efname))
750
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200751 def test_communicate_epipe(self):
752 # Issue 10963: communicate() should hide EPIPE
753 p = subprocess.Popen([sys.executable, "-c", 'pass'],
754 stdin=subprocess.PIPE,
755 stdout=subprocess.PIPE,
756 stderr=subprocess.PIPE)
757 self.addCleanup(p.stdout.close)
758 self.addCleanup(p.stderr.close)
759 self.addCleanup(p.stdin.close)
760 p.communicate(b"x" * 2**20)
761
762 def test_communicate_epipe_only_stdin(self):
763 # Issue 10963: communicate() should hide EPIPE
764 p = subprocess.Popen([sys.executable, "-c", 'pass'],
765 stdin=subprocess.PIPE)
766 self.addCleanup(p.stdin.close)
767 time.sleep(2)
768 p.communicate(b"x" * 2**20)
769
Tim Peterse718f612004-10-12 21:51:32 +0000770
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000771# context manager
772class _SuppressCoreFiles(object):
773 """Try to prevent core files from being created."""
774 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000775
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000776 def __enter__(self):
777 """Try to save previous ulimit, then set it to (0, 0)."""
778 try:
779 import resource
780 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
781 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
782 except (ImportError, ValueError, resource.error):
783 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000784
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000785 if sys.platform == 'darwin':
786 # Check if the 'Crash Reporter' on OSX was configured
787 # in 'Developer' mode and warn that it will get triggered
788 # when it is.
789 #
790 # This assumes that this context manager is used in tests
791 # that might trigger the next manager.
792 value = subprocess.Popen(['/usr/bin/defaults', 'read',
793 'com.apple.CrashReporter', 'DialogType'],
794 stdout=subprocess.PIPE).communicate()[0]
795 if value.strip() == b'developer':
796 print("this tests triggers the Crash Reporter, "
797 "that is intentional", end='')
798 sys.stdout.flush()
799
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000800 def __exit__(self, *args):
801 """Return core file behavior to default."""
802 if self.old_limit is None:
803 return
804 try:
805 import resource
806 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
807 except (ImportError, ValueError, resource.error):
808 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000809
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000810
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000811@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000812class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000813
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000814 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000815 nonexistent_dir = "/_this/pa.th/does/not/exist"
816 try:
817 os.chdir(nonexistent_dir)
818 except OSError as e:
819 # This avoids hard coding the errno value or the OS perror()
820 # string and instead capture the exception that we want to see
821 # below for comparison.
822 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000823 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000824 else:
825 self.fail("chdir to nonexistant directory %s succeeded." %
826 nonexistent_dir)
827
828 # Error in the child re-raised in the parent.
829 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000830 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000831 cwd=nonexistent_dir)
832 except OSError as e:
833 # Test that the child process chdir failure actually makes
834 # it up to the parent process as the correct exception.
835 self.assertEqual(desired_exception.errno, e.errno)
836 self.assertEqual(desired_exception.strerror, e.strerror)
837 else:
838 self.fail("Expected OSError: %s" % desired_exception)
839
840 def test_restore_signals(self):
841 # Code coverage for both values of restore_signals to make sure it
842 # at least does not blow up.
843 # A test for behavior would be complex. Contributions welcome.
844 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
845 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
846
847 def test_start_new_session(self):
848 # For code coverage of calling setsid(). We don't care if we get an
849 # EPERM error from it depending on the test execution environment, that
850 # still indicates that it was called.
851 try:
852 output = subprocess.check_output(
853 [sys.executable, "-c",
854 "import os; print(os.getpgid(os.getpid()))"],
855 start_new_session=True)
856 except OSError as e:
857 if e.errno != errno.EPERM:
858 raise
859 else:
860 parent_pgid = os.getpgid(os.getpid())
861 child_pgid = int(output)
862 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000863
864 def test_run_abort(self):
865 # returncode handles signal termination
866 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000867 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000868 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000869 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000870 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000871
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000872 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000873 # DISCLAIMER: Setting environment variables is *not* a good use
874 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000875 p = subprocess.Popen([sys.executable, "-c",
876 'import sys,os;'
877 'sys.stdout.write(os.getenv("FRUIT"))'],
878 stdout=subprocess.PIPE,
879 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000880 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000881 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000882
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000883 def test_preexec_exception(self):
884 def raise_it():
885 raise ValueError("What if two swallows carried a coconut?")
886 try:
887 p = subprocess.Popen([sys.executable, "-c", ""],
888 preexec_fn=raise_it)
889 except RuntimeError as e:
890 self.assertTrue(
891 subprocess._posixsubprocess,
892 "Expected a ValueError from the preexec_fn")
893 except ValueError as e:
894 self.assertIn("coconut", e.args[0])
895 else:
896 self.fail("Exception raised by preexec_fn did not make it "
897 "to the parent process.")
898
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000899 @unittest.skipUnless(gc, "Requires a gc module.")
900 def test_preexec_gc_module_failure(self):
901 # This tests the code that disables garbage collection if the child
902 # process will execute any Python.
903 def raise_runtime_error():
904 raise RuntimeError("this shouldn't escape")
905 enabled = gc.isenabled()
906 orig_gc_disable = gc.disable
907 orig_gc_isenabled = gc.isenabled
908 try:
909 gc.disable()
910 self.assertFalse(gc.isenabled())
911 subprocess.call([sys.executable, '-c', ''],
912 preexec_fn=lambda: None)
913 self.assertFalse(gc.isenabled(),
914 "Popen enabled gc when it shouldn't.")
915
916 gc.enable()
917 self.assertTrue(gc.isenabled())
918 subprocess.call([sys.executable, '-c', ''],
919 preexec_fn=lambda: None)
920 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
921
922 gc.disable = raise_runtime_error
923 self.assertRaises(RuntimeError, subprocess.Popen,
924 [sys.executable, '-c', ''],
925 preexec_fn=lambda: None)
926
927 del gc.isenabled # force an AttributeError
928 self.assertRaises(AttributeError, subprocess.Popen,
929 [sys.executable, '-c', ''],
930 preexec_fn=lambda: None)
931 finally:
932 gc.disable = orig_gc_disable
933 gc.isenabled = orig_gc_isenabled
934 if not enabled:
935 gc.disable()
936
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000937 def test_args_string(self):
938 # args is a string
939 fd, fname = mkstemp()
940 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000941 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000942 fobj.write("#!/bin/sh\n")
943 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
944 sys.executable)
945 os.chmod(fname, 0o700)
946 p = subprocess.Popen(fname)
947 p.wait()
948 os.remove(fname)
949 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000950
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000951 def test_invalid_args(self):
952 # invalid arguments should raise ValueError
953 self.assertRaises(ValueError, subprocess.call,
954 [sys.executable, "-c",
955 "import sys; sys.exit(47)"],
956 startupinfo=47)
957 self.assertRaises(ValueError, subprocess.call,
958 [sys.executable, "-c",
959 "import sys; sys.exit(47)"],
960 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000961
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000962 def test_shell_sequence(self):
963 # Run command through the shell (sequence)
964 newenv = os.environ.copy()
965 newenv["FRUIT"] = "apple"
966 p = subprocess.Popen(["echo $FRUIT"], shell=1,
967 stdout=subprocess.PIPE,
968 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000969 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000970 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000971
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000972 def test_shell_string(self):
973 # Run command through the shell (string)
974 newenv = os.environ.copy()
975 newenv["FRUIT"] = "apple"
976 p = subprocess.Popen("echo $FRUIT", shell=1,
977 stdout=subprocess.PIPE,
978 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000979 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000980 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +0000981
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000982 def test_call_string(self):
983 # call() function with string argument on UNIX
984 fd, fname = mkstemp()
985 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000986 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000987 fobj.write("#!/bin/sh\n")
988 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
989 sys.executable)
990 os.chmod(fname, 0o700)
991 rc = subprocess.call(fname)
992 os.remove(fname)
993 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +0000994
Stefan Krah9542cc62010-07-19 14:20:53 +0000995 def test_specific_shell(self):
996 # Issue #9265: Incorrect name passed as arg[0].
997 shells = []
998 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
999 for name in ['bash', 'ksh']:
1000 sh = os.path.join(prefix, name)
1001 if os.path.isfile(sh):
1002 shells.append(sh)
1003 if not shells: # Will probably work for any shell but csh.
1004 self.skipTest("bash or ksh required for this test")
1005 sh = '/bin/sh'
1006 if os.path.isfile(sh) and not os.path.islink(sh):
1007 # Test will fail if /bin/sh is a symlink to csh.
1008 shells.append(sh)
1009 for sh in shells:
1010 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1011 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001012 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001013 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1014
Florent Xicluna4886d242010-03-08 13:27:26 +00001015 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001016 # Do not inherit file handles from the parent.
1017 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001018 p = subprocess.Popen([sys.executable, "-c", """if 1:
1019 import sys, time
1020 sys.stdout.write('x\\n')
1021 sys.stdout.flush()
1022 time.sleep(30)
1023 """],
1024 close_fds=True,
1025 stdin=subprocess.PIPE,
1026 stdout=subprocess.PIPE,
1027 stderr=subprocess.PIPE)
1028 # Wait for the interpreter to be completely initialized before
1029 # sending any signal.
1030 p.stdout.read(1)
1031 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001032 return p
1033
1034 def test_send_signal(self):
1035 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001036 _, stderr = p.communicate()
1037 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001038 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001039
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001040 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001041 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001042 _, stderr = p.communicate()
1043 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001044 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001045
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001046 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001047 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001048 _, stderr = p.communicate()
1049 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001050 self.assertEqual(p.wait(), -signal.SIGTERM)
1051
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001052 def check_close_std_fds(self, fds):
1053 # Issue #9905: test that subprocess pipes still work properly with
1054 # some standard fds closed
1055 stdin = 0
1056 newfds = []
1057 for a in fds:
1058 b = os.dup(a)
1059 newfds.append(b)
1060 if a == 0:
1061 stdin = b
1062 try:
1063 for fd in fds:
1064 os.close(fd)
1065 out, err = subprocess.Popen([sys.executable, "-c",
1066 'import sys;'
1067 'sys.stdout.write("apple");'
1068 'sys.stdout.flush();'
1069 'sys.stderr.write("orange")'],
1070 stdin=stdin,
1071 stdout=subprocess.PIPE,
1072 stderr=subprocess.PIPE).communicate()
1073 err = support.strip_python_stderr(err)
1074 self.assertEqual((out, err), (b'apple', b'orange'))
1075 finally:
1076 for b, a in zip(newfds, fds):
1077 os.dup2(b, a)
1078 for b in newfds:
1079 os.close(b)
1080
1081 def test_close_fd_0(self):
1082 self.check_close_std_fds([0])
1083
1084 def test_close_fd_1(self):
1085 self.check_close_std_fds([1])
1086
1087 def test_close_fd_2(self):
1088 self.check_close_std_fds([2])
1089
1090 def test_close_fds_0_1(self):
1091 self.check_close_std_fds([0, 1])
1092
1093 def test_close_fds_0_2(self):
1094 self.check_close_std_fds([0, 2])
1095
1096 def test_close_fds_1_2(self):
1097 self.check_close_std_fds([1, 2])
1098
1099 def test_close_fds_0_1_2(self):
1100 # Issue #10806: test that subprocess pipes still work properly with
1101 # all standard fds closed.
1102 self.check_close_std_fds([0, 1, 2])
1103
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001104 def test_remapping_std_fds(self):
1105 # open up some temporary files
1106 temps = [mkstemp() for i in range(3)]
1107 try:
1108 temp_fds = [fd for fd, fname in temps]
1109
1110 # unlink the files -- we won't need to reopen them
1111 for fd, fname in temps:
1112 os.unlink(fname)
1113
1114 # write some data to what will become stdin, and rewind
1115 os.write(temp_fds[1], b"STDIN")
1116 os.lseek(temp_fds[1], 0, 0)
1117
1118 # move the standard file descriptors out of the way
1119 saved_fds = [os.dup(fd) for fd in range(3)]
1120 try:
1121 # duplicate the file objects over the standard fd's
1122 for fd, temp_fd in enumerate(temp_fds):
1123 os.dup2(temp_fd, fd)
1124
1125 # now use those files in the "wrong" order, so that subprocess
1126 # has to rearrange them in the child
1127 p = subprocess.Popen([sys.executable, "-c",
1128 'import sys; got = sys.stdin.read();'
1129 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1130 stdin=temp_fds[1],
1131 stdout=temp_fds[2],
1132 stderr=temp_fds[0])
1133 p.wait()
1134 finally:
1135 # restore the original fd's underneath sys.stdin, etc.
1136 for std, saved in enumerate(saved_fds):
1137 os.dup2(saved, std)
1138 os.close(saved)
1139
1140 for fd in temp_fds:
1141 os.lseek(fd, 0, 0)
1142
1143 out = os.read(temp_fds[2], 1024)
1144 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1145 self.assertEqual(out, b"got STDIN")
1146 self.assertEqual(err, b"err")
1147
1148 finally:
1149 for fd in temp_fds:
1150 os.close(fd)
1151
Victor Stinner13bb71c2010-04-23 21:41:56 +00001152 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001153 def prepare():
1154 raise ValueError("surrogate:\uDCff")
1155
1156 try:
1157 subprocess.call(
1158 [sys.executable, "-c", "pass"],
1159 preexec_fn=prepare)
1160 except ValueError as err:
1161 # Pure Python implementations keeps the message
1162 self.assertIsNone(subprocess._posixsubprocess)
1163 self.assertEqual(str(err), "surrogate:\uDCff")
1164 except RuntimeError as err:
1165 # _posixsubprocess uses a default message
1166 self.assertIsNotNone(subprocess._posixsubprocess)
1167 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1168 else:
1169 self.fail("Expected ValueError or RuntimeError")
1170
Victor Stinner13bb71c2010-04-23 21:41:56 +00001171 def test_undecodable_env(self):
1172 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001173 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001174 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001175 env = os.environ.copy()
1176 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001177 # Use C locale to get ascii for the locale encoding to force
1178 # surrogate-escaping of \xFF in the child process; otherwise it can
1179 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001180 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001181 stdout = subprocess.check_output(
1182 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001183 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001184 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001185 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001186
1187 # test bytes
1188 key = key.encode("ascii", "surrogateescape")
1189 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001190 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001191 env = os.environ.copy()
1192 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001193 stdout = subprocess.check_output(
1194 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001195 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001196 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001197 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001198
Victor Stinnerb745a742010-05-18 17:17:23 +00001199 def test_bytes_program(self):
1200 abs_program = os.fsencode(sys.executable)
1201 path, program = os.path.split(sys.executable)
1202 program = os.fsencode(program)
1203
1204 # absolute bytes path
1205 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001206 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001207
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001208 # absolute bytes path as a string
1209 cmd = b"'" + abs_program + b"' -c pass"
1210 exitcode = subprocess.call(cmd, shell=True)
1211 self.assertEqual(exitcode, 0)
1212
Victor Stinnerb745a742010-05-18 17:17:23 +00001213 # bytes program, unicode PATH
1214 env = os.environ.copy()
1215 env["PATH"] = path
1216 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001217 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001218
1219 # bytes program, bytes PATH
1220 envb = os.environb.copy()
1221 envb[b"PATH"] = os.fsencode(path)
1222 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001223 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001224
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001225 def test_pipe_cloexec(self):
1226 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1227 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1228
1229 p1 = subprocess.Popen([sys.executable, sleeper],
1230 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1231 stderr=subprocess.PIPE, close_fds=False)
1232
1233 self.addCleanup(p1.communicate, b'')
1234
1235 p2 = subprocess.Popen([sys.executable, fd_status],
1236 stdout=subprocess.PIPE, close_fds=False)
1237
1238 output, error = p2.communicate()
1239 result_fds = set(map(int, output.split(b',')))
1240 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1241 p1.stderr.fileno()])
1242
1243 self.assertFalse(result_fds & unwanted_fds,
1244 "Expected no fds from %r to be open in child, "
1245 "found %r" %
1246 (unwanted_fds, result_fds & unwanted_fds))
1247
1248 def test_pipe_cloexec_real_tools(self):
1249 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1250 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1251
1252 subdata = b'zxcvbn'
1253 data = subdata * 4 + b'\n'
1254
1255 p1 = subprocess.Popen([sys.executable, qcat],
1256 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1257 close_fds=False)
1258
1259 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1260 stdin=p1.stdout, stdout=subprocess.PIPE,
1261 close_fds=False)
1262
1263 self.addCleanup(p1.wait)
1264 self.addCleanup(p2.wait)
1265 self.addCleanup(p1.terminate)
1266 self.addCleanup(p2.terminate)
1267
1268 p1.stdin.write(data)
1269 p1.stdin.close()
1270
1271 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1272
1273 self.assertTrue(readfiles, "The child hung")
1274 self.assertEqual(p2.stdout.read(), data)
1275
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001276 p1.stdout.close()
1277 p2.stdout.close()
1278
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001279 def test_close_fds(self):
1280 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1281
1282 fds = os.pipe()
1283 self.addCleanup(os.close, fds[0])
1284 self.addCleanup(os.close, fds[1])
1285
1286 open_fds = set(fds)
1287
1288 p = subprocess.Popen([sys.executable, fd_status],
1289 stdout=subprocess.PIPE, close_fds=False)
1290 output, ignored = p.communicate()
1291 remaining_fds = set(map(int, output.split(b',')))
1292
1293 self.assertEqual(remaining_fds & open_fds, open_fds,
1294 "Some fds were closed")
1295
1296 p = subprocess.Popen([sys.executable, fd_status],
1297 stdout=subprocess.PIPE, close_fds=True)
1298 output, ignored = p.communicate()
1299 remaining_fds = set(map(int, output.split(b',')))
1300
1301 self.assertFalse(remaining_fds & open_fds,
1302 "Some fds were left open")
1303 self.assertIn(1, remaining_fds, "Subprocess failed")
1304
Victor Stinner88701e22011-06-01 13:13:04 +02001305 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1306 # descriptor of a pipe closed in the parent process is valid in the
1307 # child process according to fstat(), but the mode of the file
1308 # descriptor is invalid, and read or write raise an error.
1309 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001310 def test_pass_fds(self):
1311 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1312
1313 open_fds = set()
1314
1315 for x in range(5):
1316 fds = os.pipe()
1317 self.addCleanup(os.close, fds[0])
1318 self.addCleanup(os.close, fds[1])
1319 open_fds.update(fds)
1320
1321 for fd in open_fds:
1322 p = subprocess.Popen([sys.executable, fd_status],
1323 stdout=subprocess.PIPE, close_fds=True,
1324 pass_fds=(fd, ))
1325 output, ignored = p.communicate()
1326
1327 remaining_fds = set(map(int, output.split(b',')))
1328 to_be_closed = open_fds - {fd}
1329
1330 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1331 self.assertFalse(remaining_fds & to_be_closed,
1332 "fd to be closed passed")
1333
1334 # pass_fds overrides close_fds with a warning.
1335 with self.assertWarns(RuntimeWarning) as context:
1336 self.assertFalse(subprocess.call(
1337 [sys.executable, "-c", "import sys; sys.exit(0)"],
1338 close_fds=False, pass_fds=(fd, )))
1339 self.assertIn('overriding close_fds', str(context.warning))
1340
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001341 def test_stdout_stdin_are_single_inout_fd(self):
1342 with io.open(os.devnull, "r+") as inout:
1343 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1344 stdout=inout, stdin=inout)
1345 p.wait()
1346
1347 def test_stdout_stderr_are_single_inout_fd(self):
1348 with io.open(os.devnull, "r+") as inout:
1349 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1350 stdout=inout, stderr=inout)
1351 p.wait()
1352
1353 def test_stderr_stdin_are_single_inout_fd(self):
1354 with io.open(os.devnull, "r+") as inout:
1355 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1356 stderr=inout, stdin=inout)
1357 p.wait()
1358
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001359 def test_wait_when_sigchild_ignored(self):
1360 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1361 sigchild_ignore = support.findfile("sigchild_ignore.py",
1362 subdir="subprocessdata")
1363 p = subprocess.Popen([sys.executable, sigchild_ignore],
1364 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1365 stdout, stderr = p.communicate()
1366 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001367 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001368 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001369
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001370 def test_select_unbuffered(self):
1371 # Issue #11459: bufsize=0 should really set the pipes as
1372 # unbuffered (and therefore let select() work properly).
1373 select = support.import_module("select")
1374 p = subprocess.Popen([sys.executable, "-c",
1375 'import sys;'
1376 'sys.stdout.write("apple")'],
1377 stdout=subprocess.PIPE,
1378 bufsize=0)
1379 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001380 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001381 try:
1382 self.assertEqual(f.read(4), b"appl")
1383 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1384 finally:
1385 p.wait()
1386
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001387
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001388@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001389class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001390
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001391 def test_startupinfo(self):
1392 # startupinfo argument
1393 # We uses hardcoded constants, because we do not want to
1394 # depend on win32all.
1395 STARTF_USESHOWWINDOW = 1
1396 SW_MAXIMIZE = 3
1397 startupinfo = subprocess.STARTUPINFO()
1398 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1399 startupinfo.wShowWindow = SW_MAXIMIZE
1400 # Since Python is a console process, it won't be affected
1401 # by wShowWindow, but the argument should be silently
1402 # ignored
1403 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001404 startupinfo=startupinfo)
1405
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001406 def test_creationflags(self):
1407 # creationflags argument
1408 CREATE_NEW_CONSOLE = 16
1409 sys.stderr.write(" a DOS box should flash briefly ...\n")
1410 subprocess.call(sys.executable +
1411 ' -c "import time; time.sleep(0.25)"',
1412 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001413
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001414 def test_invalid_args(self):
1415 # invalid arguments should raise ValueError
1416 self.assertRaises(ValueError, subprocess.call,
1417 [sys.executable, "-c",
1418 "import sys; sys.exit(47)"],
1419 preexec_fn=lambda: 1)
1420 self.assertRaises(ValueError, subprocess.call,
1421 [sys.executable, "-c",
1422 "import sys; sys.exit(47)"],
1423 stdout=subprocess.PIPE,
1424 close_fds=True)
1425
1426 def test_close_fds(self):
1427 # close file descriptors
1428 rc = subprocess.call([sys.executable, "-c",
1429 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001430 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001431 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001432
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001433 def test_shell_sequence(self):
1434 # Run command through the shell (sequence)
1435 newenv = os.environ.copy()
1436 newenv["FRUIT"] = "physalis"
1437 p = subprocess.Popen(["set"], shell=1,
1438 stdout=subprocess.PIPE,
1439 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001440 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001441 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001442
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001443 def test_shell_string(self):
1444 # Run command through the shell (string)
1445 newenv = os.environ.copy()
1446 newenv["FRUIT"] = "physalis"
1447 p = subprocess.Popen("set", shell=1,
1448 stdout=subprocess.PIPE,
1449 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001450 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001451 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001452
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001453 def test_call_string(self):
1454 # call() function with string argument on Windows
1455 rc = subprocess.call(sys.executable +
1456 ' -c "import sys; sys.exit(47)"')
1457 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001458
Florent Xicluna4886d242010-03-08 13:27:26 +00001459 def _kill_process(self, method, *args):
1460 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001461 p = subprocess.Popen([sys.executable, "-c", """if 1:
1462 import sys, time
1463 sys.stdout.write('x\\n')
1464 sys.stdout.flush()
1465 time.sleep(30)
1466 """],
1467 stdin=subprocess.PIPE,
1468 stdout=subprocess.PIPE,
1469 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001470 self.addCleanup(p.stdout.close)
1471 self.addCleanup(p.stderr.close)
1472 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001473 # Wait for the interpreter to be completely initialized before
1474 # sending any signal.
1475 p.stdout.read(1)
1476 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001477 _, stderr = p.communicate()
1478 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001479 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001480 self.assertNotEqual(returncode, 0)
1481
1482 def test_send_signal(self):
1483 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001484
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001485 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001486 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001487
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001488 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001489 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001490
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001491
Brett Cannona23810f2008-05-26 19:04:21 +00001492# The module says:
1493# "NB This only works (and is only relevant) for UNIX."
1494#
1495# Actually, getoutput should work on any platform with an os.popen, but
1496# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001497@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001498class CommandTests(unittest.TestCase):
1499 def test_getoutput(self):
1500 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1501 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1502 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001503
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001504 # we use mkdtemp in the next line to create an empty directory
1505 # under our exclusive control; from that, we can invent a pathname
1506 # that we _know_ won't exist. This is guaranteed to fail.
1507 dir = None
1508 try:
1509 dir = tempfile.mkdtemp()
1510 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001511
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001512 status, output = subprocess.getstatusoutput('cat ' + name)
1513 self.assertNotEqual(status, 0)
1514 finally:
1515 if dir is not None:
1516 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001517
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001518
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001519@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1520 "poll system call not supported")
1521class ProcessTestCaseNoPoll(ProcessTestCase):
1522 def setUp(self):
1523 subprocess._has_poll = False
1524 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001525
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001526 def tearDown(self):
1527 subprocess._has_poll = True
1528 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001529
1530
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001531class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001532 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001533 def test_eintr_retry_call(self):
1534 record_calls = []
1535 def fake_os_func(*args):
1536 record_calls.append(args)
1537 if len(record_calls) == 2:
1538 raise OSError(errno.EINTR, "fake interrupted system call")
1539 return tuple(reversed(args))
1540
1541 self.assertEqual((999, 256),
1542 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1543 self.assertEqual([(256, 999)], record_calls)
1544 # This time there will be an EINTR so it will loop once.
1545 self.assertEqual((666,),
1546 subprocess._eintr_retry_call(fake_os_func, 666))
1547 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1548
1549
Tim Golden126c2962010-08-11 14:20:40 +00001550@unittest.skipUnless(mswindows, "Windows-specific tests")
1551class CommandsWithSpaces (BaseTestCase):
1552
1553 def setUp(self):
1554 super().setUp()
1555 f, fname = mkstemp(".py", "te st")
1556 self.fname = fname.lower ()
1557 os.write(f, b"import sys;"
1558 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1559 )
1560 os.close(f)
1561
1562 def tearDown(self):
1563 os.remove(self.fname)
1564 super().tearDown()
1565
1566 def with_spaces(self, *args, **kwargs):
1567 kwargs['stdout'] = subprocess.PIPE
1568 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001569 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001570 self.assertEqual(
1571 p.stdout.read ().decode("mbcs"),
1572 "2 [%r, 'ab cd']" % self.fname
1573 )
1574
1575 def test_shell_string_with_spaces(self):
1576 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001577 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1578 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001579
1580 def test_shell_sequence_with_spaces(self):
1581 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001582 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001583
1584 def test_noshell_string_with_spaces(self):
1585 # call() function with string argument with spaces on Windows
1586 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1587 "ab cd"))
1588
1589 def test_noshell_sequence_with_spaces(self):
1590 # call() function with sequence argument with spaces on Windows
1591 self.with_spaces([sys.executable, self.fname, "ab cd"])
1592
Brian Curtin79cdb662010-12-03 02:46:02 +00001593
1594class ContextManagerTests(ProcessTestCase):
1595
1596 def test_pipe(self):
1597 with subprocess.Popen([sys.executable, "-c",
1598 "import sys;"
1599 "sys.stdout.write('stdout');"
1600 "sys.stderr.write('stderr');"],
1601 stdout=subprocess.PIPE,
1602 stderr=subprocess.PIPE) as proc:
1603 self.assertEqual(proc.stdout.read(), b"stdout")
1604 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1605
1606 self.assertTrue(proc.stdout.closed)
1607 self.assertTrue(proc.stderr.closed)
1608
1609 def test_returncode(self):
1610 with subprocess.Popen([sys.executable, "-c",
1611 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07001612 pass
1613 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00001614 self.assertEqual(proc.returncode, 100)
1615
1616 def test_communicate_stdin(self):
1617 with subprocess.Popen([sys.executable, "-c",
1618 "import sys;"
1619 "sys.exit(sys.stdin.read() == 'context')"],
1620 stdin=subprocess.PIPE) as proc:
1621 proc.communicate(b"context")
1622 self.assertEqual(proc.returncode, 1)
1623
1624 def test_invalid_args(self):
1625 with self.assertRaises(EnvironmentError) as c:
1626 with subprocess.Popen(['nonexisting_i_hope'],
1627 stdout=subprocess.PIPE,
1628 stderr=subprocess.PIPE) as proc:
1629 pass
1630
1631 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1632 raise c.exception
1633
1634
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001635def test_main():
1636 unit_tests = (ProcessTestCase,
1637 POSIXProcessTestCase,
1638 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001639 CommandTests,
1640 ProcessTestCaseNoPoll,
1641 HelperFunctionTests,
1642 CommandsWithSpaces,
1643 ContextManagerTests)
1644
1645 support.run_unittest(*unit_tests)
1646 support.reap_children()
1647
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001648if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001649 unittest.main()