blob: 6ec72c7188ba56489ef6fd95e5371315d3c10d4f [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
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100192 @unittest.skipIf(sys.base_prefix != sys.prefix,
193 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000194 def test_executable_with_cwd(self):
Florent Xicluna1d1ab972010-03-11 01:53:10 +0000195 python_dir = os.path.dirname(os.path.realpath(sys.executable))
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000196 p = subprocess.Popen(["somethingyoudonthave", "-c",
197 "import sys; sys.exit(47)"],
198 executable=sys.executable, cwd=python_dir)
199 p.wait()
200 self.assertEqual(p.returncode, 47)
201
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100202 @unittest.skipIf(sys.base_prefix != sys.prefix,
203 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000204 @unittest.skipIf(sysconfig.is_python_build(),
205 "need an installed Python. See #7774")
206 def test_executable_without_cwd(self):
207 # For a normal installation, it should work without 'cwd'
208 # argument. For test runs in the build directory, see #7774.
209 p = subprocess.Popen(["somethingyoudonthave", "-c",
210 "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000211 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000212 p.wait()
213 self.assertEqual(p.returncode, 47)
214
215 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000216 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000217 p = subprocess.Popen([sys.executable, "-c",
218 'import sys; sys.exit(sys.stdin.read() == "pear")'],
219 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000220 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000221 p.stdin.close()
222 p.wait()
223 self.assertEqual(p.returncode, 1)
224
225 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000226 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000227 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000228 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000229 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000230 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000231 os.lseek(d, 0, 0)
232 p = subprocess.Popen([sys.executable, "-c",
233 'import sys; sys.exit(sys.stdin.read() == "pear")'],
234 stdin=d)
235 p.wait()
236 self.assertEqual(p.returncode, 1)
237
238 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000239 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000240 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000241 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000242 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000243 tf.seek(0)
244 p = subprocess.Popen([sys.executable, "-c",
245 'import sys; sys.exit(sys.stdin.read() == "pear")'],
246 stdin=tf)
247 p.wait()
248 self.assertEqual(p.returncode, 1)
249
250 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000251 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000252 p = subprocess.Popen([sys.executable, "-c",
253 'import sys; sys.stdout.write("orange")'],
254 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000255 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000256 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000257
258 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000259 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000260 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000261 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000262 d = tf.fileno()
263 p = subprocess.Popen([sys.executable, "-c",
264 'import sys; sys.stdout.write("orange")'],
265 stdout=d)
266 p.wait()
267 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000268 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000269
270 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000271 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000272 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000273 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000274 p = subprocess.Popen([sys.executable, "-c",
275 'import sys; sys.stdout.write("orange")'],
276 stdout=tf)
277 p.wait()
278 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000279 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000280
281 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000282 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000283 p = subprocess.Popen([sys.executable, "-c",
284 'import sys; sys.stderr.write("strawberry")'],
285 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000286 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000287 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000288
289 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000290 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000291 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000292 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000293 d = tf.fileno()
294 p = subprocess.Popen([sys.executable, "-c",
295 'import sys; sys.stderr.write("strawberry")'],
296 stderr=d)
297 p.wait()
298 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000299 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000300
301 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000302 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000303 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000304 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000305 p = subprocess.Popen([sys.executable, "-c",
306 'import sys; sys.stderr.write("strawberry")'],
307 stderr=tf)
308 p.wait()
309 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000310 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000311
312 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000313 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000314 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000315 'import sys;'
316 'sys.stdout.write("apple");'
317 'sys.stdout.flush();'
318 'sys.stderr.write("orange")'],
319 stdout=subprocess.PIPE,
320 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000321 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000322 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000323
324 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000325 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000326 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000327 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000328 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000329 'import sys;'
330 'sys.stdout.write("apple");'
331 'sys.stdout.flush();'
332 'sys.stderr.write("orange")'],
333 stdout=tf,
334 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000335 p.wait()
336 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000337 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000338
Thomas Wouters89f507f2006-12-13 04:49:30 +0000339 def test_stdout_filedes_of_stdout(self):
340 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000341 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000342 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000343 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000344
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200345 def test_stdout_devnull(self):
346 p = subprocess.Popen([sys.executable, "-c",
347 'for i in range(10240):'
348 'print("x" * 1024)'],
349 stdout=subprocess.DEVNULL)
350 p.wait()
351 self.assertEqual(p.stdout, None)
352
353 def test_stderr_devnull(self):
354 p = subprocess.Popen([sys.executable, "-c",
355 'import sys\n'
356 'for i in range(10240):'
357 'sys.stderr.write("x" * 1024)'],
358 stderr=subprocess.DEVNULL)
359 p.wait()
360 self.assertEqual(p.stderr, None)
361
362 def test_stdin_devnull(self):
363 p = subprocess.Popen([sys.executable, "-c",
364 'import sys;'
365 'sys.stdin.read(1)'],
366 stdin=subprocess.DEVNULL)
367 p.wait()
368 self.assertEqual(p.stdin, None)
369
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000370 def test_cwd(self):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000371 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000372 # We cannot use os.path.realpath to canonicalize the path,
373 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
374 cwd = os.getcwd()
375 os.chdir(tmpdir)
376 tmpdir = os.getcwd()
377 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000378 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000379 'import sys,os;'
380 'sys.stdout.write(os.getcwd())'],
381 stdout=subprocess.PIPE,
382 cwd=tmpdir)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000383 self.addCleanup(p.stdout.close)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000384 normcase = os.path.normcase
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000385 self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
386 normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000387
388 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000389 newenv = os.environ.copy()
390 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200391 with subprocess.Popen([sys.executable, "-c",
392 'import sys,os;'
393 'sys.stdout.write(os.getenv("FRUIT"))'],
394 stdout=subprocess.PIPE,
395 env=newenv) as p:
396 stdout, stderr = p.communicate()
397 self.assertEqual(stdout, b"orange")
398
Victor Stinner62d51182011-06-23 01:02:25 +0200399 # Windows requires at least the SYSTEMROOT environment variable to start
400 # Python
401 @unittest.skipIf(sys.platform == 'win32',
402 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200403 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200404 'the python library cannot be loaded '
405 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200406 def test_empty_env(self):
407 with subprocess.Popen([sys.executable, "-c",
408 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200409 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200410 stdout=subprocess.PIPE,
411 env={}) as p:
412 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200413 self.assertIn(stdout.strip(),
414 (b"[]",
415 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
416 # environment
417 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000418
Peter Astrandcbac93c2005-03-03 20:24:28 +0000419 def test_communicate_stdin(self):
420 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000421 'import sys;'
422 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000423 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000424 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000425 self.assertEqual(p.returncode, 1)
426
427 def test_communicate_stdout(self):
428 p = subprocess.Popen([sys.executable, "-c",
429 'import sys; sys.stdout.write("pineapple")'],
430 stdout=subprocess.PIPE)
431 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000432 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000433 self.assertEqual(stderr, None)
434
435 def test_communicate_stderr(self):
436 p = subprocess.Popen([sys.executable, "-c",
437 'import sys; sys.stderr.write("pineapple")'],
438 stderr=subprocess.PIPE)
439 (stdout, stderr) = p.communicate()
440 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000441 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000442
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000443 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000444 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000445 'import sys,os;'
446 'sys.stderr.write("pineapple");'
447 'sys.stdout.write(sys.stdin.read())'],
448 stdin=subprocess.PIPE,
449 stdout=subprocess.PIPE,
450 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000451 self.addCleanup(p.stdout.close)
452 self.addCleanup(p.stderr.close)
453 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000454 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000455 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000456 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000457
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400458 def test_communicate_timeout(self):
459 p = subprocess.Popen([sys.executable, "-c",
460 'import sys,os,time;'
461 'sys.stderr.write("pineapple\\n");'
462 'time.sleep(1);'
463 'sys.stderr.write("pear\\n");'
464 'sys.stdout.write(sys.stdin.read())'],
465 universal_newlines=True,
466 stdin=subprocess.PIPE,
467 stdout=subprocess.PIPE,
468 stderr=subprocess.PIPE)
469 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
470 timeout=0.3)
471 # Make sure we can keep waiting for it, and that we get the whole output
472 # after it completes.
473 (stdout, stderr) = p.communicate()
474 self.assertEqual(stdout, "banana")
475 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
476
477 def test_communicate_timeout_large_ouput(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200478 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400479 p = subprocess.Popen([sys.executable, "-c",
480 'import sys,os,time;'
481 'sys.stdout.write("a" * (64 * 1024));'
482 'time.sleep(0.2);'
483 'sys.stdout.write("a" * (64 * 1024));'
484 'time.sleep(0.2);'
485 'sys.stdout.write("a" * (64 * 1024));'
486 'time.sleep(0.2);'
487 'sys.stdout.write("a" * (64 * 1024));'],
488 stdout=subprocess.PIPE)
489 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
490 (stdout, _) = p.communicate()
491 self.assertEqual(len(stdout), 4 * 64 * 1024)
492
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000493 # Test for the fd leak reported in http://bugs.python.org/issue2791.
494 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000495 for stdin_pipe in (False, True):
496 for stdout_pipe in (False, True):
497 for stderr_pipe in (False, True):
498 options = {}
499 if stdin_pipe:
500 options['stdin'] = subprocess.PIPE
501 if stdout_pipe:
502 options['stdout'] = subprocess.PIPE
503 if stderr_pipe:
504 options['stderr'] = subprocess.PIPE
505 if not options:
506 continue
507 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
508 p.communicate()
509 if p.stdin is not None:
510 self.assertTrue(p.stdin.closed)
511 if p.stdout is not None:
512 self.assertTrue(p.stdout.closed)
513 if p.stderr is not None:
514 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000515
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000516 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000517 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000518 p = subprocess.Popen([sys.executable, "-c",
519 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000520 (stdout, stderr) = p.communicate()
521 self.assertEqual(stdout, None)
522 self.assertEqual(stderr, None)
523
524 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000525 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000526 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000527 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000528 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000529 os.close(x)
530 os.close(y)
531 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000532 'import sys,os;'
533 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200534 'sys.stderr.write("x" * %d);'
535 'sys.stdout.write(sys.stdin.read())' %
536 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000537 stdin=subprocess.PIPE,
538 stdout=subprocess.PIPE,
539 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000540 self.addCleanup(p.stdout.close)
541 self.addCleanup(p.stderr.close)
542 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200543 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000544 (stdout, stderr) = p.communicate(string_to_write)
545 self.assertEqual(stdout, string_to_write)
546
547 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000548 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000549 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000550 'import sys,os;'
551 'sys.stdout.write(sys.stdin.read())'],
552 stdin=subprocess.PIPE,
553 stdout=subprocess.PIPE,
554 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000555 self.addCleanup(p.stdout.close)
556 self.addCleanup(p.stderr.close)
557 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000558 p.stdin.write(b"banana")
559 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000560 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000561 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000562
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000563 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000564 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000565 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200566 'buf = sys.stdout.buffer;'
567 'buf.write(sys.stdin.readline().encode());'
568 'buf.flush();'
569 'buf.write(b"line2\\n");'
570 'buf.flush();'
571 'buf.write(sys.stdin.read().encode());'
572 'buf.flush();'
573 'buf.write(b"line4\\n");'
574 'buf.flush();'
575 'buf.write(b"line5\\r\\n");'
576 'buf.flush();'
577 'buf.write(b"line6\\r");'
578 'buf.flush();'
579 'buf.write(b"\\nline7");'
580 'buf.flush();'
581 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200582 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000583 stdout=subprocess.PIPE,
584 universal_newlines=1)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200585 p.stdin.write("line1\n")
586 self.assertEqual(p.stdout.readline(), "line1\n")
587 p.stdin.write("line3\n")
588 p.stdin.close()
Brian Curtin3c6a9512010-11-05 03:58:52 +0000589 self.addCleanup(p.stdout.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200590 self.assertEqual(p.stdout.readline(),
591 "line2\n")
592 self.assertEqual(p.stdout.read(6),
593 "line3\n")
594 self.assertEqual(p.stdout.read(),
595 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000596
597 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000598 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000599 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000600 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200601 'buf = sys.stdout.buffer;'
602 'buf.write(b"line2\\n");'
603 'buf.flush();'
604 'buf.write(b"line4\\n");'
605 'buf.flush();'
606 'buf.write(b"line5\\r\\n");'
607 'buf.flush();'
608 'buf.write(b"line6\\r");'
609 'buf.flush();'
610 'buf.write(b"\\nline7");'
611 'buf.flush();'
612 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200613 stderr=subprocess.PIPE,
614 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000615 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000616 self.addCleanup(p.stdout.close)
617 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000618 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200619 self.assertEqual(stdout,
620 "line2\nline4\nline5\nline6\nline7\nline8")
621
622 def test_universal_newlines_communicate_stdin(self):
623 # universal newlines through communicate(), with only stdin
624 p = subprocess.Popen([sys.executable, "-c",
625 'import sys,os;' + SETBINARY + '''\nif True:
626 s = sys.stdin.readline()
627 assert s == "line1\\n", repr(s)
628 s = sys.stdin.read()
629 assert s == "line3\\n", repr(s)
630 '''],
631 stdin=subprocess.PIPE,
632 universal_newlines=1)
633 (stdout, stderr) = p.communicate("line1\nline3\n")
634 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000635
Andrew Svetlovf3765072012-08-14 18:35:17 +0300636 def test_universal_newlines_communicate_input_none(self):
637 # Test communicate(input=None) with universal newlines.
638 #
639 # We set stdout to PIPE because, as of this writing, a different
640 # code path is tested when the number of pipes is zero or one.
641 p = subprocess.Popen([sys.executable, "-c", "pass"],
642 stdin=subprocess.PIPE,
643 stdout=subprocess.PIPE,
644 universal_newlines=True)
645 p.communicate()
646 self.assertEqual(p.returncode, 0)
647
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300648 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
649 # universal newlines through communicate(), with only stdin
650 p = subprocess.Popen([sys.executable, "-c",
651 'import sys,os;' + SETBINARY + '''\nif True:
652 s = sys.stdin.readline()
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300653 sys.stdout.buffer.write(s.encode())
654 sys.stdout.buffer.write(b"line2\\r")
655 sys.stderr.buffer.write(b"eline2\\n")
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300656 s = sys.stdin.read()
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300657 sys.stdout.buffer.write(s.encode())
658 sys.stdout.buffer.write(b"line4\\n")
659 sys.stdout.buffer.write(b"line5\\r\\n")
660 sys.stderr.buffer.write(b"eline6\\r")
661 sys.stderr.buffer.write(b"eline7\\r\\nz")
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300662 '''],
663 stdin=subprocess.PIPE,
664 stderr=subprocess.PIPE,
665 stdout=subprocess.PIPE,
666 universal_newlines=1)
667 self.addCleanup(p.stdout.close)
668 self.addCleanup(p.stderr.close)
669 (stdout, stderr) = p.communicate("line1\nline3\n")
670 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300671 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300672 # Python debug build push something like "[42442 refs]\n"
673 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300674 # Don't use assertStderrEqual because it strips CR and LF from output.
675 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300676
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000677 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000678 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000679 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000680 max_handles = 1026 # too much for most UNIX systems
681 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000682 max_handles = 2050 # too much for (at least some) Windows setups
683 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400684 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000685 try:
686 for i in range(max_handles):
687 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400688 tmpfile = os.path.join(tmpdir, support.TESTFN)
689 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000690 except OSError as e:
691 if e.errno != errno.EMFILE:
692 raise
693 break
694 else:
695 self.skipTest("failed to reach the file descriptor limit "
696 "(tried %d)" % max_handles)
697 # Close a couple of them (should be enough for a subprocess)
698 for i in range(10):
699 os.close(handles.pop())
700 # Loop creating some subprocesses. If one of them leaks some fds,
701 # the next loop iteration will fail by reaching the max fd limit.
702 for i in range(15):
703 p = subprocess.Popen([sys.executable, "-c",
704 "import sys;"
705 "sys.stdout.write(sys.stdin.read())"],
706 stdin=subprocess.PIPE,
707 stdout=subprocess.PIPE,
708 stderr=subprocess.PIPE)
709 data = p.communicate(b"lime")[0]
710 self.assertEqual(data, b"lime")
711 finally:
712 for h in handles:
713 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400714 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000715
716 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000717 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
718 '"a b c" d e')
719 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
720 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000721 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
722 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000723 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
724 'a\\\\\\b "de fg" h')
725 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
726 'a\\\\\\"b c d')
727 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
728 '"a\\\\b c" d e')
729 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
730 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000731 self.assertEqual(subprocess.list2cmdline(['ab', '']),
732 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000733
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000734 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200735 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +0200736 "import os; os.read(0, 1)"],
737 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200738 self.addCleanup(p.stdin.close)
739 self.assertIsNone(p.poll())
740 os.write(p.stdin.fileno(), b'A')
741 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000742 # Subsequent invocations should just return the returncode
743 self.assertEqual(p.poll(), 0)
744
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000745 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200746 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000747 self.assertEqual(p.wait(), 0)
748 # Subsequent invocations should just return the returncode
749 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000750
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400751 def test_wait_timeout(self):
752 p = subprocess.Popen([sys.executable,
Reid Kleckner93479cc2011-03-14 19:32:41 -0400753 "-c", "import time; time.sleep(0.1)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -0400754 with self.assertRaises(subprocess.TimeoutExpired) as c:
755 p.wait(timeout=0.01)
756 self.assertIn("0.01", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -0400757 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
758 # time to start.
759 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400760
Peter Astrand738131d2004-11-30 21:04:45 +0000761 def test_invalid_bufsize(self):
762 # an invalid type of the bufsize argument should raise
763 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000764 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000765 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000766
Guido van Rossum46a05a72007-06-07 21:56:45 +0000767 def test_bufsize_is_none(self):
768 # bufsize=None should be the same as bufsize=0.
769 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
770 self.assertEqual(p.wait(), 0)
771 # Again with keyword arg
772 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
773 self.assertEqual(p.wait(), 0)
774
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000775 def test_leaking_fds_on_error(self):
776 # see bug #5179: Popen leaks file descriptors to PIPEs if
777 # the child fails to execute; this will eventually exhaust
778 # the maximum number of open fds. 1024 seems a very common
779 # value for that limit, but Windows has 2048, so we loop
780 # 1024 times (each call leaked two fds).
781 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000782 # Windows raises IOError. Others raise OSError.
783 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000784 subprocess.Popen(['nonexisting_i_hope'],
785 stdout=subprocess.PIPE,
786 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400787 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400788 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000789 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000790
Victor Stinnerb3693582010-05-21 20:13:12 +0000791 def test_issue8780(self):
792 # Ensure that stdout is inherited from the parent
793 # if stdout=PIPE is not used
794 code = ';'.join((
795 'import subprocess, sys',
796 'retcode = subprocess.call('
797 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
798 'assert retcode == 0'))
799 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000800 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000801
Tim Goldenaf5ac392010-08-06 13:03:56 +0000802 def test_handles_closed_on_exception(self):
803 # If CreateProcess exits with an error, ensure the
804 # duplicate output handles are released
805 ifhandle, ifname = mkstemp()
806 ofhandle, ofname = mkstemp()
807 efhandle, efname = mkstemp()
808 try:
809 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
810 stderr=efhandle)
811 except OSError:
812 os.close(ifhandle)
813 os.remove(ifname)
814 os.close(ofhandle)
815 os.remove(ofname)
816 os.close(efhandle)
817 os.remove(efname)
818 self.assertFalse(os.path.exists(ifname))
819 self.assertFalse(os.path.exists(ofname))
820 self.assertFalse(os.path.exists(efname))
821
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200822 def test_communicate_epipe(self):
823 # Issue 10963: communicate() should hide EPIPE
824 p = subprocess.Popen([sys.executable, "-c", 'pass'],
825 stdin=subprocess.PIPE,
826 stdout=subprocess.PIPE,
827 stderr=subprocess.PIPE)
828 self.addCleanup(p.stdout.close)
829 self.addCleanup(p.stderr.close)
830 self.addCleanup(p.stdin.close)
831 p.communicate(b"x" * 2**20)
832
833 def test_communicate_epipe_only_stdin(self):
834 # Issue 10963: communicate() should hide EPIPE
835 p = subprocess.Popen([sys.executable, "-c", 'pass'],
836 stdin=subprocess.PIPE)
837 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200838 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200839 p.communicate(b"x" * 2**20)
840
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200841 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
842 "Requires signal.SIGUSR1")
843 @unittest.skipUnless(hasattr(os, 'kill'),
844 "Requires os.kill")
845 @unittest.skipUnless(hasattr(os, 'getppid'),
846 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200847 def test_communicate_eintr(self):
848 # Issue #12493: communicate() should handle EINTR
849 def handler(signum, frame):
850 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200851 old_handler = signal.signal(signal.SIGUSR1, handler)
852 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200853
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200854 args = [sys.executable, "-c",
855 'import os, signal;'
856 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200857 for stream in ('stdout', 'stderr'):
858 kw = {stream: subprocess.PIPE}
859 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200860 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200861 process.communicate()
862
Tim Peterse718f612004-10-12 21:51:32 +0000863
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000864# context manager
865class _SuppressCoreFiles(object):
866 """Try to prevent core files from being created."""
867 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000868
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000869 def __enter__(self):
870 """Try to save previous ulimit, then set it to (0, 0)."""
Benjamin Peterson964561b2011-12-10 12:31:42 -0500871 if resource is not None:
872 try:
873 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
874 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
875 except (ValueError, resource.error):
876 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000877
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000878 if sys.platform == 'darwin':
879 # Check if the 'Crash Reporter' on OSX was configured
880 # in 'Developer' mode and warn that it will get triggered
881 # when it is.
882 #
883 # This assumes that this context manager is used in tests
884 # that might trigger the next manager.
885 value = subprocess.Popen(['/usr/bin/defaults', 'read',
886 'com.apple.CrashReporter', 'DialogType'],
887 stdout=subprocess.PIPE).communicate()[0]
888 if value.strip() == b'developer':
889 print("this tests triggers the Crash Reporter, "
890 "that is intentional", end='')
891 sys.stdout.flush()
892
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000893 def __exit__(self, *args):
894 """Return core file behavior to default."""
895 if self.old_limit is None:
896 return
Benjamin Peterson964561b2011-12-10 12:31:42 -0500897 if resource is not None:
898 try:
899 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
900 except (ValueError, resource.error):
901 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000902
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000903
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000904@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000905class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000906
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000907 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000908 nonexistent_dir = "/_this/pa.th/does/not/exist"
909 try:
910 os.chdir(nonexistent_dir)
911 except OSError as e:
912 # This avoids hard coding the errno value or the OS perror()
913 # string and instead capture the exception that we want to see
914 # below for comparison.
915 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000916 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000917 else:
918 self.fail("chdir to nonexistant directory %s succeeded." %
919 nonexistent_dir)
920
921 # Error in the child re-raised in the parent.
922 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000923 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000924 cwd=nonexistent_dir)
925 except OSError as e:
926 # Test that the child process chdir failure actually makes
927 # it up to the parent process as the correct exception.
928 self.assertEqual(desired_exception.errno, e.errno)
929 self.assertEqual(desired_exception.strerror, e.strerror)
930 else:
931 self.fail("Expected OSError: %s" % desired_exception)
932
933 def test_restore_signals(self):
934 # Code coverage for both values of restore_signals to make sure it
935 # at least does not blow up.
936 # A test for behavior would be complex. Contributions welcome.
937 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
938 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
939
940 def test_start_new_session(self):
941 # For code coverage of calling setsid(). We don't care if we get an
942 # EPERM error from it depending on the test execution environment, that
943 # still indicates that it was called.
944 try:
945 output = subprocess.check_output(
946 [sys.executable, "-c",
947 "import os; print(os.getpgid(os.getpid()))"],
948 start_new_session=True)
949 except OSError as e:
950 if e.errno != errno.EPERM:
951 raise
952 else:
953 parent_pgid = os.getpgid(os.getpid())
954 child_pgid = int(output)
955 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000956
957 def test_run_abort(self):
958 # returncode handles signal termination
959 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000960 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000961 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000962 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000963 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000964
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000965 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000966 # DISCLAIMER: Setting environment variables is *not* a good use
967 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000968 p = subprocess.Popen([sys.executable, "-c",
969 'import sys,os;'
970 'sys.stdout.write(os.getenv("FRUIT"))'],
971 stdout=subprocess.PIPE,
972 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000973 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000974 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000975
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000976 def test_preexec_exception(self):
977 def raise_it():
978 raise ValueError("What if two swallows carried a coconut?")
979 try:
980 p = subprocess.Popen([sys.executable, "-c", ""],
981 preexec_fn=raise_it)
982 except RuntimeError as e:
983 self.assertTrue(
984 subprocess._posixsubprocess,
985 "Expected a ValueError from the preexec_fn")
986 except ValueError as e:
987 self.assertIn("coconut", e.args[0])
988 else:
989 self.fail("Exception raised by preexec_fn did not make it "
990 "to the parent process.")
991
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000992 def test_preexec_gc_module_failure(self):
993 # This tests the code that disables garbage collection if the child
994 # process will execute any Python.
995 def raise_runtime_error():
996 raise RuntimeError("this shouldn't escape")
997 enabled = gc.isenabled()
998 orig_gc_disable = gc.disable
999 orig_gc_isenabled = gc.isenabled
1000 try:
1001 gc.disable()
1002 self.assertFalse(gc.isenabled())
1003 subprocess.call([sys.executable, '-c', ''],
1004 preexec_fn=lambda: None)
1005 self.assertFalse(gc.isenabled(),
1006 "Popen enabled gc when it shouldn't.")
1007
1008 gc.enable()
1009 self.assertTrue(gc.isenabled())
1010 subprocess.call([sys.executable, '-c', ''],
1011 preexec_fn=lambda: None)
1012 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1013
1014 gc.disable = raise_runtime_error
1015 self.assertRaises(RuntimeError, subprocess.Popen,
1016 [sys.executable, '-c', ''],
1017 preexec_fn=lambda: None)
1018
1019 del gc.isenabled # force an AttributeError
1020 self.assertRaises(AttributeError, subprocess.Popen,
1021 [sys.executable, '-c', ''],
1022 preexec_fn=lambda: None)
1023 finally:
1024 gc.disable = orig_gc_disable
1025 gc.isenabled = orig_gc_isenabled
1026 if not enabled:
1027 gc.disable()
1028
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001029 def test_args_string(self):
1030 # args is a string
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 p = subprocess.Popen(fname)
1039 p.wait()
1040 os.remove(fname)
1041 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001042
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001043 def test_invalid_args(self):
1044 # invalid arguments should raise ValueError
1045 self.assertRaises(ValueError, subprocess.call,
1046 [sys.executable, "-c",
1047 "import sys; sys.exit(47)"],
1048 startupinfo=47)
1049 self.assertRaises(ValueError, subprocess.call,
1050 [sys.executable, "-c",
1051 "import sys; sys.exit(47)"],
1052 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001053
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001054 def test_shell_sequence(self):
1055 # Run command through the shell (sequence)
1056 newenv = os.environ.copy()
1057 newenv["FRUIT"] = "apple"
1058 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1059 stdout=subprocess.PIPE,
1060 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001061 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001062 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001063
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001064 def test_shell_string(self):
1065 # Run command through the shell (string)
1066 newenv = os.environ.copy()
1067 newenv["FRUIT"] = "apple"
1068 p = subprocess.Popen("echo $FRUIT", shell=1,
1069 stdout=subprocess.PIPE,
1070 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001071 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001072 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001073
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001074 def test_call_string(self):
1075 # call() function with string argument on UNIX
1076 fd, fname = mkstemp()
1077 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001078 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001079 fobj.write("#!/bin/sh\n")
1080 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1081 sys.executable)
1082 os.chmod(fname, 0o700)
1083 rc = subprocess.call(fname)
1084 os.remove(fname)
1085 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001086
Stefan Krah9542cc62010-07-19 14:20:53 +00001087 def test_specific_shell(self):
1088 # Issue #9265: Incorrect name passed as arg[0].
1089 shells = []
1090 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1091 for name in ['bash', 'ksh']:
1092 sh = os.path.join(prefix, name)
1093 if os.path.isfile(sh):
1094 shells.append(sh)
1095 if not shells: # Will probably work for any shell but csh.
1096 self.skipTest("bash or ksh required for this test")
1097 sh = '/bin/sh'
1098 if os.path.isfile(sh) and not os.path.islink(sh):
1099 # Test will fail if /bin/sh is a symlink to csh.
1100 shells.append(sh)
1101 for sh in shells:
1102 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1103 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001104 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001105 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1106
Florent Xicluna4886d242010-03-08 13:27:26 +00001107 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001108 # Do not inherit file handles from the parent.
1109 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001110 p = subprocess.Popen([sys.executable, "-c", """if 1:
1111 import sys, time
1112 sys.stdout.write('x\\n')
1113 sys.stdout.flush()
1114 time.sleep(30)
1115 """],
1116 close_fds=True,
1117 stdin=subprocess.PIPE,
1118 stdout=subprocess.PIPE,
1119 stderr=subprocess.PIPE)
1120 # Wait for the interpreter to be completely initialized before
1121 # sending any signal.
1122 p.stdout.read(1)
1123 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001124 return p
1125
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001126 def _kill_dead_process(self, method, *args):
1127 # Do not inherit file handles from the parent.
1128 # It should fix failures on some platforms.
1129 p = subprocess.Popen([sys.executable, "-c", """if 1:
1130 import sys, time
1131 sys.stdout.write('x\\n')
1132 sys.stdout.flush()
1133 """],
1134 close_fds=True,
1135 stdin=subprocess.PIPE,
1136 stdout=subprocess.PIPE,
1137 stderr=subprocess.PIPE)
1138 # Wait for the interpreter to be completely initialized before
1139 # sending any signal.
1140 p.stdout.read(1)
1141 # The process should end after this
1142 time.sleep(1)
1143 # This shouldn't raise even though the child is now dead
1144 getattr(p, method)(*args)
1145 p.communicate()
1146
Florent Xicluna4886d242010-03-08 13:27:26 +00001147 def test_send_signal(self):
1148 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001149 _, stderr = p.communicate()
1150 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001151 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001152
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001153 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001154 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001155 _, stderr = p.communicate()
1156 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001157 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001158
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001159 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001160 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001161 _, stderr = p.communicate()
1162 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001163 self.assertEqual(p.wait(), -signal.SIGTERM)
1164
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001165 def test_send_signal_dead(self):
1166 # Sending a signal to a dead process
1167 self._kill_dead_process('send_signal', signal.SIGINT)
1168
1169 def test_kill_dead(self):
1170 # Killing a dead process
1171 self._kill_dead_process('kill')
1172
1173 def test_terminate_dead(self):
1174 # Terminating a dead process
1175 self._kill_dead_process('terminate')
1176
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001177 def check_close_std_fds(self, fds):
1178 # Issue #9905: test that subprocess pipes still work properly with
1179 # some standard fds closed
1180 stdin = 0
1181 newfds = []
1182 for a in fds:
1183 b = os.dup(a)
1184 newfds.append(b)
1185 if a == 0:
1186 stdin = b
1187 try:
1188 for fd in fds:
1189 os.close(fd)
1190 out, err = subprocess.Popen([sys.executable, "-c",
1191 'import sys;'
1192 'sys.stdout.write("apple");'
1193 'sys.stdout.flush();'
1194 'sys.stderr.write("orange")'],
1195 stdin=stdin,
1196 stdout=subprocess.PIPE,
1197 stderr=subprocess.PIPE).communicate()
1198 err = support.strip_python_stderr(err)
1199 self.assertEqual((out, err), (b'apple', b'orange'))
1200 finally:
1201 for b, a in zip(newfds, fds):
1202 os.dup2(b, a)
1203 for b in newfds:
1204 os.close(b)
1205
1206 def test_close_fd_0(self):
1207 self.check_close_std_fds([0])
1208
1209 def test_close_fd_1(self):
1210 self.check_close_std_fds([1])
1211
1212 def test_close_fd_2(self):
1213 self.check_close_std_fds([2])
1214
1215 def test_close_fds_0_1(self):
1216 self.check_close_std_fds([0, 1])
1217
1218 def test_close_fds_0_2(self):
1219 self.check_close_std_fds([0, 2])
1220
1221 def test_close_fds_1_2(self):
1222 self.check_close_std_fds([1, 2])
1223
1224 def test_close_fds_0_1_2(self):
1225 # Issue #10806: test that subprocess pipes still work properly with
1226 # all standard fds closed.
1227 self.check_close_std_fds([0, 1, 2])
1228
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001229 def test_remapping_std_fds(self):
1230 # open up some temporary files
1231 temps = [mkstemp() for i in range(3)]
1232 try:
1233 temp_fds = [fd for fd, fname in temps]
1234
1235 # unlink the files -- we won't need to reopen them
1236 for fd, fname in temps:
1237 os.unlink(fname)
1238
1239 # write some data to what will become stdin, and rewind
1240 os.write(temp_fds[1], b"STDIN")
1241 os.lseek(temp_fds[1], 0, 0)
1242
1243 # move the standard file descriptors out of the way
1244 saved_fds = [os.dup(fd) for fd in range(3)]
1245 try:
1246 # duplicate the file objects over the standard fd's
1247 for fd, temp_fd in enumerate(temp_fds):
1248 os.dup2(temp_fd, fd)
1249
1250 # now use those files in the "wrong" order, so that subprocess
1251 # has to rearrange them in the child
1252 p = subprocess.Popen([sys.executable, "-c",
1253 'import sys; got = sys.stdin.read();'
1254 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1255 stdin=temp_fds[1],
1256 stdout=temp_fds[2],
1257 stderr=temp_fds[0])
1258 p.wait()
1259 finally:
1260 # restore the original fd's underneath sys.stdin, etc.
1261 for std, saved in enumerate(saved_fds):
1262 os.dup2(saved, std)
1263 os.close(saved)
1264
1265 for fd in temp_fds:
1266 os.lseek(fd, 0, 0)
1267
1268 out = os.read(temp_fds[2], 1024)
1269 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1270 self.assertEqual(out, b"got STDIN")
1271 self.assertEqual(err, b"err")
1272
1273 finally:
1274 for fd in temp_fds:
1275 os.close(fd)
1276
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001277 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1278 # open up some temporary files
1279 temps = [mkstemp() for i in range(3)]
1280 temp_fds = [fd for fd, fname in temps]
1281 try:
1282 # unlink the files -- we won't need to reopen them
1283 for fd, fname in temps:
1284 os.unlink(fname)
1285
1286 # save a copy of the standard file descriptors
1287 saved_fds = [os.dup(fd) for fd in range(3)]
1288 try:
1289 # duplicate the temp files over the standard fd's 0, 1, 2
1290 for fd, temp_fd in enumerate(temp_fds):
1291 os.dup2(temp_fd, fd)
1292
1293 # write some data to what will become stdin, and rewind
1294 os.write(stdin_no, b"STDIN")
1295 os.lseek(stdin_no, 0, 0)
1296
1297 # now use those files in the given order, so that subprocess
1298 # has to rearrange them in the child
1299 p = subprocess.Popen([sys.executable, "-c",
1300 'import sys; got = sys.stdin.read();'
1301 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1302 stdin=stdin_no,
1303 stdout=stdout_no,
1304 stderr=stderr_no)
1305 p.wait()
1306
1307 for fd in temp_fds:
1308 os.lseek(fd, 0, 0)
1309
1310 out = os.read(stdout_no, 1024)
1311 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1312 finally:
1313 for std, saved in enumerate(saved_fds):
1314 os.dup2(saved, std)
1315 os.close(saved)
1316
1317 self.assertEqual(out, b"got STDIN")
1318 self.assertEqual(err, b"err")
1319
1320 finally:
1321 for fd in temp_fds:
1322 os.close(fd)
1323
1324 # When duping fds, if there arises a situation where one of the fds is
1325 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1326 # This tests all combinations of this.
1327 def test_swap_fds(self):
1328 self.check_swap_fds(0, 1, 2)
1329 self.check_swap_fds(0, 2, 1)
1330 self.check_swap_fds(1, 0, 2)
1331 self.check_swap_fds(1, 2, 0)
1332 self.check_swap_fds(2, 0, 1)
1333 self.check_swap_fds(2, 1, 0)
1334
Victor Stinner13bb71c2010-04-23 21:41:56 +00001335 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001336 def prepare():
1337 raise ValueError("surrogate:\uDCff")
1338
1339 try:
1340 subprocess.call(
1341 [sys.executable, "-c", "pass"],
1342 preexec_fn=prepare)
1343 except ValueError as err:
1344 # Pure Python implementations keeps the message
1345 self.assertIsNone(subprocess._posixsubprocess)
1346 self.assertEqual(str(err), "surrogate:\uDCff")
1347 except RuntimeError as err:
1348 # _posixsubprocess uses a default message
1349 self.assertIsNotNone(subprocess._posixsubprocess)
1350 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1351 else:
1352 self.fail("Expected ValueError or RuntimeError")
1353
Victor Stinner13bb71c2010-04-23 21:41:56 +00001354 def test_undecodable_env(self):
1355 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001356 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001357 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001358 env = os.environ.copy()
1359 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001360 # Use C locale to get ascii for the locale encoding to force
1361 # surrogate-escaping of \xFF in the child process; otherwise it can
1362 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001363 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001364 stdout = subprocess.check_output(
1365 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001366 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001367 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001368 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001369
1370 # test bytes
1371 key = key.encode("ascii", "surrogateescape")
1372 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001373 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001374 env = os.environ.copy()
1375 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001376 stdout = subprocess.check_output(
1377 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001378 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001379 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001380 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001381
Victor Stinnerb745a742010-05-18 17:17:23 +00001382 def test_bytes_program(self):
1383 abs_program = os.fsencode(sys.executable)
1384 path, program = os.path.split(sys.executable)
1385 program = os.fsencode(program)
1386
1387 # absolute bytes path
1388 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001389 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001390
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001391 # absolute bytes path as a string
1392 cmd = b"'" + abs_program + b"' -c pass"
1393 exitcode = subprocess.call(cmd, shell=True)
1394 self.assertEqual(exitcode, 0)
1395
Victor Stinnerb745a742010-05-18 17:17:23 +00001396 # bytes program, unicode PATH
1397 env = os.environ.copy()
1398 env["PATH"] = path
1399 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001400 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001401
1402 # bytes program, bytes PATH
1403 envb = os.environb.copy()
1404 envb[b"PATH"] = os.fsencode(path)
1405 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001406 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001407
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001408 def test_pipe_cloexec(self):
1409 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1410 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1411
1412 p1 = subprocess.Popen([sys.executable, sleeper],
1413 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1414 stderr=subprocess.PIPE, close_fds=False)
1415
1416 self.addCleanup(p1.communicate, b'')
1417
1418 p2 = subprocess.Popen([sys.executable, fd_status],
1419 stdout=subprocess.PIPE, close_fds=False)
1420
1421 output, error = p2.communicate()
1422 result_fds = set(map(int, output.split(b',')))
1423 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1424 p1.stderr.fileno()])
1425
1426 self.assertFalse(result_fds & unwanted_fds,
1427 "Expected no fds from %r to be open in child, "
1428 "found %r" %
1429 (unwanted_fds, result_fds & unwanted_fds))
1430
1431 def test_pipe_cloexec_real_tools(self):
1432 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1433 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1434
1435 subdata = b'zxcvbn'
1436 data = subdata * 4 + b'\n'
1437
1438 p1 = subprocess.Popen([sys.executable, qcat],
1439 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1440 close_fds=False)
1441
1442 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1443 stdin=p1.stdout, stdout=subprocess.PIPE,
1444 close_fds=False)
1445
1446 self.addCleanup(p1.wait)
1447 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001448 def kill_p1():
1449 try:
1450 p1.terminate()
1451 except ProcessLookupError:
1452 pass
1453 def kill_p2():
1454 try:
1455 p2.terminate()
1456 except ProcessLookupError:
1457 pass
1458 self.addCleanup(kill_p1)
1459 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001460
1461 p1.stdin.write(data)
1462 p1.stdin.close()
1463
1464 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1465
1466 self.assertTrue(readfiles, "The child hung")
1467 self.assertEqual(p2.stdout.read(), data)
1468
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001469 p1.stdout.close()
1470 p2.stdout.close()
1471
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001472 def test_close_fds(self):
1473 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1474
1475 fds = os.pipe()
1476 self.addCleanup(os.close, fds[0])
1477 self.addCleanup(os.close, fds[1])
1478
1479 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001480 # add a bunch more fds
1481 for _ in range(9):
1482 fd = os.open("/dev/null", os.O_RDONLY)
1483 self.addCleanup(os.close, fd)
1484 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001485
1486 p = subprocess.Popen([sys.executable, fd_status],
1487 stdout=subprocess.PIPE, close_fds=False)
1488 output, ignored = p.communicate()
1489 remaining_fds = set(map(int, output.split(b',')))
1490
1491 self.assertEqual(remaining_fds & open_fds, open_fds,
1492 "Some fds were closed")
1493
1494 p = subprocess.Popen([sys.executable, fd_status],
1495 stdout=subprocess.PIPE, close_fds=True)
1496 output, ignored = p.communicate()
1497 remaining_fds = set(map(int, output.split(b',')))
1498
1499 self.assertFalse(remaining_fds & open_fds,
1500 "Some fds were left open")
1501 self.assertIn(1, remaining_fds, "Subprocess failed")
1502
Gregory P. Smith8facece2012-01-21 14:01:08 -08001503 # Keep some of the fd's we opened open in the subprocess.
1504 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1505 fds_to_keep = set(open_fds.pop() for _ in range(8))
1506 p = subprocess.Popen([sys.executable, fd_status],
1507 stdout=subprocess.PIPE, close_fds=True,
1508 pass_fds=())
1509 output, ignored = p.communicate()
1510 remaining_fds = set(map(int, output.split(b',')))
1511
1512 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1513 "Some fds not in pass_fds were left open")
1514 self.assertIn(1, remaining_fds, "Subprocess failed")
1515
Victor Stinner88701e22011-06-01 13:13:04 +02001516 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1517 # descriptor of a pipe closed in the parent process is valid in the
1518 # child process according to fstat(), but the mode of the file
1519 # descriptor is invalid, and read or write raise an error.
1520 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001521 def test_pass_fds(self):
1522 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1523
1524 open_fds = set()
1525
1526 for x in range(5):
1527 fds = os.pipe()
1528 self.addCleanup(os.close, fds[0])
1529 self.addCleanup(os.close, fds[1])
1530 open_fds.update(fds)
1531
1532 for fd in open_fds:
1533 p = subprocess.Popen([sys.executable, fd_status],
1534 stdout=subprocess.PIPE, close_fds=True,
1535 pass_fds=(fd, ))
1536 output, ignored = p.communicate()
1537
1538 remaining_fds = set(map(int, output.split(b',')))
1539 to_be_closed = open_fds - {fd}
1540
1541 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1542 self.assertFalse(remaining_fds & to_be_closed,
1543 "fd to be closed passed")
1544
1545 # pass_fds overrides close_fds with a warning.
1546 with self.assertWarns(RuntimeWarning) as context:
1547 self.assertFalse(subprocess.call(
1548 [sys.executable, "-c", "import sys; sys.exit(0)"],
1549 close_fds=False, pass_fds=(fd, )))
1550 self.assertIn('overriding close_fds', str(context.warning))
1551
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001552 def test_stdout_stdin_are_single_inout_fd(self):
1553 with io.open(os.devnull, "r+") as inout:
1554 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1555 stdout=inout, stdin=inout)
1556 p.wait()
1557
1558 def test_stdout_stderr_are_single_inout_fd(self):
1559 with io.open(os.devnull, "r+") as inout:
1560 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1561 stdout=inout, stderr=inout)
1562 p.wait()
1563
1564 def test_stderr_stdin_are_single_inout_fd(self):
1565 with io.open(os.devnull, "r+") as inout:
1566 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1567 stderr=inout, stdin=inout)
1568 p.wait()
1569
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001570 def test_wait_when_sigchild_ignored(self):
1571 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1572 sigchild_ignore = support.findfile("sigchild_ignore.py",
1573 subdir="subprocessdata")
1574 p = subprocess.Popen([sys.executable, sigchild_ignore],
1575 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1576 stdout, stderr = p.communicate()
1577 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001578 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001579 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001580
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001581 def test_select_unbuffered(self):
1582 # Issue #11459: bufsize=0 should really set the pipes as
1583 # unbuffered (and therefore let select() work properly).
1584 select = support.import_module("select")
1585 p = subprocess.Popen([sys.executable, "-c",
1586 'import sys;'
1587 'sys.stdout.write("apple")'],
1588 stdout=subprocess.PIPE,
1589 bufsize=0)
1590 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001591 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001592 try:
1593 self.assertEqual(f.read(4), b"appl")
1594 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1595 finally:
1596 p.wait()
1597
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001598 def test_zombie_fast_process_del(self):
1599 # Issue #12650: on Unix, if Popen.__del__() was called before the
1600 # process exited, it wouldn't be added to subprocess._active, and would
1601 # remain a zombie.
1602 # spawn a Popen, and delete its reference before it exits
1603 p = subprocess.Popen([sys.executable, "-c",
1604 'import sys, time;'
1605 'time.sleep(0.2)'],
1606 stdout=subprocess.PIPE,
1607 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001608 self.addCleanup(p.stdout.close)
1609 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001610 ident = id(p)
1611 pid = p.pid
1612 del p
1613 # check that p is in the active processes list
1614 self.assertIn(ident, [id(o) for o in subprocess._active])
1615
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001616 def test_leak_fast_process_del_killed(self):
1617 # Issue #12650: on Unix, if Popen.__del__() was called before the
1618 # process exited, and the process got killed by a signal, it would never
1619 # be removed from subprocess._active, which triggered a FD and memory
1620 # leak.
1621 # spawn a Popen, delete its reference and kill it
1622 p = subprocess.Popen([sys.executable, "-c",
1623 'import time;'
1624 'time.sleep(3)'],
1625 stdout=subprocess.PIPE,
1626 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001627 self.addCleanup(p.stdout.close)
1628 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001629 ident = id(p)
1630 pid = p.pid
1631 del p
1632 os.kill(pid, signal.SIGKILL)
1633 # check that p is in the active processes list
1634 self.assertIn(ident, [id(o) for o in subprocess._active])
1635
1636 # let some time for the process to exit, and create a new Popen: this
1637 # should trigger the wait() of p
1638 time.sleep(0.2)
1639 with self.assertRaises(EnvironmentError) as c:
1640 with subprocess.Popen(['nonexisting_i_hope'],
1641 stdout=subprocess.PIPE,
1642 stderr=subprocess.PIPE) as proc:
1643 pass
1644 # p should have been wait()ed on, and removed from the _active list
1645 self.assertRaises(OSError, os.waitpid, pid, 0)
1646 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1647
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001648
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001649@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001650class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001651
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001652 def test_startupinfo(self):
1653 # startupinfo argument
1654 # We uses hardcoded constants, because we do not want to
1655 # depend on win32all.
1656 STARTF_USESHOWWINDOW = 1
1657 SW_MAXIMIZE = 3
1658 startupinfo = subprocess.STARTUPINFO()
1659 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1660 startupinfo.wShowWindow = SW_MAXIMIZE
1661 # Since Python is a console process, it won't be affected
1662 # by wShowWindow, but the argument should be silently
1663 # ignored
1664 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001665 startupinfo=startupinfo)
1666
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001667 def test_creationflags(self):
1668 # creationflags argument
1669 CREATE_NEW_CONSOLE = 16
1670 sys.stderr.write(" a DOS box should flash briefly ...\n")
1671 subprocess.call(sys.executable +
1672 ' -c "import time; time.sleep(0.25)"',
1673 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001674
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001675 def test_invalid_args(self):
1676 # invalid arguments should raise ValueError
1677 self.assertRaises(ValueError, subprocess.call,
1678 [sys.executable, "-c",
1679 "import sys; sys.exit(47)"],
1680 preexec_fn=lambda: 1)
1681 self.assertRaises(ValueError, subprocess.call,
1682 [sys.executable, "-c",
1683 "import sys; sys.exit(47)"],
1684 stdout=subprocess.PIPE,
1685 close_fds=True)
1686
1687 def test_close_fds(self):
1688 # close file descriptors
1689 rc = subprocess.call([sys.executable, "-c",
1690 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001691 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001692 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001693
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001694 def test_shell_sequence(self):
1695 # Run command through the shell (sequence)
1696 newenv = os.environ.copy()
1697 newenv["FRUIT"] = "physalis"
1698 p = subprocess.Popen(["set"], shell=1,
1699 stdout=subprocess.PIPE,
1700 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001701 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001702 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001703
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001704 def test_shell_string(self):
1705 # Run command through the shell (string)
1706 newenv = os.environ.copy()
1707 newenv["FRUIT"] = "physalis"
1708 p = subprocess.Popen("set", shell=1,
1709 stdout=subprocess.PIPE,
1710 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001711 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001712 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001713
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001714 def test_call_string(self):
1715 # call() function with string argument on Windows
1716 rc = subprocess.call(sys.executable +
1717 ' -c "import sys; sys.exit(47)"')
1718 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001719
Florent Xicluna4886d242010-03-08 13:27:26 +00001720 def _kill_process(self, method, *args):
1721 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001722 p = subprocess.Popen([sys.executable, "-c", """if 1:
1723 import sys, time
1724 sys.stdout.write('x\\n')
1725 sys.stdout.flush()
1726 time.sleep(30)
1727 """],
1728 stdin=subprocess.PIPE,
1729 stdout=subprocess.PIPE,
1730 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001731 self.addCleanup(p.stdout.close)
1732 self.addCleanup(p.stderr.close)
1733 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001734 # Wait for the interpreter to be completely initialized before
1735 # sending any signal.
1736 p.stdout.read(1)
1737 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001738 _, stderr = p.communicate()
1739 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001740 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001741 self.assertNotEqual(returncode, 0)
1742
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001743 def _kill_dead_process(self, method, *args):
1744 p = subprocess.Popen([sys.executable, "-c", """if 1:
1745 import sys, time
1746 sys.stdout.write('x\\n')
1747 sys.stdout.flush()
1748 sys.exit(42)
1749 """],
1750 stdin=subprocess.PIPE,
1751 stdout=subprocess.PIPE,
1752 stderr=subprocess.PIPE)
1753 self.addCleanup(p.stdout.close)
1754 self.addCleanup(p.stderr.close)
1755 self.addCleanup(p.stdin.close)
1756 # Wait for the interpreter to be completely initialized before
1757 # sending any signal.
1758 p.stdout.read(1)
1759 # The process should end after this
1760 time.sleep(1)
1761 # This shouldn't raise even though the child is now dead
1762 getattr(p, method)(*args)
1763 _, stderr = p.communicate()
1764 self.assertStderrEqual(stderr, b'')
1765 rc = p.wait()
1766 self.assertEqual(rc, 42)
1767
Florent Xicluna4886d242010-03-08 13:27:26 +00001768 def test_send_signal(self):
1769 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001770
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001771 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001772 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001773
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001774 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001775 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001776
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001777 def test_send_signal_dead(self):
1778 self._kill_dead_process('send_signal', signal.SIGTERM)
1779
1780 def test_kill_dead(self):
1781 self._kill_dead_process('kill')
1782
1783 def test_terminate_dead(self):
1784 self._kill_dead_process('terminate')
1785
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001786
Brett Cannona23810f2008-05-26 19:04:21 +00001787# The module says:
1788# "NB This only works (and is only relevant) for UNIX."
1789#
1790# Actually, getoutput should work on any platform with an os.popen, but
1791# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001792@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001793class CommandTests(unittest.TestCase):
1794 def test_getoutput(self):
1795 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1796 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1797 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001798
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001799 # we use mkdtemp in the next line to create an empty directory
1800 # under our exclusive control; from that, we can invent a pathname
1801 # that we _know_ won't exist. This is guaranteed to fail.
1802 dir = None
1803 try:
1804 dir = tempfile.mkdtemp()
1805 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001806
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001807 status, output = subprocess.getstatusoutput('cat ' + name)
1808 self.assertNotEqual(status, 0)
1809 finally:
1810 if dir is not None:
1811 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001812
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001813
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001814@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1815 "poll system call not supported")
1816class ProcessTestCaseNoPoll(ProcessTestCase):
1817 def setUp(self):
1818 subprocess._has_poll = False
1819 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001820
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001821 def tearDown(self):
1822 subprocess._has_poll = True
1823 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001824
1825
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001826class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001827 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001828 def test_eintr_retry_call(self):
1829 record_calls = []
1830 def fake_os_func(*args):
1831 record_calls.append(args)
1832 if len(record_calls) == 2:
1833 raise OSError(errno.EINTR, "fake interrupted system call")
1834 return tuple(reversed(args))
1835
1836 self.assertEqual((999, 256),
1837 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1838 self.assertEqual([(256, 999)], record_calls)
1839 # This time there will be an EINTR so it will loop once.
1840 self.assertEqual((666,),
1841 subprocess._eintr_retry_call(fake_os_func, 666))
1842 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1843
1844
Tim Golden126c2962010-08-11 14:20:40 +00001845@unittest.skipUnless(mswindows, "Windows-specific tests")
1846class CommandsWithSpaces (BaseTestCase):
1847
1848 def setUp(self):
1849 super().setUp()
1850 f, fname = mkstemp(".py", "te st")
1851 self.fname = fname.lower ()
1852 os.write(f, b"import sys;"
1853 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1854 )
1855 os.close(f)
1856
1857 def tearDown(self):
1858 os.remove(self.fname)
1859 super().tearDown()
1860
1861 def with_spaces(self, *args, **kwargs):
1862 kwargs['stdout'] = subprocess.PIPE
1863 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001864 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001865 self.assertEqual(
1866 p.stdout.read ().decode("mbcs"),
1867 "2 [%r, 'ab cd']" % self.fname
1868 )
1869
1870 def test_shell_string_with_spaces(self):
1871 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001872 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1873 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001874
1875 def test_shell_sequence_with_spaces(self):
1876 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001877 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001878
1879 def test_noshell_string_with_spaces(self):
1880 # call() function with string argument with spaces on Windows
1881 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1882 "ab cd"))
1883
1884 def test_noshell_sequence_with_spaces(self):
1885 # call() function with sequence argument with spaces on Windows
1886 self.with_spaces([sys.executable, self.fname, "ab cd"])
1887
Brian Curtin79cdb662010-12-03 02:46:02 +00001888
Georg Brandla86b2622012-02-20 21:34:57 +01001889class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00001890
1891 def test_pipe(self):
1892 with subprocess.Popen([sys.executable, "-c",
1893 "import sys;"
1894 "sys.stdout.write('stdout');"
1895 "sys.stderr.write('stderr');"],
1896 stdout=subprocess.PIPE,
1897 stderr=subprocess.PIPE) as proc:
1898 self.assertEqual(proc.stdout.read(), b"stdout")
1899 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1900
1901 self.assertTrue(proc.stdout.closed)
1902 self.assertTrue(proc.stderr.closed)
1903
1904 def test_returncode(self):
1905 with subprocess.Popen([sys.executable, "-c",
1906 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07001907 pass
1908 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00001909 self.assertEqual(proc.returncode, 100)
1910
1911 def test_communicate_stdin(self):
1912 with subprocess.Popen([sys.executable, "-c",
1913 "import sys;"
1914 "sys.exit(sys.stdin.read() == 'context')"],
1915 stdin=subprocess.PIPE) as proc:
1916 proc.communicate(b"context")
1917 self.assertEqual(proc.returncode, 1)
1918
1919 def test_invalid_args(self):
1920 with self.assertRaises(EnvironmentError) as c:
1921 with subprocess.Popen(['nonexisting_i_hope'],
1922 stdout=subprocess.PIPE,
1923 stderr=subprocess.PIPE) as proc:
1924 pass
1925
1926 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1927 raise c.exception
1928
1929
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001930def test_main():
1931 unit_tests = (ProcessTestCase,
1932 POSIXProcessTestCase,
1933 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001934 CommandTests,
1935 ProcessTestCaseNoPoll,
1936 HelperFunctionTests,
1937 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02001938 ContextManagerTests,
1939 )
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001940
1941 support.run_unittest(*unit_tests)
1942 support.reap_children()
1943
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001944if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001945 unittest.main()