blob: 0f8d1ca9591d77560bcadc4065b97452f61d8a3d [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
Benjamin Petersonb870aa12011-12-10 12:44:25 -050016import gc
Benjamin Peterson964561b2011-12-10 12:31:42 -050017
18try:
19 import resource
20except ImportError:
21 resource = None
22
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000023mswindows = (sys.platform == "win32")
24
25#
26# Depends on the following external programs: Python
27#
28
29if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000030 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
31 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000032else:
33 SETBINARY = ''
34
Florent Xiclunab1e94e82010-02-27 22:12:37 +000035
36try:
37 mkstemp = tempfile.mkstemp
38except AttributeError:
39 # tempfile.mkstemp is not available
40 def mkstemp():
41 """Replacement for mkstemp, calling mktemp."""
42 fname = tempfile.mktemp()
43 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
44
Tim Peters3761e8d2004-10-13 04:07:12 +000045
Florent Xiclunac049d872010-03-27 22:47:23 +000046class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000047 def setUp(self):
48 # Try to minimize the number of children we have so this test
49 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000050 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000051
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000052 def tearDown(self):
53 for inst in subprocess._active:
54 inst.wait()
55 subprocess._cleanup()
56 self.assertFalse(subprocess._active, "subprocess._active not empty")
57
Florent Xiclunab1e94e82010-02-27 22:12:37 +000058 def assertStderrEqual(self, stderr, expected, msg=None):
59 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
60 # shutdown time. That frustrates tests trying to check stderr produced
61 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000062 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040063 # strip_python_stderr also strips whitespace, so we do too.
64 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000065 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000066
Florent Xiclunac049d872010-03-27 22:47:23 +000067
68class ProcessTestCase(BaseTestCase):
69
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000070 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000071 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000072 rc = subprocess.call([sys.executable, "-c",
73 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000074 self.assertEqual(rc, 47)
75
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040076 def test_call_timeout(self):
77 # call() function with timeout argument; we want to test that the child
78 # process gets killed when the timeout expires. If the child isn't
79 # killed, this call will deadlock since subprocess.call waits for the
80 # child.
81 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
82 [sys.executable, "-c", "while True: pass"],
83 timeout=0.1)
84
Peter Astrand454f7672005-01-01 09:36:35 +000085 def test_check_call_zero(self):
86 # check_call() function with zero return code
87 rc = subprocess.check_call([sys.executable, "-c",
88 "import sys; sys.exit(0)"])
89 self.assertEqual(rc, 0)
90
91 def test_check_call_nonzero(self):
92 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000093 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +000094 subprocess.check_call([sys.executable, "-c",
95 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000096 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000097
Georg Brandlf9734072008-12-07 15:30:06 +000098 def test_check_output(self):
99 # check_output() function with zero return code
100 output = subprocess.check_output(
101 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000102 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000103
104 def test_check_output_nonzero(self):
105 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000106 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000107 subprocess.check_output(
108 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000109 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000110
111 def test_check_output_stderr(self):
112 # check_output() function stderr redirected to stdout
113 output = subprocess.check_output(
114 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
115 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000116 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000117
118 def test_check_output_stdout_arg(self):
119 # check_output() function stderr redirected to stdout
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000120 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000121 output = subprocess.check_output(
122 [sys.executable, "-c", "print('will not be run')"],
123 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000124 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000125 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000126
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400127 def test_check_output_timeout(self):
128 # check_output() function with timeout arg
129 with self.assertRaises(subprocess.TimeoutExpired) as c:
130 output = subprocess.check_output(
131 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200132 "import sys, time\n"
133 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400134 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200135 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400136 # Some heavily loaded buildbots (sparc Debian 3.x) require
137 # this much time to start and print.
138 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400139 self.fail("Expected TimeoutExpired.")
140 self.assertEqual(c.exception.output, b'BDFL')
141
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000142 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000143 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000144 newenv = os.environ.copy()
145 newenv["FRUIT"] = "banana"
146 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000147 'import sys, os;'
148 'sys.exit(os.getenv("FRUIT")=="banana")'],
149 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000150 self.assertEqual(rc, 1)
151
Victor Stinner87b9bc32011-06-01 00:57:47 +0200152 def test_invalid_args(self):
153 # Popen() called with invalid arguments should raise TypeError
154 # but Popen.__del__ should not complain (issue #12085)
155 with support.captured_stderr() as s:
156 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
157 argcount = subprocess.Popen.__init__.__code__.co_argcount
158 too_many_args = [0] * (argcount + 1)
159 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
160 self.assertEqual(s.getvalue(), '')
161
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000162 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000163 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000164 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000165 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000166 self.addCleanup(p.stdout.close)
167 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000168 p.wait()
169 self.assertEqual(p.stdin, None)
170
171 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000172 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000173 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000174 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000175 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000176 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000177 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000178 self.addCleanup(p.stdin.close)
179 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000180 p.wait()
181 self.assertEqual(p.stdout, None)
182
183 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000184 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000185 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000186 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000187 self.addCleanup(p.stdout.close)
188 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000189 p.wait()
190 self.assertEqual(p.stderr, None)
191
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000192 def test_executable_with_cwd(self):
Florent Xicluna1d1ab972010-03-11 01:53:10 +0000193 python_dir = os.path.dirname(os.path.realpath(sys.executable))
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000194 p = subprocess.Popen(["somethingyoudonthave", "-c",
195 "import sys; sys.exit(47)"],
196 executable=sys.executable, cwd=python_dir)
197 p.wait()
198 self.assertEqual(p.returncode, 47)
199
200 @unittest.skipIf(sysconfig.is_python_build(),
201 "need an installed Python. See #7774")
202 def test_executable_without_cwd(self):
203 # For a normal installation, it should work without 'cwd'
204 # argument. For test runs in the build directory, see #7774.
205 p = subprocess.Popen(["somethingyoudonthave", "-c",
206 "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000207 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000208 p.wait()
209 self.assertEqual(p.returncode, 47)
210
211 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000212 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000213 p = subprocess.Popen([sys.executable, "-c",
214 'import sys; sys.exit(sys.stdin.read() == "pear")'],
215 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000216 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000217 p.stdin.close()
218 p.wait()
219 self.assertEqual(p.returncode, 1)
220
221 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000222 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000223 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000224 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000225 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000226 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000227 os.lseek(d, 0, 0)
228 p = subprocess.Popen([sys.executable, "-c",
229 'import sys; sys.exit(sys.stdin.read() == "pear")'],
230 stdin=d)
231 p.wait()
232 self.assertEqual(p.returncode, 1)
233
234 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000235 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000236 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000237 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000238 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000239 tf.seek(0)
240 p = subprocess.Popen([sys.executable, "-c",
241 'import sys; sys.exit(sys.stdin.read() == "pear")'],
242 stdin=tf)
243 p.wait()
244 self.assertEqual(p.returncode, 1)
245
246 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000247 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000248 p = subprocess.Popen([sys.executable, "-c",
249 'import sys; sys.stdout.write("orange")'],
250 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000251 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000252 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000253
254 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000255 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000256 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000257 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000258 d = tf.fileno()
259 p = subprocess.Popen([sys.executable, "-c",
260 'import sys; sys.stdout.write("orange")'],
261 stdout=d)
262 p.wait()
263 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000264 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000265
266 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000267 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000268 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000269 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000270 p = subprocess.Popen([sys.executable, "-c",
271 'import sys; sys.stdout.write("orange")'],
272 stdout=tf)
273 p.wait()
274 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000275 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000276
277 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000278 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000279 p = subprocess.Popen([sys.executable, "-c",
280 'import sys; sys.stderr.write("strawberry")'],
281 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000282 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000283 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000284
285 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000286 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000287 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000288 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000289 d = tf.fileno()
290 p = subprocess.Popen([sys.executable, "-c",
291 'import sys; sys.stderr.write("strawberry")'],
292 stderr=d)
293 p.wait()
294 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000295 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000296
297 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000298 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000299 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000300 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000301 p = subprocess.Popen([sys.executable, "-c",
302 'import sys; sys.stderr.write("strawberry")'],
303 stderr=tf)
304 p.wait()
305 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000306 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000307
308 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000309 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000310 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000311 'import sys;'
312 'sys.stdout.write("apple");'
313 'sys.stdout.flush();'
314 'sys.stderr.write("orange")'],
315 stdout=subprocess.PIPE,
316 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000317 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000318 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000319
320 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000321 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000322 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000323 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000324 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000325 'import sys;'
326 'sys.stdout.write("apple");'
327 'sys.stdout.flush();'
328 'sys.stderr.write("orange")'],
329 stdout=tf,
330 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000331 p.wait()
332 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000333 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000334
Thomas Wouters89f507f2006-12-13 04:49:30 +0000335 def test_stdout_filedes_of_stdout(self):
336 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000337 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000338 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000339 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000340
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200341 def test_stdout_devnull(self):
342 p = subprocess.Popen([sys.executable, "-c",
343 'for i in range(10240):'
344 'print("x" * 1024)'],
345 stdout=subprocess.DEVNULL)
346 p.wait()
347 self.assertEqual(p.stdout, None)
348
349 def test_stderr_devnull(self):
350 p = subprocess.Popen([sys.executable, "-c",
351 'import sys\n'
352 'for i in range(10240):'
353 'sys.stderr.write("x" * 1024)'],
354 stderr=subprocess.DEVNULL)
355 p.wait()
356 self.assertEqual(p.stderr, None)
357
358 def test_stdin_devnull(self):
359 p = subprocess.Popen([sys.executable, "-c",
360 'import sys;'
361 'sys.stdin.read(1)'],
362 stdin=subprocess.DEVNULL)
363 p.wait()
364 self.assertEqual(p.stdin, None)
365
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000366 def test_cwd(self):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000367 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000368 # We cannot use os.path.realpath to canonicalize the path,
369 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
370 cwd = os.getcwd()
371 os.chdir(tmpdir)
372 tmpdir = os.getcwd()
373 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000374 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000375 'import sys,os;'
376 'sys.stdout.write(os.getcwd())'],
377 stdout=subprocess.PIPE,
378 cwd=tmpdir)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000379 self.addCleanup(p.stdout.close)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000380 normcase = os.path.normcase
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000381 self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
382 normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000383
384 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000385 newenv = os.environ.copy()
386 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200387 with subprocess.Popen([sys.executable, "-c",
388 'import sys,os;'
389 'sys.stdout.write(os.getenv("FRUIT"))'],
390 stdout=subprocess.PIPE,
391 env=newenv) as p:
392 stdout, stderr = p.communicate()
393 self.assertEqual(stdout, b"orange")
394
Victor Stinner62d51182011-06-23 01:02:25 +0200395 # Windows requires at least the SYSTEMROOT environment variable to start
396 # Python
397 @unittest.skipIf(sys.platform == 'win32',
398 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200399 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200400 'the python library cannot be loaded '
401 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200402 def test_empty_env(self):
403 with subprocess.Popen([sys.executable, "-c",
404 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200405 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200406 stdout=subprocess.PIPE,
407 env={}) as p:
408 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200409 self.assertIn(stdout.strip(),
410 (b"[]",
411 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
412 # environment
413 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000414
Peter Astrandcbac93c2005-03-03 20:24:28 +0000415 def test_communicate_stdin(self):
416 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000417 'import sys;'
418 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000419 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000420 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000421 self.assertEqual(p.returncode, 1)
422
423 def test_communicate_stdout(self):
424 p = subprocess.Popen([sys.executable, "-c",
425 'import sys; sys.stdout.write("pineapple")'],
426 stdout=subprocess.PIPE)
427 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000428 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000429 self.assertEqual(stderr, None)
430
431 def test_communicate_stderr(self):
432 p = subprocess.Popen([sys.executable, "-c",
433 'import sys; sys.stderr.write("pineapple")'],
434 stderr=subprocess.PIPE)
435 (stdout, stderr) = p.communicate()
436 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000437 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000438
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000439 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000440 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000441 'import sys,os;'
442 'sys.stderr.write("pineapple");'
443 'sys.stdout.write(sys.stdin.read())'],
444 stdin=subprocess.PIPE,
445 stdout=subprocess.PIPE,
446 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000447 self.addCleanup(p.stdout.close)
448 self.addCleanup(p.stderr.close)
449 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000450 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000451 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000452 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000453
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400454 def test_communicate_timeout(self):
455 p = subprocess.Popen([sys.executable, "-c",
456 'import sys,os,time;'
457 'sys.stderr.write("pineapple\\n");'
458 'time.sleep(1);'
459 'sys.stderr.write("pear\\n");'
460 'sys.stdout.write(sys.stdin.read())'],
461 universal_newlines=True,
462 stdin=subprocess.PIPE,
463 stdout=subprocess.PIPE,
464 stderr=subprocess.PIPE)
465 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
466 timeout=0.3)
467 # Make sure we can keep waiting for it, and that we get the whole output
468 # after it completes.
469 (stdout, stderr) = p.communicate()
470 self.assertEqual(stdout, "banana")
471 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
472
473 def test_communicate_timeout_large_ouput(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200474 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400475 p = subprocess.Popen([sys.executable, "-c",
476 'import sys,os,time;'
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 'time.sleep(0.2);'
483 'sys.stdout.write("a" * (64 * 1024));'],
484 stdout=subprocess.PIPE)
485 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
486 (stdout, _) = p.communicate()
487 self.assertEqual(len(stdout), 4 * 64 * 1024)
488
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000489 # Test for the fd leak reported in http://bugs.python.org/issue2791.
490 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000491 for stdin_pipe in (False, True):
492 for stdout_pipe in (False, True):
493 for stderr_pipe in (False, True):
494 options = {}
495 if stdin_pipe:
496 options['stdin'] = subprocess.PIPE
497 if stdout_pipe:
498 options['stdout'] = subprocess.PIPE
499 if stderr_pipe:
500 options['stderr'] = subprocess.PIPE
501 if not options:
502 continue
503 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
504 p.communicate()
505 if p.stdin is not None:
506 self.assertTrue(p.stdin.closed)
507 if p.stdout is not None:
508 self.assertTrue(p.stdout.closed)
509 if p.stderr is not None:
510 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000511
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000512 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000513 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000514 p = subprocess.Popen([sys.executable, "-c",
515 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000516 (stdout, stderr) = p.communicate()
517 self.assertEqual(stdout, None)
518 self.assertEqual(stderr, None)
519
520 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000521 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000522 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000523 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000524 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000525 os.close(x)
526 os.close(y)
527 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000528 'import sys,os;'
529 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200530 'sys.stderr.write("x" * %d);'
531 'sys.stdout.write(sys.stdin.read())' %
532 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000533 stdin=subprocess.PIPE,
534 stdout=subprocess.PIPE,
535 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000536 self.addCleanup(p.stdout.close)
537 self.addCleanup(p.stderr.close)
538 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200539 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000540 (stdout, stderr) = p.communicate(string_to_write)
541 self.assertEqual(stdout, string_to_write)
542
543 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000544 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000545 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000546 'import sys,os;'
547 'sys.stdout.write(sys.stdin.read())'],
548 stdin=subprocess.PIPE,
549 stdout=subprocess.PIPE,
550 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000551 self.addCleanup(p.stdout.close)
552 self.addCleanup(p.stderr.close)
553 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000554 p.stdin.write(b"banana")
555 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000556 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000557 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000558
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000559 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000560 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000561 'import sys,os;' + SETBINARY +
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200562 'sys.stdout.write(sys.stdin.readline());'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000563 'sys.stdout.flush();'
564 'sys.stdout.write("line2\\n");'
565 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200566 'sys.stdout.write(sys.stdin.read());'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000567 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200568 'sys.stdout.write("line4\\n");'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000569 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200570 'sys.stdout.write("line5\\r\\n");'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000571 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200572 'sys.stdout.write("line6\\r");'
573 'sys.stdout.flush();'
574 'sys.stdout.write("\\nline7");'
575 'sys.stdout.flush();'
576 'sys.stdout.write("\\nline8");'],
577 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000578 stdout=subprocess.PIPE,
579 universal_newlines=1)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200580 p.stdin.write("line1\n")
581 self.assertEqual(p.stdout.readline(), "line1\n")
582 p.stdin.write("line3\n")
583 p.stdin.close()
Brian Curtin3c6a9512010-11-05 03:58:52 +0000584 self.addCleanup(p.stdout.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200585 self.assertEqual(p.stdout.readline(),
586 "line2\n")
587 self.assertEqual(p.stdout.read(6),
588 "line3\n")
589 self.assertEqual(p.stdout.read(),
590 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000591
592 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000593 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000594 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000595 'import sys,os;' + SETBINARY +
Guido van Rossum98297ee2007-11-06 21:34:58 +0000596 'sys.stdout.write("line2\\n");'
597 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200598 'sys.stdout.write("line4\\n");'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000599 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200600 'sys.stdout.write("line5\\r\\n");'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000601 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200602 'sys.stdout.write("line6\\r");'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000603 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200604 'sys.stdout.write("\\nline7");'
605 'sys.stdout.flush();'
606 'sys.stdout.write("\\nline8");'],
607 stderr=subprocess.PIPE,
608 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000609 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000610 self.addCleanup(p.stdout.close)
611 self.addCleanup(p.stderr.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200612 # BUG: can't give a non-empty stdin because it breaks both the
613 # select- and poll-based communicate() implementations.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000614 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200615 self.assertEqual(stdout,
616 "line2\nline4\nline5\nline6\nline7\nline8")
617
618 def test_universal_newlines_communicate_stdin(self):
619 # universal newlines through communicate(), with only stdin
620 p = subprocess.Popen([sys.executable, "-c",
621 'import sys,os;' + SETBINARY + '''\nif True:
622 s = sys.stdin.readline()
623 assert s == "line1\\n", repr(s)
624 s = sys.stdin.read()
625 assert s == "line3\\n", repr(s)
626 '''],
627 stdin=subprocess.PIPE,
628 universal_newlines=1)
629 (stdout, stderr) = p.communicate("line1\nline3\n")
630 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000631
632 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000633 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000634 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000635 max_handles = 1026 # too much for most UNIX systems
636 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000637 max_handles = 2050 # too much for (at least some) Windows setups
638 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400639 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000640 try:
641 for i in range(max_handles):
642 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400643 tmpfile = os.path.join(tmpdir, support.TESTFN)
644 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000645 except OSError as e:
646 if e.errno != errno.EMFILE:
647 raise
648 break
649 else:
650 self.skipTest("failed to reach the file descriptor limit "
651 "(tried %d)" % max_handles)
652 # Close a couple of them (should be enough for a subprocess)
653 for i in range(10):
654 os.close(handles.pop())
655 # Loop creating some subprocesses. If one of them leaks some fds,
656 # the next loop iteration will fail by reaching the max fd limit.
657 for i in range(15):
658 p = subprocess.Popen([sys.executable, "-c",
659 "import sys;"
660 "sys.stdout.write(sys.stdin.read())"],
661 stdin=subprocess.PIPE,
662 stdout=subprocess.PIPE,
663 stderr=subprocess.PIPE)
664 data = p.communicate(b"lime")[0]
665 self.assertEqual(data, b"lime")
666 finally:
667 for h in handles:
668 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400669 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000670
671 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000672 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
673 '"a b c" d e')
674 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
675 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000676 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
677 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000678 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
679 'a\\\\\\b "de fg" h')
680 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
681 'a\\\\\\"b c d')
682 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
683 '"a\\\\b c" d e')
684 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
685 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000686 self.assertEqual(subprocess.list2cmdline(['ab', '']),
687 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000688
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000689 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200690 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +0200691 "import os; os.read(0, 1)"],
692 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200693 self.addCleanup(p.stdin.close)
694 self.assertIsNone(p.poll())
695 os.write(p.stdin.fileno(), b'A')
696 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000697 # Subsequent invocations should just return the returncode
698 self.assertEqual(p.poll(), 0)
699
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000700 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200701 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000702 self.assertEqual(p.wait(), 0)
703 # Subsequent invocations should just return the returncode
704 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000705
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400706 def test_wait_timeout(self):
707 p = subprocess.Popen([sys.executable,
Reid Kleckner93479cc2011-03-14 19:32:41 -0400708 "-c", "import time; time.sleep(0.1)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -0400709 with self.assertRaises(subprocess.TimeoutExpired) as c:
710 p.wait(timeout=0.01)
711 self.assertIn("0.01", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -0400712 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
713 # time to start.
714 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400715
Peter Astrand738131d2004-11-30 21:04:45 +0000716 def test_invalid_bufsize(self):
717 # an invalid type of the bufsize argument should raise
718 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000719 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000720 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000721
Guido van Rossum46a05a72007-06-07 21:56:45 +0000722 def test_bufsize_is_none(self):
723 # bufsize=None should be the same as bufsize=0.
724 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
725 self.assertEqual(p.wait(), 0)
726 # Again with keyword arg
727 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
728 self.assertEqual(p.wait(), 0)
729
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000730 def test_leaking_fds_on_error(self):
731 # see bug #5179: Popen leaks file descriptors to PIPEs if
732 # the child fails to execute; this will eventually exhaust
733 # the maximum number of open fds. 1024 seems a very common
734 # value for that limit, but Windows has 2048, so we loop
735 # 1024 times (each call leaked two fds).
736 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000737 # Windows raises IOError. Others raise OSError.
738 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000739 subprocess.Popen(['nonexisting_i_hope'],
740 stdout=subprocess.PIPE,
741 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400742 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400743 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000744 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000745
Victor Stinnerb3693582010-05-21 20:13:12 +0000746 def test_issue8780(self):
747 # Ensure that stdout is inherited from the parent
748 # if stdout=PIPE is not used
749 code = ';'.join((
750 'import subprocess, sys',
751 'retcode = subprocess.call('
752 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
753 'assert retcode == 0'))
754 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000755 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000756
Tim Goldenaf5ac392010-08-06 13:03:56 +0000757 def test_handles_closed_on_exception(self):
758 # If CreateProcess exits with an error, ensure the
759 # duplicate output handles are released
760 ifhandle, ifname = mkstemp()
761 ofhandle, ofname = mkstemp()
762 efhandle, efname = mkstemp()
763 try:
764 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
765 stderr=efhandle)
766 except OSError:
767 os.close(ifhandle)
768 os.remove(ifname)
769 os.close(ofhandle)
770 os.remove(ofname)
771 os.close(efhandle)
772 os.remove(efname)
773 self.assertFalse(os.path.exists(ifname))
774 self.assertFalse(os.path.exists(ofname))
775 self.assertFalse(os.path.exists(efname))
776
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200777 def test_communicate_epipe(self):
778 # Issue 10963: communicate() should hide EPIPE
779 p = subprocess.Popen([sys.executable, "-c", 'pass'],
780 stdin=subprocess.PIPE,
781 stdout=subprocess.PIPE,
782 stderr=subprocess.PIPE)
783 self.addCleanup(p.stdout.close)
784 self.addCleanup(p.stderr.close)
785 self.addCleanup(p.stdin.close)
786 p.communicate(b"x" * 2**20)
787
788 def test_communicate_epipe_only_stdin(self):
789 # Issue 10963: communicate() should hide EPIPE
790 p = subprocess.Popen([sys.executable, "-c", 'pass'],
791 stdin=subprocess.PIPE)
792 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200793 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200794 p.communicate(b"x" * 2**20)
795
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200796 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
797 "Requires signal.SIGUSR1")
798 @unittest.skipUnless(hasattr(os, 'kill'),
799 "Requires os.kill")
800 @unittest.skipUnless(hasattr(os, 'getppid'),
801 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200802 def test_communicate_eintr(self):
803 # Issue #12493: communicate() should handle EINTR
804 def handler(signum, frame):
805 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200806 old_handler = signal.signal(signal.SIGUSR1, handler)
807 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200808
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200809 args = [sys.executable, "-c",
810 'import os, signal;'
811 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200812 for stream in ('stdout', 'stderr'):
813 kw = {stream: subprocess.PIPE}
814 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200815 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200816 process.communicate()
817
Tim Peterse718f612004-10-12 21:51:32 +0000818
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000819# context manager
820class _SuppressCoreFiles(object):
821 """Try to prevent core files from being created."""
822 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000823
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000824 def __enter__(self):
825 """Try to save previous ulimit, then set it to (0, 0)."""
Benjamin Peterson964561b2011-12-10 12:31:42 -0500826 if resource is not None:
827 try:
828 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
829 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
830 except (ValueError, resource.error):
831 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000832
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000833 if sys.platform == 'darwin':
834 # Check if the 'Crash Reporter' on OSX was configured
835 # in 'Developer' mode and warn that it will get triggered
836 # when it is.
837 #
838 # This assumes that this context manager is used in tests
839 # that might trigger the next manager.
840 value = subprocess.Popen(['/usr/bin/defaults', 'read',
841 'com.apple.CrashReporter', 'DialogType'],
842 stdout=subprocess.PIPE).communicate()[0]
843 if value.strip() == b'developer':
844 print("this tests triggers the Crash Reporter, "
845 "that is intentional", end='')
846 sys.stdout.flush()
847
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000848 def __exit__(self, *args):
849 """Return core file behavior to default."""
850 if self.old_limit is None:
851 return
Benjamin Peterson964561b2011-12-10 12:31:42 -0500852 if resource is not None:
853 try:
854 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
855 except (ValueError, resource.error):
856 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000857
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000858
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000859@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000860class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000861
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000862 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000863 nonexistent_dir = "/_this/pa.th/does/not/exist"
864 try:
865 os.chdir(nonexistent_dir)
866 except OSError as e:
867 # This avoids hard coding the errno value or the OS perror()
868 # string and instead capture the exception that we want to see
869 # below for comparison.
870 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000871 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000872 else:
873 self.fail("chdir to nonexistant directory %s succeeded." %
874 nonexistent_dir)
875
876 # Error in the child re-raised in the parent.
877 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000878 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000879 cwd=nonexistent_dir)
880 except OSError as e:
881 # Test that the child process chdir failure actually makes
882 # it up to the parent process as the correct exception.
883 self.assertEqual(desired_exception.errno, e.errno)
884 self.assertEqual(desired_exception.strerror, e.strerror)
885 else:
886 self.fail("Expected OSError: %s" % desired_exception)
887
888 def test_restore_signals(self):
889 # Code coverage for both values of restore_signals to make sure it
890 # at least does not blow up.
891 # A test for behavior would be complex. Contributions welcome.
892 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
893 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
894
895 def test_start_new_session(self):
896 # For code coverage of calling setsid(). We don't care if we get an
897 # EPERM error from it depending on the test execution environment, that
898 # still indicates that it was called.
899 try:
900 output = subprocess.check_output(
901 [sys.executable, "-c",
902 "import os; print(os.getpgid(os.getpid()))"],
903 start_new_session=True)
904 except OSError as e:
905 if e.errno != errno.EPERM:
906 raise
907 else:
908 parent_pgid = os.getpgid(os.getpid())
909 child_pgid = int(output)
910 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000911
912 def test_run_abort(self):
913 # returncode handles signal termination
914 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000915 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000916 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000917 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000918 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000919
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000920 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000921 # DISCLAIMER: Setting environment variables is *not* a good use
922 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000923 p = subprocess.Popen([sys.executable, "-c",
924 'import sys,os;'
925 'sys.stdout.write(os.getenv("FRUIT"))'],
926 stdout=subprocess.PIPE,
927 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000928 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000929 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000930
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000931 def test_preexec_exception(self):
932 def raise_it():
933 raise ValueError("What if two swallows carried a coconut?")
934 try:
935 p = subprocess.Popen([sys.executable, "-c", ""],
936 preexec_fn=raise_it)
937 except RuntimeError as e:
938 self.assertTrue(
939 subprocess._posixsubprocess,
940 "Expected a ValueError from the preexec_fn")
941 except ValueError as e:
942 self.assertIn("coconut", e.args[0])
943 else:
944 self.fail("Exception raised by preexec_fn did not make it "
945 "to the parent process.")
946
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000947 def test_preexec_gc_module_failure(self):
948 # This tests the code that disables garbage collection if the child
949 # process will execute any Python.
950 def raise_runtime_error():
951 raise RuntimeError("this shouldn't escape")
952 enabled = gc.isenabled()
953 orig_gc_disable = gc.disable
954 orig_gc_isenabled = gc.isenabled
955 try:
956 gc.disable()
957 self.assertFalse(gc.isenabled())
958 subprocess.call([sys.executable, '-c', ''],
959 preexec_fn=lambda: None)
960 self.assertFalse(gc.isenabled(),
961 "Popen enabled gc when it shouldn't.")
962
963 gc.enable()
964 self.assertTrue(gc.isenabled())
965 subprocess.call([sys.executable, '-c', ''],
966 preexec_fn=lambda: None)
967 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
968
969 gc.disable = raise_runtime_error
970 self.assertRaises(RuntimeError, subprocess.Popen,
971 [sys.executable, '-c', ''],
972 preexec_fn=lambda: None)
973
974 del gc.isenabled # force an AttributeError
975 self.assertRaises(AttributeError, subprocess.Popen,
976 [sys.executable, '-c', ''],
977 preexec_fn=lambda: None)
978 finally:
979 gc.disable = orig_gc_disable
980 gc.isenabled = orig_gc_isenabled
981 if not enabled:
982 gc.disable()
983
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000984 def test_args_string(self):
985 # args is a string
986 fd, fname = mkstemp()
987 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000988 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000989 fobj.write("#!/bin/sh\n")
990 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
991 sys.executable)
992 os.chmod(fname, 0o700)
993 p = subprocess.Popen(fname)
994 p.wait()
995 os.remove(fname)
996 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000997
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000998 def test_invalid_args(self):
999 # invalid arguments should raise ValueError
1000 self.assertRaises(ValueError, subprocess.call,
1001 [sys.executable, "-c",
1002 "import sys; sys.exit(47)"],
1003 startupinfo=47)
1004 self.assertRaises(ValueError, subprocess.call,
1005 [sys.executable, "-c",
1006 "import sys; sys.exit(47)"],
1007 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001008
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001009 def test_shell_sequence(self):
1010 # Run command through the shell (sequence)
1011 newenv = os.environ.copy()
1012 newenv["FRUIT"] = "apple"
1013 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1014 stdout=subprocess.PIPE,
1015 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001016 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001017 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001018
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001019 def test_shell_string(self):
1020 # Run command through the shell (string)
1021 newenv = os.environ.copy()
1022 newenv["FRUIT"] = "apple"
1023 p = subprocess.Popen("echo $FRUIT", shell=1,
1024 stdout=subprocess.PIPE,
1025 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001026 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001027 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001028
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001029 def test_call_string(self):
1030 # call() function with string argument on UNIX
1031 fd, fname = mkstemp()
1032 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001033 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001034 fobj.write("#!/bin/sh\n")
1035 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1036 sys.executable)
1037 os.chmod(fname, 0o700)
1038 rc = subprocess.call(fname)
1039 os.remove(fname)
1040 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001041
Stefan Krah9542cc62010-07-19 14:20:53 +00001042 def test_specific_shell(self):
1043 # Issue #9265: Incorrect name passed as arg[0].
1044 shells = []
1045 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1046 for name in ['bash', 'ksh']:
1047 sh = os.path.join(prefix, name)
1048 if os.path.isfile(sh):
1049 shells.append(sh)
1050 if not shells: # Will probably work for any shell but csh.
1051 self.skipTest("bash or ksh required for this test")
1052 sh = '/bin/sh'
1053 if os.path.isfile(sh) and not os.path.islink(sh):
1054 # Test will fail if /bin/sh is a symlink to csh.
1055 shells.append(sh)
1056 for sh in shells:
1057 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1058 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001059 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001060 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1061
Florent Xicluna4886d242010-03-08 13:27:26 +00001062 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001063 # Do not inherit file handles from the parent.
1064 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001065 p = subprocess.Popen([sys.executable, "-c", """if 1:
1066 import sys, time
1067 sys.stdout.write('x\\n')
1068 sys.stdout.flush()
1069 time.sleep(30)
1070 """],
1071 close_fds=True,
1072 stdin=subprocess.PIPE,
1073 stdout=subprocess.PIPE,
1074 stderr=subprocess.PIPE)
1075 # Wait for the interpreter to be completely initialized before
1076 # sending any signal.
1077 p.stdout.read(1)
1078 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001079 return p
1080
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001081 def _kill_dead_process(self, method, *args):
1082 # Do not inherit file handles from the parent.
1083 # It should fix failures on some platforms.
1084 p = subprocess.Popen([sys.executable, "-c", """if 1:
1085 import sys, time
1086 sys.stdout.write('x\\n')
1087 sys.stdout.flush()
1088 """],
1089 close_fds=True,
1090 stdin=subprocess.PIPE,
1091 stdout=subprocess.PIPE,
1092 stderr=subprocess.PIPE)
1093 # Wait for the interpreter to be completely initialized before
1094 # sending any signal.
1095 p.stdout.read(1)
1096 # The process should end after this
1097 time.sleep(1)
1098 # This shouldn't raise even though the child is now dead
1099 getattr(p, method)(*args)
1100 p.communicate()
1101
Florent Xicluna4886d242010-03-08 13:27:26 +00001102 def test_send_signal(self):
1103 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001104 _, stderr = p.communicate()
1105 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001106 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001107
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001108 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001109 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001110 _, stderr = p.communicate()
1111 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001112 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001113
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001114 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001115 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001116 _, stderr = p.communicate()
1117 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001118 self.assertEqual(p.wait(), -signal.SIGTERM)
1119
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001120 def test_send_signal_dead(self):
1121 # Sending a signal to a dead process
1122 self._kill_dead_process('send_signal', signal.SIGINT)
1123
1124 def test_kill_dead(self):
1125 # Killing a dead process
1126 self._kill_dead_process('kill')
1127
1128 def test_terminate_dead(self):
1129 # Terminating a dead process
1130 self._kill_dead_process('terminate')
1131
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001132 def check_close_std_fds(self, fds):
1133 # Issue #9905: test that subprocess pipes still work properly with
1134 # some standard fds closed
1135 stdin = 0
1136 newfds = []
1137 for a in fds:
1138 b = os.dup(a)
1139 newfds.append(b)
1140 if a == 0:
1141 stdin = b
1142 try:
1143 for fd in fds:
1144 os.close(fd)
1145 out, err = subprocess.Popen([sys.executable, "-c",
1146 'import sys;'
1147 'sys.stdout.write("apple");'
1148 'sys.stdout.flush();'
1149 'sys.stderr.write("orange")'],
1150 stdin=stdin,
1151 stdout=subprocess.PIPE,
1152 stderr=subprocess.PIPE).communicate()
1153 err = support.strip_python_stderr(err)
1154 self.assertEqual((out, err), (b'apple', b'orange'))
1155 finally:
1156 for b, a in zip(newfds, fds):
1157 os.dup2(b, a)
1158 for b in newfds:
1159 os.close(b)
1160
1161 def test_close_fd_0(self):
1162 self.check_close_std_fds([0])
1163
1164 def test_close_fd_1(self):
1165 self.check_close_std_fds([1])
1166
1167 def test_close_fd_2(self):
1168 self.check_close_std_fds([2])
1169
1170 def test_close_fds_0_1(self):
1171 self.check_close_std_fds([0, 1])
1172
1173 def test_close_fds_0_2(self):
1174 self.check_close_std_fds([0, 2])
1175
1176 def test_close_fds_1_2(self):
1177 self.check_close_std_fds([1, 2])
1178
1179 def test_close_fds_0_1_2(self):
1180 # Issue #10806: test that subprocess pipes still work properly with
1181 # all standard fds closed.
1182 self.check_close_std_fds([0, 1, 2])
1183
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001184 def test_remapping_std_fds(self):
1185 # open up some temporary files
1186 temps = [mkstemp() for i in range(3)]
1187 try:
1188 temp_fds = [fd for fd, fname in temps]
1189
1190 # unlink the files -- we won't need to reopen them
1191 for fd, fname in temps:
1192 os.unlink(fname)
1193
1194 # write some data to what will become stdin, and rewind
1195 os.write(temp_fds[1], b"STDIN")
1196 os.lseek(temp_fds[1], 0, 0)
1197
1198 # move the standard file descriptors out of the way
1199 saved_fds = [os.dup(fd) for fd in range(3)]
1200 try:
1201 # duplicate the file objects over the standard fd's
1202 for fd, temp_fd in enumerate(temp_fds):
1203 os.dup2(temp_fd, fd)
1204
1205 # now use those files in the "wrong" order, so that subprocess
1206 # has to rearrange them in the child
1207 p = subprocess.Popen([sys.executable, "-c",
1208 'import sys; got = sys.stdin.read();'
1209 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1210 stdin=temp_fds[1],
1211 stdout=temp_fds[2],
1212 stderr=temp_fds[0])
1213 p.wait()
1214 finally:
1215 # restore the original fd's underneath sys.stdin, etc.
1216 for std, saved in enumerate(saved_fds):
1217 os.dup2(saved, std)
1218 os.close(saved)
1219
1220 for fd in temp_fds:
1221 os.lseek(fd, 0, 0)
1222
1223 out = os.read(temp_fds[2], 1024)
1224 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1225 self.assertEqual(out, b"got STDIN")
1226 self.assertEqual(err, b"err")
1227
1228 finally:
1229 for fd in temp_fds:
1230 os.close(fd)
1231
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001232 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1233 # open up some temporary files
1234 temps = [mkstemp() for i in range(3)]
1235 temp_fds = [fd for fd, fname in temps]
1236 try:
1237 # unlink the files -- we won't need to reopen them
1238 for fd, fname in temps:
1239 os.unlink(fname)
1240
1241 # save a copy of the standard file descriptors
1242 saved_fds = [os.dup(fd) for fd in range(3)]
1243 try:
1244 # duplicate the temp files over the standard fd's 0, 1, 2
1245 for fd, temp_fd in enumerate(temp_fds):
1246 os.dup2(temp_fd, fd)
1247
1248 # write some data to what will become stdin, and rewind
1249 os.write(stdin_no, b"STDIN")
1250 os.lseek(stdin_no, 0, 0)
1251
1252 # now use those files in the given order, so that subprocess
1253 # has to rearrange them in the child
1254 p = subprocess.Popen([sys.executable, "-c",
1255 'import sys; got = sys.stdin.read();'
1256 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1257 stdin=stdin_no,
1258 stdout=stdout_no,
1259 stderr=stderr_no)
1260 p.wait()
1261
1262 for fd in temp_fds:
1263 os.lseek(fd, 0, 0)
1264
1265 out = os.read(stdout_no, 1024)
1266 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1267 finally:
1268 for std, saved in enumerate(saved_fds):
1269 os.dup2(saved, std)
1270 os.close(saved)
1271
1272 self.assertEqual(out, b"got STDIN")
1273 self.assertEqual(err, b"err")
1274
1275 finally:
1276 for fd in temp_fds:
1277 os.close(fd)
1278
1279 # When duping fds, if there arises a situation where one of the fds is
1280 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1281 # This tests all combinations of this.
1282 def test_swap_fds(self):
1283 self.check_swap_fds(0, 1, 2)
1284 self.check_swap_fds(0, 2, 1)
1285 self.check_swap_fds(1, 0, 2)
1286 self.check_swap_fds(1, 2, 0)
1287 self.check_swap_fds(2, 0, 1)
1288 self.check_swap_fds(2, 1, 0)
1289
Victor Stinner13bb71c2010-04-23 21:41:56 +00001290 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001291 def prepare():
1292 raise ValueError("surrogate:\uDCff")
1293
1294 try:
1295 subprocess.call(
1296 [sys.executable, "-c", "pass"],
1297 preexec_fn=prepare)
1298 except ValueError as err:
1299 # Pure Python implementations keeps the message
1300 self.assertIsNone(subprocess._posixsubprocess)
1301 self.assertEqual(str(err), "surrogate:\uDCff")
1302 except RuntimeError as err:
1303 # _posixsubprocess uses a default message
1304 self.assertIsNotNone(subprocess._posixsubprocess)
1305 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1306 else:
1307 self.fail("Expected ValueError or RuntimeError")
1308
Victor Stinner13bb71c2010-04-23 21:41:56 +00001309 def test_undecodable_env(self):
1310 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001311 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001312 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001313 env = os.environ.copy()
1314 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001315 # Use C locale to get ascii for the locale encoding to force
1316 # surrogate-escaping of \xFF in the child process; otherwise it can
1317 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001318 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001319 stdout = subprocess.check_output(
1320 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001321 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001322 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001323 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001324
1325 # test bytes
1326 key = key.encode("ascii", "surrogateescape")
1327 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001328 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001329 env = os.environ.copy()
1330 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001331 stdout = subprocess.check_output(
1332 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001333 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001334 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001335 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001336
Victor Stinnerb745a742010-05-18 17:17:23 +00001337 def test_bytes_program(self):
1338 abs_program = os.fsencode(sys.executable)
1339 path, program = os.path.split(sys.executable)
1340 program = os.fsencode(program)
1341
1342 # absolute bytes path
1343 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001344 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001345
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001346 # absolute bytes path as a string
1347 cmd = b"'" + abs_program + b"' -c pass"
1348 exitcode = subprocess.call(cmd, shell=True)
1349 self.assertEqual(exitcode, 0)
1350
Victor Stinnerb745a742010-05-18 17:17:23 +00001351 # bytes program, unicode PATH
1352 env = os.environ.copy()
1353 env["PATH"] = path
1354 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001355 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001356
1357 # bytes program, bytes PATH
1358 envb = os.environb.copy()
1359 envb[b"PATH"] = os.fsencode(path)
1360 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001361 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001362
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001363 def test_pipe_cloexec(self):
1364 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1365 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1366
1367 p1 = subprocess.Popen([sys.executable, sleeper],
1368 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1369 stderr=subprocess.PIPE, close_fds=False)
1370
1371 self.addCleanup(p1.communicate, b'')
1372
1373 p2 = subprocess.Popen([sys.executable, fd_status],
1374 stdout=subprocess.PIPE, close_fds=False)
1375
1376 output, error = p2.communicate()
1377 result_fds = set(map(int, output.split(b',')))
1378 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1379 p1.stderr.fileno()])
1380
1381 self.assertFalse(result_fds & unwanted_fds,
1382 "Expected no fds from %r to be open in child, "
1383 "found %r" %
1384 (unwanted_fds, result_fds & unwanted_fds))
1385
1386 def test_pipe_cloexec_real_tools(self):
1387 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1388 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1389
1390 subdata = b'zxcvbn'
1391 data = subdata * 4 + b'\n'
1392
1393 p1 = subprocess.Popen([sys.executable, qcat],
1394 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1395 close_fds=False)
1396
1397 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1398 stdin=p1.stdout, stdout=subprocess.PIPE,
1399 close_fds=False)
1400
1401 self.addCleanup(p1.wait)
1402 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001403 def kill_p1():
1404 try:
1405 p1.terminate()
1406 except ProcessLookupError:
1407 pass
1408 def kill_p2():
1409 try:
1410 p2.terminate()
1411 except ProcessLookupError:
1412 pass
1413 self.addCleanup(kill_p1)
1414 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001415
1416 p1.stdin.write(data)
1417 p1.stdin.close()
1418
1419 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1420
1421 self.assertTrue(readfiles, "The child hung")
1422 self.assertEqual(p2.stdout.read(), data)
1423
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001424 p1.stdout.close()
1425 p2.stdout.close()
1426
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001427 def test_close_fds(self):
1428 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1429
1430 fds = os.pipe()
1431 self.addCleanup(os.close, fds[0])
1432 self.addCleanup(os.close, fds[1])
1433
1434 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001435 # add a bunch more fds
1436 for _ in range(9):
1437 fd = os.open("/dev/null", os.O_RDONLY)
1438 self.addCleanup(os.close, fd)
1439 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001440
1441 p = subprocess.Popen([sys.executable, fd_status],
1442 stdout=subprocess.PIPE, close_fds=False)
1443 output, ignored = p.communicate()
1444 remaining_fds = set(map(int, output.split(b',')))
1445
1446 self.assertEqual(remaining_fds & open_fds, open_fds,
1447 "Some fds were closed")
1448
1449 p = subprocess.Popen([sys.executable, fd_status],
1450 stdout=subprocess.PIPE, close_fds=True)
1451 output, ignored = p.communicate()
1452 remaining_fds = set(map(int, output.split(b',')))
1453
1454 self.assertFalse(remaining_fds & open_fds,
1455 "Some fds were left open")
1456 self.assertIn(1, remaining_fds, "Subprocess failed")
1457
Gregory P. Smith8facece2012-01-21 14:01:08 -08001458 # Keep some of the fd's we opened open in the subprocess.
1459 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1460 fds_to_keep = set(open_fds.pop() for _ in range(8))
1461 p = subprocess.Popen([sys.executable, fd_status],
1462 stdout=subprocess.PIPE, close_fds=True,
1463 pass_fds=())
1464 output, ignored = p.communicate()
1465 remaining_fds = set(map(int, output.split(b',')))
1466
1467 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1468 "Some fds not in pass_fds were left open")
1469 self.assertIn(1, remaining_fds, "Subprocess failed")
1470
Victor Stinner88701e22011-06-01 13:13:04 +02001471 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1472 # descriptor of a pipe closed in the parent process is valid in the
1473 # child process according to fstat(), but the mode of the file
1474 # descriptor is invalid, and read or write raise an error.
1475 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001476 def test_pass_fds(self):
1477 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1478
1479 open_fds = set()
1480
1481 for x in range(5):
1482 fds = os.pipe()
1483 self.addCleanup(os.close, fds[0])
1484 self.addCleanup(os.close, fds[1])
1485 open_fds.update(fds)
1486
1487 for fd in open_fds:
1488 p = subprocess.Popen([sys.executable, fd_status],
1489 stdout=subprocess.PIPE, close_fds=True,
1490 pass_fds=(fd, ))
1491 output, ignored = p.communicate()
1492
1493 remaining_fds = set(map(int, output.split(b',')))
1494 to_be_closed = open_fds - {fd}
1495
1496 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1497 self.assertFalse(remaining_fds & to_be_closed,
1498 "fd to be closed passed")
1499
1500 # pass_fds overrides close_fds with a warning.
1501 with self.assertWarns(RuntimeWarning) as context:
1502 self.assertFalse(subprocess.call(
1503 [sys.executable, "-c", "import sys; sys.exit(0)"],
1504 close_fds=False, pass_fds=(fd, )))
1505 self.assertIn('overriding close_fds', str(context.warning))
1506
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001507 def test_stdout_stdin_are_single_inout_fd(self):
1508 with io.open(os.devnull, "r+") as inout:
1509 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1510 stdout=inout, stdin=inout)
1511 p.wait()
1512
1513 def test_stdout_stderr_are_single_inout_fd(self):
1514 with io.open(os.devnull, "r+") as inout:
1515 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1516 stdout=inout, stderr=inout)
1517 p.wait()
1518
1519 def test_stderr_stdin_are_single_inout_fd(self):
1520 with io.open(os.devnull, "r+") as inout:
1521 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1522 stderr=inout, stdin=inout)
1523 p.wait()
1524
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001525 def test_wait_when_sigchild_ignored(self):
1526 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1527 sigchild_ignore = support.findfile("sigchild_ignore.py",
1528 subdir="subprocessdata")
1529 p = subprocess.Popen([sys.executable, sigchild_ignore],
1530 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1531 stdout, stderr = p.communicate()
1532 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001533 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001534 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001535
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001536 def test_select_unbuffered(self):
1537 # Issue #11459: bufsize=0 should really set the pipes as
1538 # unbuffered (and therefore let select() work properly).
1539 select = support.import_module("select")
1540 p = subprocess.Popen([sys.executable, "-c",
1541 'import sys;'
1542 'sys.stdout.write("apple")'],
1543 stdout=subprocess.PIPE,
1544 bufsize=0)
1545 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001546 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001547 try:
1548 self.assertEqual(f.read(4), b"appl")
1549 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1550 finally:
1551 p.wait()
1552
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001553 def test_zombie_fast_process_del(self):
1554 # Issue #12650: on Unix, if Popen.__del__() was called before the
1555 # process exited, it wouldn't be added to subprocess._active, and would
1556 # remain a zombie.
1557 # spawn a Popen, and delete its reference before it exits
1558 p = subprocess.Popen([sys.executable, "-c",
1559 'import sys, time;'
1560 'time.sleep(0.2)'],
1561 stdout=subprocess.PIPE,
1562 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001563 self.addCleanup(p.stdout.close)
1564 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001565 ident = id(p)
1566 pid = p.pid
1567 del p
1568 # check that p is in the active processes list
1569 self.assertIn(ident, [id(o) for o in subprocess._active])
1570
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001571 def test_leak_fast_process_del_killed(self):
1572 # Issue #12650: on Unix, if Popen.__del__() was called before the
1573 # process exited, and the process got killed by a signal, it would never
1574 # be removed from subprocess._active, which triggered a FD and memory
1575 # leak.
1576 # spawn a Popen, delete its reference and kill it
1577 p = subprocess.Popen([sys.executable, "-c",
1578 'import time;'
1579 'time.sleep(3)'],
1580 stdout=subprocess.PIPE,
1581 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001582 self.addCleanup(p.stdout.close)
1583 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001584 ident = id(p)
1585 pid = p.pid
1586 del p
1587 os.kill(pid, signal.SIGKILL)
1588 # check that p is in the active processes list
1589 self.assertIn(ident, [id(o) for o in subprocess._active])
1590
1591 # let some time for the process to exit, and create a new Popen: this
1592 # should trigger the wait() of p
1593 time.sleep(0.2)
1594 with self.assertRaises(EnvironmentError) as c:
1595 with subprocess.Popen(['nonexisting_i_hope'],
1596 stdout=subprocess.PIPE,
1597 stderr=subprocess.PIPE) as proc:
1598 pass
1599 # p should have been wait()ed on, and removed from the _active list
1600 self.assertRaises(OSError, os.waitpid, pid, 0)
1601 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1602
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001603
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001604@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001605class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001606
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001607 def test_startupinfo(self):
1608 # startupinfo argument
1609 # We uses hardcoded constants, because we do not want to
1610 # depend on win32all.
1611 STARTF_USESHOWWINDOW = 1
1612 SW_MAXIMIZE = 3
1613 startupinfo = subprocess.STARTUPINFO()
1614 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1615 startupinfo.wShowWindow = SW_MAXIMIZE
1616 # Since Python is a console process, it won't be affected
1617 # by wShowWindow, but the argument should be silently
1618 # ignored
1619 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001620 startupinfo=startupinfo)
1621
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001622 def test_creationflags(self):
1623 # creationflags argument
1624 CREATE_NEW_CONSOLE = 16
1625 sys.stderr.write(" a DOS box should flash briefly ...\n")
1626 subprocess.call(sys.executable +
1627 ' -c "import time; time.sleep(0.25)"',
1628 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001629
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001630 def test_invalid_args(self):
1631 # invalid arguments should raise ValueError
1632 self.assertRaises(ValueError, subprocess.call,
1633 [sys.executable, "-c",
1634 "import sys; sys.exit(47)"],
1635 preexec_fn=lambda: 1)
1636 self.assertRaises(ValueError, subprocess.call,
1637 [sys.executable, "-c",
1638 "import sys; sys.exit(47)"],
1639 stdout=subprocess.PIPE,
1640 close_fds=True)
1641
1642 def test_close_fds(self):
1643 # close file descriptors
1644 rc = subprocess.call([sys.executable, "-c",
1645 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001646 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001647 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001648
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001649 def test_shell_sequence(self):
1650 # Run command through the shell (sequence)
1651 newenv = os.environ.copy()
1652 newenv["FRUIT"] = "physalis"
1653 p = subprocess.Popen(["set"], shell=1,
1654 stdout=subprocess.PIPE,
1655 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001656 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001657 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001658
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001659 def test_shell_string(self):
1660 # Run command through the shell (string)
1661 newenv = os.environ.copy()
1662 newenv["FRUIT"] = "physalis"
1663 p = subprocess.Popen("set", shell=1,
1664 stdout=subprocess.PIPE,
1665 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001666 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001667 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001668
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001669 def test_call_string(self):
1670 # call() function with string argument on Windows
1671 rc = subprocess.call(sys.executable +
1672 ' -c "import sys; sys.exit(47)"')
1673 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001674
Florent Xicluna4886d242010-03-08 13:27:26 +00001675 def _kill_process(self, method, *args):
1676 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001677 p = subprocess.Popen([sys.executable, "-c", """if 1:
1678 import sys, time
1679 sys.stdout.write('x\\n')
1680 sys.stdout.flush()
1681 time.sleep(30)
1682 """],
1683 stdin=subprocess.PIPE,
1684 stdout=subprocess.PIPE,
1685 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001686 self.addCleanup(p.stdout.close)
1687 self.addCleanup(p.stderr.close)
1688 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001689 # Wait for the interpreter to be completely initialized before
1690 # sending any signal.
1691 p.stdout.read(1)
1692 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001693 _, stderr = p.communicate()
1694 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001695 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001696 self.assertNotEqual(returncode, 0)
1697
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001698 def _kill_dead_process(self, method, *args):
1699 p = subprocess.Popen([sys.executable, "-c", """if 1:
1700 import sys, time
1701 sys.stdout.write('x\\n')
1702 sys.stdout.flush()
1703 sys.exit(42)
1704 """],
1705 stdin=subprocess.PIPE,
1706 stdout=subprocess.PIPE,
1707 stderr=subprocess.PIPE)
1708 self.addCleanup(p.stdout.close)
1709 self.addCleanup(p.stderr.close)
1710 self.addCleanup(p.stdin.close)
1711 # Wait for the interpreter to be completely initialized before
1712 # sending any signal.
1713 p.stdout.read(1)
1714 # The process should end after this
1715 time.sleep(1)
1716 # This shouldn't raise even though the child is now dead
1717 getattr(p, method)(*args)
1718 _, stderr = p.communicate()
1719 self.assertStderrEqual(stderr, b'')
1720 rc = p.wait()
1721 self.assertEqual(rc, 42)
1722
Florent Xicluna4886d242010-03-08 13:27:26 +00001723 def test_send_signal(self):
1724 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001725
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001726 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001727 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001728
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001729 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001730 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001731
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001732 def test_send_signal_dead(self):
1733 self._kill_dead_process('send_signal', signal.SIGTERM)
1734
1735 def test_kill_dead(self):
1736 self._kill_dead_process('kill')
1737
1738 def test_terminate_dead(self):
1739 self._kill_dead_process('terminate')
1740
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001741
Brett Cannona23810f2008-05-26 19:04:21 +00001742# The module says:
1743# "NB This only works (and is only relevant) for UNIX."
1744#
1745# Actually, getoutput should work on any platform with an os.popen, but
1746# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001747@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001748class CommandTests(unittest.TestCase):
1749 def test_getoutput(self):
1750 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1751 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1752 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001753
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001754 # we use mkdtemp in the next line to create an empty directory
1755 # under our exclusive control; from that, we can invent a pathname
1756 # that we _know_ won't exist. This is guaranteed to fail.
1757 dir = None
1758 try:
1759 dir = tempfile.mkdtemp()
1760 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001761
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001762 status, output = subprocess.getstatusoutput('cat ' + name)
1763 self.assertNotEqual(status, 0)
1764 finally:
1765 if dir is not None:
1766 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001767
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001768
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001769@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1770 "poll system call not supported")
1771class ProcessTestCaseNoPoll(ProcessTestCase):
1772 def setUp(self):
1773 subprocess._has_poll = False
1774 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001775
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001776 def tearDown(self):
1777 subprocess._has_poll = True
1778 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001779
1780
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001781class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001782 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001783 def test_eintr_retry_call(self):
1784 record_calls = []
1785 def fake_os_func(*args):
1786 record_calls.append(args)
1787 if len(record_calls) == 2:
1788 raise OSError(errno.EINTR, "fake interrupted system call")
1789 return tuple(reversed(args))
1790
1791 self.assertEqual((999, 256),
1792 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1793 self.assertEqual([(256, 999)], record_calls)
1794 # This time there will be an EINTR so it will loop once.
1795 self.assertEqual((666,),
1796 subprocess._eintr_retry_call(fake_os_func, 666))
1797 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1798
1799
Tim Golden126c2962010-08-11 14:20:40 +00001800@unittest.skipUnless(mswindows, "Windows-specific tests")
1801class CommandsWithSpaces (BaseTestCase):
1802
1803 def setUp(self):
1804 super().setUp()
1805 f, fname = mkstemp(".py", "te st")
1806 self.fname = fname.lower ()
1807 os.write(f, b"import sys;"
1808 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1809 )
1810 os.close(f)
1811
1812 def tearDown(self):
1813 os.remove(self.fname)
1814 super().tearDown()
1815
1816 def with_spaces(self, *args, **kwargs):
1817 kwargs['stdout'] = subprocess.PIPE
1818 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001819 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001820 self.assertEqual(
1821 p.stdout.read ().decode("mbcs"),
1822 "2 [%r, 'ab cd']" % self.fname
1823 )
1824
1825 def test_shell_string_with_spaces(self):
1826 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001827 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1828 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001829
1830 def test_shell_sequence_with_spaces(self):
1831 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001832 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001833
1834 def test_noshell_string_with_spaces(self):
1835 # call() function with string argument with spaces on Windows
1836 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1837 "ab cd"))
1838
1839 def test_noshell_sequence_with_spaces(self):
1840 # call() function with sequence argument with spaces on Windows
1841 self.with_spaces([sys.executable, self.fname, "ab cd"])
1842
Brian Curtin79cdb662010-12-03 02:46:02 +00001843
Georg Brandla86b2622012-02-20 21:34:57 +01001844class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00001845
1846 def test_pipe(self):
1847 with subprocess.Popen([sys.executable, "-c",
1848 "import sys;"
1849 "sys.stdout.write('stdout');"
1850 "sys.stderr.write('stderr');"],
1851 stdout=subprocess.PIPE,
1852 stderr=subprocess.PIPE) as proc:
1853 self.assertEqual(proc.stdout.read(), b"stdout")
1854 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1855
1856 self.assertTrue(proc.stdout.closed)
1857 self.assertTrue(proc.stderr.closed)
1858
1859 def test_returncode(self):
1860 with subprocess.Popen([sys.executable, "-c",
1861 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07001862 pass
1863 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00001864 self.assertEqual(proc.returncode, 100)
1865
1866 def test_communicate_stdin(self):
1867 with subprocess.Popen([sys.executable, "-c",
1868 "import sys;"
1869 "sys.exit(sys.stdin.read() == 'context')"],
1870 stdin=subprocess.PIPE) as proc:
1871 proc.communicate(b"context")
1872 self.assertEqual(proc.returncode, 1)
1873
1874 def test_invalid_args(self):
1875 with self.assertRaises(EnvironmentError) as c:
1876 with subprocess.Popen(['nonexisting_i_hope'],
1877 stdout=subprocess.PIPE,
1878 stderr=subprocess.PIPE) as proc:
1879 pass
1880
1881 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1882 raise c.exception
1883
1884
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001885def test_main():
1886 unit_tests = (ProcessTestCase,
1887 POSIXProcessTestCase,
1888 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001889 CommandTests,
1890 ProcessTestCaseNoPoll,
1891 HelperFunctionTests,
1892 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02001893 ContextManagerTests,
1894 )
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001895
1896 support.run_unittest(*unit_tests)
1897 support.reap_children()
1898
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001899if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001900 unittest.main()