blob: 2bf49f2a10d155839904fab6aef33b6333777b1a [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
Victor Stinner1848db82011-07-05 14:49:46 +0200770 @unittest.skipUnless(hasattr(signal, 'SIGALRM'),
771 "Requires signal.SIGALRM")
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200772 def test_communicate_eintr(self):
773 # Issue #12493: communicate() should handle EINTR
774 def handler(signum, frame):
775 pass
776 old_handler = signal.signal(signal.SIGALRM, handler)
777 self.addCleanup(signal.signal, signal.SIGALRM, old_handler)
778
779 # the process is running for 2 seconds
780 args = [sys.executable, "-c", 'import time; time.sleep(2)']
781 for stream in ('stdout', 'stderr'):
782 kw = {stream: subprocess.PIPE}
783 with subprocess.Popen(args, **kw) as process:
784 signal.alarm(1)
785 # communicate() will be interrupted by SIGALRM
786 process.communicate()
787
Tim Peterse718f612004-10-12 21:51:32 +0000788
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000789# context manager
790class _SuppressCoreFiles(object):
791 """Try to prevent core files from being created."""
792 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000793
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000794 def __enter__(self):
795 """Try to save previous ulimit, then set it to (0, 0)."""
796 try:
797 import resource
798 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
799 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
800 except (ImportError, ValueError, resource.error):
801 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000802
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000803 if sys.platform == 'darwin':
804 # Check if the 'Crash Reporter' on OSX was configured
805 # in 'Developer' mode and warn that it will get triggered
806 # when it is.
807 #
808 # This assumes that this context manager is used in tests
809 # that might trigger the next manager.
810 value = subprocess.Popen(['/usr/bin/defaults', 'read',
811 'com.apple.CrashReporter', 'DialogType'],
812 stdout=subprocess.PIPE).communicate()[0]
813 if value.strip() == b'developer':
814 print("this tests triggers the Crash Reporter, "
815 "that is intentional", end='')
816 sys.stdout.flush()
817
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000818 def __exit__(self, *args):
819 """Return core file behavior to default."""
820 if self.old_limit is None:
821 return
822 try:
823 import resource
824 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
825 except (ImportError, ValueError, resource.error):
826 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000827
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000828
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000829@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000830class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000831
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000832 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000833 nonexistent_dir = "/_this/pa.th/does/not/exist"
834 try:
835 os.chdir(nonexistent_dir)
836 except OSError as e:
837 # This avoids hard coding the errno value or the OS perror()
838 # string and instead capture the exception that we want to see
839 # below for comparison.
840 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000841 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000842 else:
843 self.fail("chdir to nonexistant directory %s succeeded." %
844 nonexistent_dir)
845
846 # Error in the child re-raised in the parent.
847 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000848 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000849 cwd=nonexistent_dir)
850 except OSError as e:
851 # Test that the child process chdir failure actually makes
852 # it up to the parent process as the correct exception.
853 self.assertEqual(desired_exception.errno, e.errno)
854 self.assertEqual(desired_exception.strerror, e.strerror)
855 else:
856 self.fail("Expected OSError: %s" % desired_exception)
857
858 def test_restore_signals(self):
859 # Code coverage for both values of restore_signals to make sure it
860 # at least does not blow up.
861 # A test for behavior would be complex. Contributions welcome.
862 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
863 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
864
865 def test_start_new_session(self):
866 # For code coverage of calling setsid(). We don't care if we get an
867 # EPERM error from it depending on the test execution environment, that
868 # still indicates that it was called.
869 try:
870 output = subprocess.check_output(
871 [sys.executable, "-c",
872 "import os; print(os.getpgid(os.getpid()))"],
873 start_new_session=True)
874 except OSError as e:
875 if e.errno != errno.EPERM:
876 raise
877 else:
878 parent_pgid = os.getpgid(os.getpid())
879 child_pgid = int(output)
880 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000881
882 def test_run_abort(self):
883 # returncode handles signal termination
884 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000885 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000886 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000887 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000888 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000889
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000890 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000891 # DISCLAIMER: Setting environment variables is *not* a good use
892 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000893 p = subprocess.Popen([sys.executable, "-c",
894 'import sys,os;'
895 'sys.stdout.write(os.getenv("FRUIT"))'],
896 stdout=subprocess.PIPE,
897 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000898 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000899 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000900
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000901 def test_preexec_exception(self):
902 def raise_it():
903 raise ValueError("What if two swallows carried a coconut?")
904 try:
905 p = subprocess.Popen([sys.executable, "-c", ""],
906 preexec_fn=raise_it)
907 except RuntimeError as e:
908 self.assertTrue(
909 subprocess._posixsubprocess,
910 "Expected a ValueError from the preexec_fn")
911 except ValueError as e:
912 self.assertIn("coconut", e.args[0])
913 else:
914 self.fail("Exception raised by preexec_fn did not make it "
915 "to the parent process.")
916
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000917 @unittest.skipUnless(gc, "Requires a gc module.")
918 def test_preexec_gc_module_failure(self):
919 # This tests the code that disables garbage collection if the child
920 # process will execute any Python.
921 def raise_runtime_error():
922 raise RuntimeError("this shouldn't escape")
923 enabled = gc.isenabled()
924 orig_gc_disable = gc.disable
925 orig_gc_isenabled = gc.isenabled
926 try:
927 gc.disable()
928 self.assertFalse(gc.isenabled())
929 subprocess.call([sys.executable, '-c', ''],
930 preexec_fn=lambda: None)
931 self.assertFalse(gc.isenabled(),
932 "Popen enabled gc when it shouldn't.")
933
934 gc.enable()
935 self.assertTrue(gc.isenabled())
936 subprocess.call([sys.executable, '-c', ''],
937 preexec_fn=lambda: None)
938 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
939
940 gc.disable = raise_runtime_error
941 self.assertRaises(RuntimeError, subprocess.Popen,
942 [sys.executable, '-c', ''],
943 preexec_fn=lambda: None)
944
945 del gc.isenabled # force an AttributeError
946 self.assertRaises(AttributeError, subprocess.Popen,
947 [sys.executable, '-c', ''],
948 preexec_fn=lambda: None)
949 finally:
950 gc.disable = orig_gc_disable
951 gc.isenabled = orig_gc_isenabled
952 if not enabled:
953 gc.disable()
954
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000955 def test_args_string(self):
956 # args is a string
957 fd, fname = mkstemp()
958 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000959 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000960 fobj.write("#!/bin/sh\n")
961 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
962 sys.executable)
963 os.chmod(fname, 0o700)
964 p = subprocess.Popen(fname)
965 p.wait()
966 os.remove(fname)
967 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000968
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000969 def test_invalid_args(self):
970 # invalid arguments should raise ValueError
971 self.assertRaises(ValueError, subprocess.call,
972 [sys.executable, "-c",
973 "import sys; sys.exit(47)"],
974 startupinfo=47)
975 self.assertRaises(ValueError, subprocess.call,
976 [sys.executable, "-c",
977 "import sys; sys.exit(47)"],
978 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000979
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000980 def test_shell_sequence(self):
981 # Run command through the shell (sequence)
982 newenv = os.environ.copy()
983 newenv["FRUIT"] = "apple"
984 p = subprocess.Popen(["echo $FRUIT"], shell=1,
985 stdout=subprocess.PIPE,
986 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000987 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000988 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000989
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000990 def test_shell_string(self):
991 # Run command through the shell (string)
992 newenv = os.environ.copy()
993 newenv["FRUIT"] = "apple"
994 p = subprocess.Popen("echo $FRUIT", shell=1,
995 stdout=subprocess.PIPE,
996 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000997 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000998 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +0000999
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001000 def test_call_string(self):
1001 # call() function with string argument on UNIX
1002 fd, fname = mkstemp()
1003 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001004 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001005 fobj.write("#!/bin/sh\n")
1006 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1007 sys.executable)
1008 os.chmod(fname, 0o700)
1009 rc = subprocess.call(fname)
1010 os.remove(fname)
1011 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001012
Stefan Krah9542cc62010-07-19 14:20:53 +00001013 def test_specific_shell(self):
1014 # Issue #9265: Incorrect name passed as arg[0].
1015 shells = []
1016 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1017 for name in ['bash', 'ksh']:
1018 sh = os.path.join(prefix, name)
1019 if os.path.isfile(sh):
1020 shells.append(sh)
1021 if not shells: # Will probably work for any shell but csh.
1022 self.skipTest("bash or ksh required for this test")
1023 sh = '/bin/sh'
1024 if os.path.isfile(sh) and not os.path.islink(sh):
1025 # Test will fail if /bin/sh is a symlink to csh.
1026 shells.append(sh)
1027 for sh in shells:
1028 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1029 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001030 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001031 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1032
Florent Xicluna4886d242010-03-08 13:27:26 +00001033 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001034 # Do not inherit file handles from the parent.
1035 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001036 p = subprocess.Popen([sys.executable, "-c", """if 1:
1037 import sys, time
1038 sys.stdout.write('x\\n')
1039 sys.stdout.flush()
1040 time.sleep(30)
1041 """],
1042 close_fds=True,
1043 stdin=subprocess.PIPE,
1044 stdout=subprocess.PIPE,
1045 stderr=subprocess.PIPE)
1046 # Wait for the interpreter to be completely initialized before
1047 # sending any signal.
1048 p.stdout.read(1)
1049 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001050 return p
1051
1052 def test_send_signal(self):
1053 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001054 _, stderr = p.communicate()
1055 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001056 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001057
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001058 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001059 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001060 _, stderr = p.communicate()
1061 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001062 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001063
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001064 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001065 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001066 _, stderr = p.communicate()
1067 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001068 self.assertEqual(p.wait(), -signal.SIGTERM)
1069
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001070 def check_close_std_fds(self, fds):
1071 # Issue #9905: test that subprocess pipes still work properly with
1072 # some standard fds closed
1073 stdin = 0
1074 newfds = []
1075 for a in fds:
1076 b = os.dup(a)
1077 newfds.append(b)
1078 if a == 0:
1079 stdin = b
1080 try:
1081 for fd in fds:
1082 os.close(fd)
1083 out, err = subprocess.Popen([sys.executable, "-c",
1084 'import sys;'
1085 'sys.stdout.write("apple");'
1086 'sys.stdout.flush();'
1087 'sys.stderr.write("orange")'],
1088 stdin=stdin,
1089 stdout=subprocess.PIPE,
1090 stderr=subprocess.PIPE).communicate()
1091 err = support.strip_python_stderr(err)
1092 self.assertEqual((out, err), (b'apple', b'orange'))
1093 finally:
1094 for b, a in zip(newfds, fds):
1095 os.dup2(b, a)
1096 for b in newfds:
1097 os.close(b)
1098
1099 def test_close_fd_0(self):
1100 self.check_close_std_fds([0])
1101
1102 def test_close_fd_1(self):
1103 self.check_close_std_fds([1])
1104
1105 def test_close_fd_2(self):
1106 self.check_close_std_fds([2])
1107
1108 def test_close_fds_0_1(self):
1109 self.check_close_std_fds([0, 1])
1110
1111 def test_close_fds_0_2(self):
1112 self.check_close_std_fds([0, 2])
1113
1114 def test_close_fds_1_2(self):
1115 self.check_close_std_fds([1, 2])
1116
1117 def test_close_fds_0_1_2(self):
1118 # Issue #10806: test that subprocess pipes still work properly with
1119 # all standard fds closed.
1120 self.check_close_std_fds([0, 1, 2])
1121
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001122 def test_remapping_std_fds(self):
1123 # open up some temporary files
1124 temps = [mkstemp() for i in range(3)]
1125 try:
1126 temp_fds = [fd for fd, fname in temps]
1127
1128 # unlink the files -- we won't need to reopen them
1129 for fd, fname in temps:
1130 os.unlink(fname)
1131
1132 # write some data to what will become stdin, and rewind
1133 os.write(temp_fds[1], b"STDIN")
1134 os.lseek(temp_fds[1], 0, 0)
1135
1136 # move the standard file descriptors out of the way
1137 saved_fds = [os.dup(fd) for fd in range(3)]
1138 try:
1139 # duplicate the file objects over the standard fd's
1140 for fd, temp_fd in enumerate(temp_fds):
1141 os.dup2(temp_fd, fd)
1142
1143 # now use those files in the "wrong" order, so that subprocess
1144 # has to rearrange them in the child
1145 p = subprocess.Popen([sys.executable, "-c",
1146 'import sys; got = sys.stdin.read();'
1147 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1148 stdin=temp_fds[1],
1149 stdout=temp_fds[2],
1150 stderr=temp_fds[0])
1151 p.wait()
1152 finally:
1153 # restore the original fd's underneath sys.stdin, etc.
1154 for std, saved in enumerate(saved_fds):
1155 os.dup2(saved, std)
1156 os.close(saved)
1157
1158 for fd in temp_fds:
1159 os.lseek(fd, 0, 0)
1160
1161 out = os.read(temp_fds[2], 1024)
1162 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1163 self.assertEqual(out, b"got STDIN")
1164 self.assertEqual(err, b"err")
1165
1166 finally:
1167 for fd in temp_fds:
1168 os.close(fd)
1169
Victor Stinner13bb71c2010-04-23 21:41:56 +00001170 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001171 def prepare():
1172 raise ValueError("surrogate:\uDCff")
1173
1174 try:
1175 subprocess.call(
1176 [sys.executable, "-c", "pass"],
1177 preexec_fn=prepare)
1178 except ValueError as err:
1179 # Pure Python implementations keeps the message
1180 self.assertIsNone(subprocess._posixsubprocess)
1181 self.assertEqual(str(err), "surrogate:\uDCff")
1182 except RuntimeError as err:
1183 # _posixsubprocess uses a default message
1184 self.assertIsNotNone(subprocess._posixsubprocess)
1185 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1186 else:
1187 self.fail("Expected ValueError or RuntimeError")
1188
Victor Stinner13bb71c2010-04-23 21:41:56 +00001189 def test_undecodable_env(self):
1190 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001191 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001192 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001193 env = os.environ.copy()
1194 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001195 # Use C locale to get ascii for the locale encoding to force
1196 # surrogate-escaping of \xFF in the child process; otherwise it can
1197 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001198 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001199 stdout = subprocess.check_output(
1200 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001201 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001202 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001203 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001204
1205 # test bytes
1206 key = key.encode("ascii", "surrogateescape")
1207 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001208 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001209 env = os.environ.copy()
1210 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001211 stdout = subprocess.check_output(
1212 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001213 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001214 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001215 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001216
Victor Stinnerb745a742010-05-18 17:17:23 +00001217 def test_bytes_program(self):
1218 abs_program = os.fsencode(sys.executable)
1219 path, program = os.path.split(sys.executable)
1220 program = os.fsencode(program)
1221
1222 # absolute bytes path
1223 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001224 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001225
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001226 # absolute bytes path as a string
1227 cmd = b"'" + abs_program + b"' -c pass"
1228 exitcode = subprocess.call(cmd, shell=True)
1229 self.assertEqual(exitcode, 0)
1230
Victor Stinnerb745a742010-05-18 17:17:23 +00001231 # bytes program, unicode PATH
1232 env = os.environ.copy()
1233 env["PATH"] = path
1234 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001235 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001236
1237 # bytes program, bytes PATH
1238 envb = os.environb.copy()
1239 envb[b"PATH"] = os.fsencode(path)
1240 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001241 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001242
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001243 def test_pipe_cloexec(self):
1244 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1245 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1246
1247 p1 = subprocess.Popen([sys.executable, sleeper],
1248 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1249 stderr=subprocess.PIPE, close_fds=False)
1250
1251 self.addCleanup(p1.communicate, b'')
1252
1253 p2 = subprocess.Popen([sys.executable, fd_status],
1254 stdout=subprocess.PIPE, close_fds=False)
1255
1256 output, error = p2.communicate()
1257 result_fds = set(map(int, output.split(b',')))
1258 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1259 p1.stderr.fileno()])
1260
1261 self.assertFalse(result_fds & unwanted_fds,
1262 "Expected no fds from %r to be open in child, "
1263 "found %r" %
1264 (unwanted_fds, result_fds & unwanted_fds))
1265
1266 def test_pipe_cloexec_real_tools(self):
1267 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1268 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1269
1270 subdata = b'zxcvbn'
1271 data = subdata * 4 + b'\n'
1272
1273 p1 = subprocess.Popen([sys.executable, qcat],
1274 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1275 close_fds=False)
1276
1277 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1278 stdin=p1.stdout, stdout=subprocess.PIPE,
1279 close_fds=False)
1280
1281 self.addCleanup(p1.wait)
1282 self.addCleanup(p2.wait)
1283 self.addCleanup(p1.terminate)
1284 self.addCleanup(p2.terminate)
1285
1286 p1.stdin.write(data)
1287 p1.stdin.close()
1288
1289 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1290
1291 self.assertTrue(readfiles, "The child hung")
1292 self.assertEqual(p2.stdout.read(), data)
1293
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001294 p1.stdout.close()
1295 p2.stdout.close()
1296
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001297 def test_close_fds(self):
1298 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1299
1300 fds = os.pipe()
1301 self.addCleanup(os.close, fds[0])
1302 self.addCleanup(os.close, fds[1])
1303
1304 open_fds = set(fds)
1305
1306 p = subprocess.Popen([sys.executable, fd_status],
1307 stdout=subprocess.PIPE, close_fds=False)
1308 output, ignored = p.communicate()
1309 remaining_fds = set(map(int, output.split(b',')))
1310
1311 self.assertEqual(remaining_fds & open_fds, open_fds,
1312 "Some fds were closed")
1313
1314 p = subprocess.Popen([sys.executable, fd_status],
1315 stdout=subprocess.PIPE, close_fds=True)
1316 output, ignored = p.communicate()
1317 remaining_fds = set(map(int, output.split(b',')))
1318
1319 self.assertFalse(remaining_fds & open_fds,
1320 "Some fds were left open")
1321 self.assertIn(1, remaining_fds, "Subprocess failed")
1322
Victor Stinner88701e22011-06-01 13:13:04 +02001323 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1324 # descriptor of a pipe closed in the parent process is valid in the
1325 # child process according to fstat(), but the mode of the file
1326 # descriptor is invalid, and read or write raise an error.
1327 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001328 def test_pass_fds(self):
1329 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1330
1331 open_fds = set()
1332
1333 for x in range(5):
1334 fds = os.pipe()
1335 self.addCleanup(os.close, fds[0])
1336 self.addCleanup(os.close, fds[1])
1337 open_fds.update(fds)
1338
1339 for fd in open_fds:
1340 p = subprocess.Popen([sys.executable, fd_status],
1341 stdout=subprocess.PIPE, close_fds=True,
1342 pass_fds=(fd, ))
1343 output, ignored = p.communicate()
1344
1345 remaining_fds = set(map(int, output.split(b',')))
1346 to_be_closed = open_fds - {fd}
1347
1348 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1349 self.assertFalse(remaining_fds & to_be_closed,
1350 "fd to be closed passed")
1351
1352 # pass_fds overrides close_fds with a warning.
1353 with self.assertWarns(RuntimeWarning) as context:
1354 self.assertFalse(subprocess.call(
1355 [sys.executable, "-c", "import sys; sys.exit(0)"],
1356 close_fds=False, pass_fds=(fd, )))
1357 self.assertIn('overriding close_fds', str(context.warning))
1358
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001359 def test_stdout_stdin_are_single_inout_fd(self):
1360 with io.open(os.devnull, "r+") as inout:
1361 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1362 stdout=inout, stdin=inout)
1363 p.wait()
1364
1365 def test_stdout_stderr_are_single_inout_fd(self):
1366 with io.open(os.devnull, "r+") as inout:
1367 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1368 stdout=inout, stderr=inout)
1369 p.wait()
1370
1371 def test_stderr_stdin_are_single_inout_fd(self):
1372 with io.open(os.devnull, "r+") as inout:
1373 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1374 stderr=inout, stdin=inout)
1375 p.wait()
1376
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001377 def test_wait_when_sigchild_ignored(self):
1378 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1379 sigchild_ignore = support.findfile("sigchild_ignore.py",
1380 subdir="subprocessdata")
1381 p = subprocess.Popen([sys.executable, sigchild_ignore],
1382 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1383 stdout, stderr = p.communicate()
1384 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001385 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001386 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001387
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001388 def test_select_unbuffered(self):
1389 # Issue #11459: bufsize=0 should really set the pipes as
1390 # unbuffered (and therefore let select() work properly).
1391 select = support.import_module("select")
1392 p = subprocess.Popen([sys.executable, "-c",
1393 'import sys;'
1394 'sys.stdout.write("apple")'],
1395 stdout=subprocess.PIPE,
1396 bufsize=0)
1397 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001398 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001399 try:
1400 self.assertEqual(f.read(4), b"appl")
1401 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1402 finally:
1403 p.wait()
1404
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001405
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001406@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001407class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001408
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001409 def test_startupinfo(self):
1410 # startupinfo argument
1411 # We uses hardcoded constants, because we do not want to
1412 # depend on win32all.
1413 STARTF_USESHOWWINDOW = 1
1414 SW_MAXIMIZE = 3
1415 startupinfo = subprocess.STARTUPINFO()
1416 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1417 startupinfo.wShowWindow = SW_MAXIMIZE
1418 # Since Python is a console process, it won't be affected
1419 # by wShowWindow, but the argument should be silently
1420 # ignored
1421 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001422 startupinfo=startupinfo)
1423
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001424 def test_creationflags(self):
1425 # creationflags argument
1426 CREATE_NEW_CONSOLE = 16
1427 sys.stderr.write(" a DOS box should flash briefly ...\n")
1428 subprocess.call(sys.executable +
1429 ' -c "import time; time.sleep(0.25)"',
1430 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001431
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001432 def test_invalid_args(self):
1433 # invalid arguments should raise ValueError
1434 self.assertRaises(ValueError, subprocess.call,
1435 [sys.executable, "-c",
1436 "import sys; sys.exit(47)"],
1437 preexec_fn=lambda: 1)
1438 self.assertRaises(ValueError, subprocess.call,
1439 [sys.executable, "-c",
1440 "import sys; sys.exit(47)"],
1441 stdout=subprocess.PIPE,
1442 close_fds=True)
1443
1444 def test_close_fds(self):
1445 # close file descriptors
1446 rc = subprocess.call([sys.executable, "-c",
1447 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001448 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001449 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001450
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001451 def test_shell_sequence(self):
1452 # Run command through the shell (sequence)
1453 newenv = os.environ.copy()
1454 newenv["FRUIT"] = "physalis"
1455 p = subprocess.Popen(["set"], shell=1,
1456 stdout=subprocess.PIPE,
1457 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001458 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001459 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001460
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001461 def test_shell_string(self):
1462 # Run command through the shell (string)
1463 newenv = os.environ.copy()
1464 newenv["FRUIT"] = "physalis"
1465 p = subprocess.Popen("set", shell=1,
1466 stdout=subprocess.PIPE,
1467 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001468 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001469 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001470
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001471 def test_call_string(self):
1472 # call() function with string argument on Windows
1473 rc = subprocess.call(sys.executable +
1474 ' -c "import sys; sys.exit(47)"')
1475 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001476
Florent Xicluna4886d242010-03-08 13:27:26 +00001477 def _kill_process(self, method, *args):
1478 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001479 p = subprocess.Popen([sys.executable, "-c", """if 1:
1480 import sys, time
1481 sys.stdout.write('x\\n')
1482 sys.stdout.flush()
1483 time.sleep(30)
1484 """],
1485 stdin=subprocess.PIPE,
1486 stdout=subprocess.PIPE,
1487 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001488 self.addCleanup(p.stdout.close)
1489 self.addCleanup(p.stderr.close)
1490 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001491 # Wait for the interpreter to be completely initialized before
1492 # sending any signal.
1493 p.stdout.read(1)
1494 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001495 _, stderr = p.communicate()
1496 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001497 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001498 self.assertNotEqual(returncode, 0)
1499
1500 def test_send_signal(self):
1501 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001502
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001503 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001504 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001505
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001506 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001507 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001508
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001509
Brett Cannona23810f2008-05-26 19:04:21 +00001510# The module says:
1511# "NB This only works (and is only relevant) for UNIX."
1512#
1513# Actually, getoutput should work on any platform with an os.popen, but
1514# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001515@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001516class CommandTests(unittest.TestCase):
1517 def test_getoutput(self):
1518 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1519 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1520 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001521
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001522 # we use mkdtemp in the next line to create an empty directory
1523 # under our exclusive control; from that, we can invent a pathname
1524 # that we _know_ won't exist. This is guaranteed to fail.
1525 dir = None
1526 try:
1527 dir = tempfile.mkdtemp()
1528 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001529
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001530 status, output = subprocess.getstatusoutput('cat ' + name)
1531 self.assertNotEqual(status, 0)
1532 finally:
1533 if dir is not None:
1534 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001535
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001536
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001537@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1538 "poll system call not supported")
1539class ProcessTestCaseNoPoll(ProcessTestCase):
1540 def setUp(self):
1541 subprocess._has_poll = False
1542 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001543
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001544 def tearDown(self):
1545 subprocess._has_poll = True
1546 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001547
1548
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001549class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001550 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001551 def test_eintr_retry_call(self):
1552 record_calls = []
1553 def fake_os_func(*args):
1554 record_calls.append(args)
1555 if len(record_calls) == 2:
1556 raise OSError(errno.EINTR, "fake interrupted system call")
1557 return tuple(reversed(args))
1558
1559 self.assertEqual((999, 256),
1560 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1561 self.assertEqual([(256, 999)], record_calls)
1562 # This time there will be an EINTR so it will loop once.
1563 self.assertEqual((666,),
1564 subprocess._eintr_retry_call(fake_os_func, 666))
1565 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1566
1567
Tim Golden126c2962010-08-11 14:20:40 +00001568@unittest.skipUnless(mswindows, "Windows-specific tests")
1569class CommandsWithSpaces (BaseTestCase):
1570
1571 def setUp(self):
1572 super().setUp()
1573 f, fname = mkstemp(".py", "te st")
1574 self.fname = fname.lower ()
1575 os.write(f, b"import sys;"
1576 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1577 )
1578 os.close(f)
1579
1580 def tearDown(self):
1581 os.remove(self.fname)
1582 super().tearDown()
1583
1584 def with_spaces(self, *args, **kwargs):
1585 kwargs['stdout'] = subprocess.PIPE
1586 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001587 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001588 self.assertEqual(
1589 p.stdout.read ().decode("mbcs"),
1590 "2 [%r, 'ab cd']" % self.fname
1591 )
1592
1593 def test_shell_string_with_spaces(self):
1594 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001595 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1596 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001597
1598 def test_shell_sequence_with_spaces(self):
1599 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001600 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001601
1602 def test_noshell_string_with_spaces(self):
1603 # call() function with string argument with spaces on Windows
1604 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1605 "ab cd"))
1606
1607 def test_noshell_sequence_with_spaces(self):
1608 # call() function with sequence argument with spaces on Windows
1609 self.with_spaces([sys.executable, self.fname, "ab cd"])
1610
Brian Curtin79cdb662010-12-03 02:46:02 +00001611
1612class ContextManagerTests(ProcessTestCase):
1613
1614 def test_pipe(self):
1615 with subprocess.Popen([sys.executable, "-c",
1616 "import sys;"
1617 "sys.stdout.write('stdout');"
1618 "sys.stderr.write('stderr');"],
1619 stdout=subprocess.PIPE,
1620 stderr=subprocess.PIPE) as proc:
1621 self.assertEqual(proc.stdout.read(), b"stdout")
1622 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1623
1624 self.assertTrue(proc.stdout.closed)
1625 self.assertTrue(proc.stderr.closed)
1626
1627 def test_returncode(self):
1628 with subprocess.Popen([sys.executable, "-c",
1629 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07001630 pass
1631 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00001632 self.assertEqual(proc.returncode, 100)
1633
1634 def test_communicate_stdin(self):
1635 with subprocess.Popen([sys.executable, "-c",
1636 "import sys;"
1637 "sys.exit(sys.stdin.read() == 'context')"],
1638 stdin=subprocess.PIPE) as proc:
1639 proc.communicate(b"context")
1640 self.assertEqual(proc.returncode, 1)
1641
1642 def test_invalid_args(self):
1643 with self.assertRaises(EnvironmentError) as c:
1644 with subprocess.Popen(['nonexisting_i_hope'],
1645 stdout=subprocess.PIPE,
1646 stderr=subprocess.PIPE) as proc:
1647 pass
1648
1649 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1650 raise c.exception
1651
1652
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001653def test_main():
1654 unit_tests = (ProcessTestCase,
1655 POSIXProcessTestCase,
1656 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001657 CommandTests,
1658 ProcessTestCaseNoPoll,
1659 HelperFunctionTests,
1660 CommandsWithSpaces,
1661 ContextManagerTests)
1662
1663 support.run_unittest(*unit_tests)
1664 support.reap_children()
1665
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001666if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001667 unittest.main()