blob: 2420772c36f359fdb25f0002a28487618618384e [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
Andrew Svetlov82860712012-08-19 22:13:41 +03007import locale
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00008import os
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00009import errno
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000010import tempfile
11import time
Tim Peters3761e8d2004-10-13 04:07:12 +000012import re
Ezio Melotti184bdfb2010-02-18 09:37:05 +000013import sysconfig
Gregory P. Smithd23047b2010-12-04 09:10:44 +000014import warnings
Gregory P. Smith51ee2702010-12-13 07:59:39 +000015import select
Gregory P. Smith81ce6852011-03-15 02:04:11 -040016import shutil
Benjamin Petersonb870aa12011-12-10 12:44:25 -050017import gc
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030018import textwrap
Benjamin Peterson964561b2011-12-10 12:31:42 -050019
20try:
21 import resource
22except ImportError:
23 resource = None
24
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000025mswindows = (sys.platform == "win32")
26
27#
28# Depends on the following external programs: Python
29#
30
31if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000032 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
33 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000034else:
35 SETBINARY = ''
36
Florent Xiclunab1e94e82010-02-27 22:12:37 +000037
38try:
39 mkstemp = tempfile.mkstemp
40except AttributeError:
41 # tempfile.mkstemp is not available
42 def mkstemp():
43 """Replacement for mkstemp, calling mktemp."""
44 fname = tempfile.mktemp()
45 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
46
Tim Peters3761e8d2004-10-13 04:07:12 +000047
Florent Xiclunac049d872010-03-27 22:47:23 +000048class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000049 def setUp(self):
50 # Try to minimize the number of children we have so this test
51 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000052 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000053
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000054 def tearDown(self):
55 for inst in subprocess._active:
56 inst.wait()
57 subprocess._cleanup()
58 self.assertFalse(subprocess._active, "subprocess._active not empty")
59
Florent Xiclunab1e94e82010-02-27 22:12:37 +000060 def assertStderrEqual(self, stderr, expected, msg=None):
61 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
62 # shutdown time. That frustrates tests trying to check stderr produced
63 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000064 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040065 # strip_python_stderr also strips whitespace, so we do too.
66 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000067 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000068
Florent Xiclunac049d872010-03-27 22:47:23 +000069
70class ProcessTestCase(BaseTestCase):
71
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000072 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000073 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000074 rc = subprocess.call([sys.executable, "-c",
75 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000076 self.assertEqual(rc, 47)
77
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040078 def test_call_timeout(self):
79 # call() function with timeout argument; we want to test that the child
80 # process gets killed when the timeout expires. If the child isn't
81 # killed, this call will deadlock since subprocess.call waits for the
82 # child.
83 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
84 [sys.executable, "-c", "while True: pass"],
85 timeout=0.1)
86
Peter Astrand454f7672005-01-01 09:36:35 +000087 def test_check_call_zero(self):
88 # check_call() function with zero return code
89 rc = subprocess.check_call([sys.executable, "-c",
90 "import sys; sys.exit(0)"])
91 self.assertEqual(rc, 0)
92
93 def test_check_call_nonzero(self):
94 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000095 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +000096 subprocess.check_call([sys.executable, "-c",
97 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000098 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000099
Georg Brandlf9734072008-12-07 15:30:06 +0000100 def test_check_output(self):
101 # check_output() function with zero return code
102 output = subprocess.check_output(
103 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000104 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000105
106 def test_check_output_nonzero(self):
107 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000108 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000109 subprocess.check_output(
110 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000111 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000112
113 def test_check_output_stderr(self):
114 # check_output() function stderr redirected to stdout
115 output = subprocess.check_output(
116 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
117 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000118 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000119
120 def test_check_output_stdout_arg(self):
121 # check_output() function stderr redirected to stdout
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000122 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000123 output = subprocess.check_output(
124 [sys.executable, "-c", "print('will not be run')"],
125 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000126 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000127 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000128
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400129 def test_check_output_timeout(self):
130 # check_output() function with timeout arg
131 with self.assertRaises(subprocess.TimeoutExpired) as c:
132 output = subprocess.check_output(
133 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200134 "import sys, time\n"
135 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400136 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200137 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400138 # Some heavily loaded buildbots (sparc Debian 3.x) require
139 # this much time to start and print.
140 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400141 self.fail("Expected TimeoutExpired.")
142 self.assertEqual(c.exception.output, b'BDFL')
143
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000144 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000145 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000146 newenv = os.environ.copy()
147 newenv["FRUIT"] = "banana"
148 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000149 'import sys, os;'
150 'sys.exit(os.getenv("FRUIT")=="banana")'],
151 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000152 self.assertEqual(rc, 1)
153
Victor Stinner87b9bc32011-06-01 00:57:47 +0200154 def test_invalid_args(self):
155 # Popen() called with invalid arguments should raise TypeError
156 # but Popen.__del__ should not complain (issue #12085)
157 with support.captured_stderr() as s:
158 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
159 argcount = subprocess.Popen.__init__.__code__.co_argcount
160 too_many_args = [0] * (argcount + 1)
161 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
162 self.assertEqual(s.getvalue(), '')
163
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000164 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000165 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000166 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000167 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000168 self.addCleanup(p.stdout.close)
169 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000170 p.wait()
171 self.assertEqual(p.stdin, None)
172
173 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000174 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000175 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000176 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000177 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000178 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000179 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000180 self.addCleanup(p.stdin.close)
181 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000182 p.wait()
183 self.assertEqual(p.stdout, None)
184
185 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000186 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000187 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000188 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000189 self.addCleanup(p.stdout.close)
190 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000191 p.wait()
192 self.assertEqual(p.stderr, None)
193
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100194 @unittest.skipIf(sys.base_prefix != sys.prefix,
195 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000196 def test_executable_with_cwd(self):
Florent Xicluna1d1ab972010-03-11 01:53:10 +0000197 python_dir = os.path.dirname(os.path.realpath(sys.executable))
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000198 p = subprocess.Popen(["somethingyoudonthave", "-c",
199 "import sys; sys.exit(47)"],
200 executable=sys.executable, cwd=python_dir)
201 p.wait()
202 self.assertEqual(p.returncode, 47)
203
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100204 @unittest.skipIf(sys.base_prefix != sys.prefix,
205 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000206 @unittest.skipIf(sysconfig.is_python_build(),
207 "need an installed Python. See #7774")
208 def test_executable_without_cwd(self):
209 # For a normal installation, it should work without 'cwd'
210 # argument. For test runs in the build directory, see #7774.
211 p = subprocess.Popen(["somethingyoudonthave", "-c",
212 "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000213 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000214 p.wait()
215 self.assertEqual(p.returncode, 47)
216
217 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000218 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000219 p = subprocess.Popen([sys.executable, "-c",
220 'import sys; sys.exit(sys.stdin.read() == "pear")'],
221 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000222 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000223 p.stdin.close()
224 p.wait()
225 self.assertEqual(p.returncode, 1)
226
227 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000228 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000229 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000230 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000231 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000232 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000233 os.lseek(d, 0, 0)
234 p = subprocess.Popen([sys.executable, "-c",
235 'import sys; sys.exit(sys.stdin.read() == "pear")'],
236 stdin=d)
237 p.wait()
238 self.assertEqual(p.returncode, 1)
239
240 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000241 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000242 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000243 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000244 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000245 tf.seek(0)
246 p = subprocess.Popen([sys.executable, "-c",
247 'import sys; sys.exit(sys.stdin.read() == "pear")'],
248 stdin=tf)
249 p.wait()
250 self.assertEqual(p.returncode, 1)
251
252 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000253 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000254 p = subprocess.Popen([sys.executable, "-c",
255 'import sys; sys.stdout.write("orange")'],
256 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000257 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000258 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000259
260 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000261 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000262 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000263 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000264 d = tf.fileno()
265 p = subprocess.Popen([sys.executable, "-c",
266 'import sys; sys.stdout.write("orange")'],
267 stdout=d)
268 p.wait()
269 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000270 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000271
272 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000273 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000274 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000275 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000276 p = subprocess.Popen([sys.executable, "-c",
277 'import sys; sys.stdout.write("orange")'],
278 stdout=tf)
279 p.wait()
280 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000281 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000282
283 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000284 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000285 p = subprocess.Popen([sys.executable, "-c",
286 'import sys; sys.stderr.write("strawberry")'],
287 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000288 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000289 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000290
291 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000292 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000293 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000294 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000295 d = tf.fileno()
296 p = subprocess.Popen([sys.executable, "-c",
297 'import sys; sys.stderr.write("strawberry")'],
298 stderr=d)
299 p.wait()
300 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000301 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000302
303 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000304 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000305 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000306 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000307 p = subprocess.Popen([sys.executable, "-c",
308 'import sys; sys.stderr.write("strawberry")'],
309 stderr=tf)
310 p.wait()
311 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000312 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000313
314 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000315 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000316 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000317 'import sys;'
318 'sys.stdout.write("apple");'
319 'sys.stdout.flush();'
320 'sys.stderr.write("orange")'],
321 stdout=subprocess.PIPE,
322 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000323 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000324 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000325
326 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000327 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000328 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000329 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000330 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000331 'import sys;'
332 'sys.stdout.write("apple");'
333 'sys.stdout.flush();'
334 'sys.stderr.write("orange")'],
335 stdout=tf,
336 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000337 p.wait()
338 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000339 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000340
Thomas Wouters89f507f2006-12-13 04:49:30 +0000341 def test_stdout_filedes_of_stdout(self):
342 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000343 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000344 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000345 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000346
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200347 def test_stdout_devnull(self):
348 p = subprocess.Popen([sys.executable, "-c",
349 'for i in range(10240):'
350 'print("x" * 1024)'],
351 stdout=subprocess.DEVNULL)
352 p.wait()
353 self.assertEqual(p.stdout, None)
354
355 def test_stderr_devnull(self):
356 p = subprocess.Popen([sys.executable, "-c",
357 'import sys\n'
358 'for i in range(10240):'
359 'sys.stderr.write("x" * 1024)'],
360 stderr=subprocess.DEVNULL)
361 p.wait()
362 self.assertEqual(p.stderr, None)
363
364 def test_stdin_devnull(self):
365 p = subprocess.Popen([sys.executable, "-c",
366 'import sys;'
367 'sys.stdin.read(1)'],
368 stdin=subprocess.DEVNULL)
369 p.wait()
370 self.assertEqual(p.stdin, None)
371
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000372 def test_cwd(self):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000373 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000374 # We cannot use os.path.realpath to canonicalize the path,
375 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
376 cwd = os.getcwd()
377 os.chdir(tmpdir)
378 tmpdir = os.getcwd()
379 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000380 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000381 'import sys,os;'
382 'sys.stdout.write(os.getcwd())'],
383 stdout=subprocess.PIPE,
384 cwd=tmpdir)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000385 self.addCleanup(p.stdout.close)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000386 normcase = os.path.normcase
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000387 self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
388 normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000389
390 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000391 newenv = os.environ.copy()
392 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200393 with subprocess.Popen([sys.executable, "-c",
394 'import sys,os;'
395 'sys.stdout.write(os.getenv("FRUIT"))'],
396 stdout=subprocess.PIPE,
397 env=newenv) as p:
398 stdout, stderr = p.communicate()
399 self.assertEqual(stdout, b"orange")
400
Victor Stinner62d51182011-06-23 01:02:25 +0200401 # Windows requires at least the SYSTEMROOT environment variable to start
402 # Python
403 @unittest.skipIf(sys.platform == 'win32',
404 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200405 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200406 'the python library cannot be loaded '
407 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200408 def test_empty_env(self):
409 with subprocess.Popen([sys.executable, "-c",
410 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200411 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200412 stdout=subprocess.PIPE,
413 env={}) as p:
414 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200415 self.assertIn(stdout.strip(),
416 (b"[]",
417 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
418 # environment
419 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000420
Peter Astrandcbac93c2005-03-03 20:24:28 +0000421 def test_communicate_stdin(self):
422 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000423 'import sys;'
424 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000425 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000426 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000427 self.assertEqual(p.returncode, 1)
428
429 def test_communicate_stdout(self):
430 p = subprocess.Popen([sys.executable, "-c",
431 'import sys; sys.stdout.write("pineapple")'],
432 stdout=subprocess.PIPE)
433 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000434 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000435 self.assertEqual(stderr, None)
436
437 def test_communicate_stderr(self):
438 p = subprocess.Popen([sys.executable, "-c",
439 'import sys; sys.stderr.write("pineapple")'],
440 stderr=subprocess.PIPE)
441 (stdout, stderr) = p.communicate()
442 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000443 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000444
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000445 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000446 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000447 'import sys,os;'
448 'sys.stderr.write("pineapple");'
449 'sys.stdout.write(sys.stdin.read())'],
450 stdin=subprocess.PIPE,
451 stdout=subprocess.PIPE,
452 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000453 self.addCleanup(p.stdout.close)
454 self.addCleanup(p.stderr.close)
455 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000456 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000457 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000458 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000459
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400460 def test_communicate_timeout(self):
461 p = subprocess.Popen([sys.executable, "-c",
462 'import sys,os,time;'
463 'sys.stderr.write("pineapple\\n");'
464 'time.sleep(1);'
465 'sys.stderr.write("pear\\n");'
466 'sys.stdout.write(sys.stdin.read())'],
467 universal_newlines=True,
468 stdin=subprocess.PIPE,
469 stdout=subprocess.PIPE,
470 stderr=subprocess.PIPE)
471 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
472 timeout=0.3)
473 # Make sure we can keep waiting for it, and that we get the whole output
474 # after it completes.
475 (stdout, stderr) = p.communicate()
476 self.assertEqual(stdout, "banana")
477 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
478
479 def test_communicate_timeout_large_ouput(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200480 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400481 p = subprocess.Popen([sys.executable, "-c",
482 'import sys,os,time;'
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 'time.sleep(0.2);'
489 'sys.stdout.write("a" * (64 * 1024));'],
490 stdout=subprocess.PIPE)
491 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
492 (stdout, _) = p.communicate()
493 self.assertEqual(len(stdout), 4 * 64 * 1024)
494
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000495 # Test for the fd leak reported in http://bugs.python.org/issue2791.
496 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000497 for stdin_pipe in (False, True):
498 for stdout_pipe in (False, True):
499 for stderr_pipe in (False, True):
500 options = {}
501 if stdin_pipe:
502 options['stdin'] = subprocess.PIPE
503 if stdout_pipe:
504 options['stdout'] = subprocess.PIPE
505 if stderr_pipe:
506 options['stderr'] = subprocess.PIPE
507 if not options:
508 continue
509 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
510 p.communicate()
511 if p.stdin is not None:
512 self.assertTrue(p.stdin.closed)
513 if p.stdout is not None:
514 self.assertTrue(p.stdout.closed)
515 if p.stderr is not None:
516 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000517
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000518 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000519 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000520 p = subprocess.Popen([sys.executable, "-c",
521 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000522 (stdout, stderr) = p.communicate()
523 self.assertEqual(stdout, None)
524 self.assertEqual(stderr, None)
525
526 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000527 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000528 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000529 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000530 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000531 os.close(x)
532 os.close(y)
533 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000534 'import sys,os;'
535 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200536 'sys.stderr.write("x" * %d);'
537 'sys.stdout.write(sys.stdin.read())' %
538 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000539 stdin=subprocess.PIPE,
540 stdout=subprocess.PIPE,
541 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000542 self.addCleanup(p.stdout.close)
543 self.addCleanup(p.stderr.close)
544 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200545 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000546 (stdout, stderr) = p.communicate(string_to_write)
547 self.assertEqual(stdout, string_to_write)
548
549 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000550 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000551 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000552 'import sys,os;'
553 'sys.stdout.write(sys.stdin.read())'],
554 stdin=subprocess.PIPE,
555 stdout=subprocess.PIPE,
556 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000557 self.addCleanup(p.stdout.close)
558 self.addCleanup(p.stderr.close)
559 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000560 p.stdin.write(b"banana")
561 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000562 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000563 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000564
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000565 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000566 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000567 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200568 'buf = sys.stdout.buffer;'
569 'buf.write(sys.stdin.readline().encode());'
570 'buf.flush();'
571 'buf.write(b"line2\\n");'
572 'buf.flush();'
573 'buf.write(sys.stdin.read().encode());'
574 'buf.flush();'
575 'buf.write(b"line4\\n");'
576 'buf.flush();'
577 'buf.write(b"line5\\r\\n");'
578 'buf.flush();'
579 'buf.write(b"line6\\r");'
580 'buf.flush();'
581 'buf.write(b"\\nline7");'
582 'buf.flush();'
583 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200584 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000585 stdout=subprocess.PIPE,
586 universal_newlines=1)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200587 p.stdin.write("line1\n")
588 self.assertEqual(p.stdout.readline(), "line1\n")
589 p.stdin.write("line3\n")
590 p.stdin.close()
Brian Curtin3c6a9512010-11-05 03:58:52 +0000591 self.addCleanup(p.stdout.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200592 self.assertEqual(p.stdout.readline(),
593 "line2\n")
594 self.assertEqual(p.stdout.read(6),
595 "line3\n")
596 self.assertEqual(p.stdout.read(),
597 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000598
599 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000600 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000601 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000602 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200603 'buf = sys.stdout.buffer;'
604 'buf.write(b"line2\\n");'
605 'buf.flush();'
606 'buf.write(b"line4\\n");'
607 'buf.flush();'
608 'buf.write(b"line5\\r\\n");'
609 'buf.flush();'
610 'buf.write(b"line6\\r");'
611 'buf.flush();'
612 'buf.write(b"\\nline7");'
613 'buf.flush();'
614 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200615 stderr=subprocess.PIPE,
616 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000617 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000618 self.addCleanup(p.stdout.close)
619 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000620 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200621 self.assertEqual(stdout,
622 "line2\nline4\nline5\nline6\nline7\nline8")
623
624 def test_universal_newlines_communicate_stdin(self):
625 # universal newlines through communicate(), with only stdin
626 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300627 'import sys,os;' + SETBINARY + textwrap.dedent('''
628 s = sys.stdin.readline()
629 assert s == "line1\\n", repr(s)
630 s = sys.stdin.read()
631 assert s == "line3\\n", repr(s)
632 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200633 stdin=subprocess.PIPE,
634 universal_newlines=1)
635 (stdout, stderr) = p.communicate("line1\nline3\n")
636 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000637
Andrew Svetlovf3765072012-08-14 18:35:17 +0300638 def test_universal_newlines_communicate_input_none(self):
639 # Test communicate(input=None) with universal newlines.
640 #
641 # We set stdout to PIPE because, as of this writing, a different
642 # code path is tested when the number of pipes is zero or one.
643 p = subprocess.Popen([sys.executable, "-c", "pass"],
644 stdin=subprocess.PIPE,
645 stdout=subprocess.PIPE,
646 universal_newlines=True)
647 p.communicate()
648 self.assertEqual(p.returncode, 0)
649
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300650 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300651 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300652 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300653 'import sys,os;' + SETBINARY + textwrap.dedent('''
654 s = sys.stdin.buffer.readline()
655 sys.stdout.buffer.write(s)
656 sys.stdout.buffer.write(b"line2\\r")
657 sys.stderr.buffer.write(b"eline2\\n")
658 s = sys.stdin.buffer.read()
659 sys.stdout.buffer.write(s)
660 sys.stdout.buffer.write(b"line4\\n")
661 sys.stdout.buffer.write(b"line5\\r\\n")
662 sys.stderr.buffer.write(b"eline6\\r")
663 sys.stderr.buffer.write(b"eline7\\r\\nz")
664 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300665 stdin=subprocess.PIPE,
666 stderr=subprocess.PIPE,
667 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300668 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300669 self.addCleanup(p.stdout.close)
670 self.addCleanup(p.stderr.close)
671 (stdout, stderr) = p.communicate("line1\nline3\n")
672 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300673 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300674 # Python debug build push something like "[42442 refs]\n"
675 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300676 # Don't use assertStderrEqual because it strips CR and LF from output.
677 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300678
Andrew Svetlov82860712012-08-19 22:13:41 +0300679 def test_universal_newlines_communicate_encodings(self):
680 # Check that universal newlines mode works for various encodings,
681 # in particular for encodings in the UTF-16 and UTF-32 families.
682 # See issue #15595.
683 #
684 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
685 # without, and UTF-16 and UTF-32.
686 for encoding in ['utf-16', 'utf-32-be']:
687 old_getpreferredencoding = locale.getpreferredencoding
688 # Indirectly via io.TextIOWrapper, Popen() defaults to
689 # locale.getpreferredencoding(False) and earlier in Python 3.2 to
690 # locale.getpreferredencoding().
691 def getpreferredencoding(do_setlocale=True):
692 return encoding
693 code = ("import sys; "
694 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
695 encoding)
696 args = [sys.executable, '-c', code]
697 try:
698 locale.getpreferredencoding = getpreferredencoding
699 # We set stdin to be non-None because, as of this writing,
700 # a different code path is used when the number of pipes is
701 # zero or one.
702 popen = subprocess.Popen(args, universal_newlines=True,
703 stdin=subprocess.PIPE,
704 stdout=subprocess.PIPE)
705 stdout, stderr = popen.communicate(input='')
706 finally:
707 locale.getpreferredencoding = old_getpreferredencoding
Andrew Svetlov82860712012-08-19 22:13:41 +0300708 self.assertEqual(stdout, '1\n2\n3\n4')
709
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000710 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000711 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000712 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000713 max_handles = 1026 # too much for most UNIX systems
714 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000715 max_handles = 2050 # too much for (at least some) Windows setups
716 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400717 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000718 try:
719 for i in range(max_handles):
720 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400721 tmpfile = os.path.join(tmpdir, support.TESTFN)
722 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000723 except OSError as e:
724 if e.errno != errno.EMFILE:
725 raise
726 break
727 else:
728 self.skipTest("failed to reach the file descriptor limit "
729 "(tried %d)" % max_handles)
730 # Close a couple of them (should be enough for a subprocess)
731 for i in range(10):
732 os.close(handles.pop())
733 # Loop creating some subprocesses. If one of them leaks some fds,
734 # the next loop iteration will fail by reaching the max fd limit.
735 for i in range(15):
736 p = subprocess.Popen([sys.executable, "-c",
737 "import sys;"
738 "sys.stdout.write(sys.stdin.read())"],
739 stdin=subprocess.PIPE,
740 stdout=subprocess.PIPE,
741 stderr=subprocess.PIPE)
742 data = p.communicate(b"lime")[0]
743 self.assertEqual(data, b"lime")
744 finally:
745 for h in handles:
746 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400747 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000748
749 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000750 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
751 '"a b c" d e')
752 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
753 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000754 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
755 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000756 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
757 'a\\\\\\b "de fg" h')
758 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
759 'a\\\\\\"b c d')
760 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
761 '"a\\\\b c" d e')
762 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
763 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000764 self.assertEqual(subprocess.list2cmdline(['ab', '']),
765 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000766
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000767 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200768 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +0200769 "import os; os.read(0, 1)"],
770 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200771 self.addCleanup(p.stdin.close)
772 self.assertIsNone(p.poll())
773 os.write(p.stdin.fileno(), b'A')
774 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000775 # Subsequent invocations should just return the returncode
776 self.assertEqual(p.poll(), 0)
777
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000778 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200779 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000780 self.assertEqual(p.wait(), 0)
781 # Subsequent invocations should just return the returncode
782 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000783
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400784 def test_wait_timeout(self):
785 p = subprocess.Popen([sys.executable,
Reid Kleckner93479cc2011-03-14 19:32:41 -0400786 "-c", "import time; time.sleep(0.1)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -0400787 with self.assertRaises(subprocess.TimeoutExpired) as c:
788 p.wait(timeout=0.01)
789 self.assertIn("0.01", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -0400790 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
791 # time to start.
792 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400793
Peter Astrand738131d2004-11-30 21:04:45 +0000794 def test_invalid_bufsize(self):
795 # an invalid type of the bufsize argument should raise
796 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000797 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000798 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000799
Guido van Rossum46a05a72007-06-07 21:56:45 +0000800 def test_bufsize_is_none(self):
801 # bufsize=None should be the same as bufsize=0.
802 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
803 self.assertEqual(p.wait(), 0)
804 # Again with keyword arg
805 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
806 self.assertEqual(p.wait(), 0)
807
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000808 def test_leaking_fds_on_error(self):
809 # see bug #5179: Popen leaks file descriptors to PIPEs if
810 # the child fails to execute; this will eventually exhaust
811 # the maximum number of open fds. 1024 seems a very common
812 # value for that limit, but Windows has 2048, so we loop
813 # 1024 times (each call leaked two fds).
814 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000815 # Windows raises IOError. Others raise OSError.
816 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000817 subprocess.Popen(['nonexisting_i_hope'],
818 stdout=subprocess.PIPE,
819 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400820 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400821 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000822 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000823
Victor Stinnerb3693582010-05-21 20:13:12 +0000824 def test_issue8780(self):
825 # Ensure that stdout is inherited from the parent
826 # if stdout=PIPE is not used
827 code = ';'.join((
828 'import subprocess, sys',
829 'retcode = subprocess.call('
830 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
831 'assert retcode == 0'))
832 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000833 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000834
Tim Goldenaf5ac392010-08-06 13:03:56 +0000835 def test_handles_closed_on_exception(self):
836 # If CreateProcess exits with an error, ensure the
837 # duplicate output handles are released
838 ifhandle, ifname = mkstemp()
839 ofhandle, ofname = mkstemp()
840 efhandle, efname = mkstemp()
841 try:
842 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
843 stderr=efhandle)
844 except OSError:
845 os.close(ifhandle)
846 os.remove(ifname)
847 os.close(ofhandle)
848 os.remove(ofname)
849 os.close(efhandle)
850 os.remove(efname)
851 self.assertFalse(os.path.exists(ifname))
852 self.assertFalse(os.path.exists(ofname))
853 self.assertFalse(os.path.exists(efname))
854
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200855 def test_communicate_epipe(self):
856 # Issue 10963: communicate() should hide EPIPE
857 p = subprocess.Popen([sys.executable, "-c", 'pass'],
858 stdin=subprocess.PIPE,
859 stdout=subprocess.PIPE,
860 stderr=subprocess.PIPE)
861 self.addCleanup(p.stdout.close)
862 self.addCleanup(p.stderr.close)
863 self.addCleanup(p.stdin.close)
864 p.communicate(b"x" * 2**20)
865
866 def test_communicate_epipe_only_stdin(self):
867 # Issue 10963: communicate() should hide EPIPE
868 p = subprocess.Popen([sys.executable, "-c", 'pass'],
869 stdin=subprocess.PIPE)
870 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200871 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200872 p.communicate(b"x" * 2**20)
873
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200874 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
875 "Requires signal.SIGUSR1")
876 @unittest.skipUnless(hasattr(os, 'kill'),
877 "Requires os.kill")
878 @unittest.skipUnless(hasattr(os, 'getppid'),
879 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200880 def test_communicate_eintr(self):
881 # Issue #12493: communicate() should handle EINTR
882 def handler(signum, frame):
883 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200884 old_handler = signal.signal(signal.SIGUSR1, handler)
885 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200886
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200887 args = [sys.executable, "-c",
888 'import os, signal;'
889 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200890 for stream in ('stdout', 'stderr'):
891 kw = {stream: subprocess.PIPE}
892 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200893 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200894 process.communicate()
895
Tim Peterse718f612004-10-12 21:51:32 +0000896
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000897# context manager
898class _SuppressCoreFiles(object):
899 """Try to prevent core files from being created."""
900 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000901
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000902 def __enter__(self):
903 """Try to save previous ulimit, then set it to (0, 0)."""
Benjamin Peterson964561b2011-12-10 12:31:42 -0500904 if resource is not None:
905 try:
906 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
907 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
908 except (ValueError, resource.error):
909 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000910
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000911 if sys.platform == 'darwin':
912 # Check if the 'Crash Reporter' on OSX was configured
913 # in 'Developer' mode and warn that it will get triggered
914 # when it is.
915 #
916 # This assumes that this context manager is used in tests
917 # that might trigger the next manager.
918 value = subprocess.Popen(['/usr/bin/defaults', 'read',
919 'com.apple.CrashReporter', 'DialogType'],
920 stdout=subprocess.PIPE).communicate()[0]
921 if value.strip() == b'developer':
922 print("this tests triggers the Crash Reporter, "
923 "that is intentional", end='')
924 sys.stdout.flush()
925
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000926 def __exit__(self, *args):
927 """Return core file behavior to default."""
928 if self.old_limit is None:
929 return
Benjamin Peterson964561b2011-12-10 12:31:42 -0500930 if resource is not None:
931 try:
932 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
933 except (ValueError, resource.error):
934 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000935
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000936
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000937@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000938class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000939
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000940 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000941 nonexistent_dir = "/_this/pa.th/does/not/exist"
942 try:
943 os.chdir(nonexistent_dir)
944 except OSError as e:
945 # This avoids hard coding the errno value or the OS perror()
946 # string and instead capture the exception that we want to see
947 # below for comparison.
948 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000949 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000950 else:
951 self.fail("chdir to nonexistant directory %s succeeded." %
952 nonexistent_dir)
953
954 # Error in the child re-raised in the parent.
955 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000956 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000957 cwd=nonexistent_dir)
958 except OSError as e:
959 # Test that the child process chdir failure actually makes
960 # it up to the parent process as the correct exception.
961 self.assertEqual(desired_exception.errno, e.errno)
962 self.assertEqual(desired_exception.strerror, e.strerror)
963 else:
964 self.fail("Expected OSError: %s" % desired_exception)
965
966 def test_restore_signals(self):
967 # Code coverage for both values of restore_signals to make sure it
968 # at least does not blow up.
969 # A test for behavior would be complex. Contributions welcome.
970 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
971 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
972
973 def test_start_new_session(self):
974 # For code coverage of calling setsid(). We don't care if we get an
975 # EPERM error from it depending on the test execution environment, that
976 # still indicates that it was called.
977 try:
978 output = subprocess.check_output(
979 [sys.executable, "-c",
980 "import os; print(os.getpgid(os.getpid()))"],
981 start_new_session=True)
982 except OSError as e:
983 if e.errno != errno.EPERM:
984 raise
985 else:
986 parent_pgid = os.getpgid(os.getpid())
987 child_pgid = int(output)
988 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000989
990 def test_run_abort(self):
991 # returncode handles signal termination
992 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000993 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000994 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000995 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000996 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000997
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000998 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000999 # DISCLAIMER: Setting environment variables is *not* a good use
1000 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001001 p = subprocess.Popen([sys.executable, "-c",
1002 'import sys,os;'
1003 'sys.stdout.write(os.getenv("FRUIT"))'],
1004 stdout=subprocess.PIPE,
1005 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +00001006 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001007 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001008
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001009 def test_preexec_exception(self):
1010 def raise_it():
1011 raise ValueError("What if two swallows carried a coconut?")
1012 try:
1013 p = subprocess.Popen([sys.executable, "-c", ""],
1014 preexec_fn=raise_it)
1015 except RuntimeError as e:
1016 self.assertTrue(
1017 subprocess._posixsubprocess,
1018 "Expected a ValueError from the preexec_fn")
1019 except ValueError as e:
1020 self.assertIn("coconut", e.args[0])
1021 else:
1022 self.fail("Exception raised by preexec_fn did not make it "
1023 "to the parent process.")
1024
Gregory P. Smith32ec9da2010-03-19 16:53:08 +00001025 def test_preexec_gc_module_failure(self):
1026 # This tests the code that disables garbage collection if the child
1027 # process will execute any Python.
1028 def raise_runtime_error():
1029 raise RuntimeError("this shouldn't escape")
1030 enabled = gc.isenabled()
1031 orig_gc_disable = gc.disable
1032 orig_gc_isenabled = gc.isenabled
1033 try:
1034 gc.disable()
1035 self.assertFalse(gc.isenabled())
1036 subprocess.call([sys.executable, '-c', ''],
1037 preexec_fn=lambda: None)
1038 self.assertFalse(gc.isenabled(),
1039 "Popen enabled gc when it shouldn't.")
1040
1041 gc.enable()
1042 self.assertTrue(gc.isenabled())
1043 subprocess.call([sys.executable, '-c', ''],
1044 preexec_fn=lambda: None)
1045 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1046
1047 gc.disable = raise_runtime_error
1048 self.assertRaises(RuntimeError, subprocess.Popen,
1049 [sys.executable, '-c', ''],
1050 preexec_fn=lambda: None)
1051
1052 del gc.isenabled # force an AttributeError
1053 self.assertRaises(AttributeError, subprocess.Popen,
1054 [sys.executable, '-c', ''],
1055 preexec_fn=lambda: None)
1056 finally:
1057 gc.disable = orig_gc_disable
1058 gc.isenabled = orig_gc_isenabled
1059 if not enabled:
1060 gc.disable()
1061
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001062 def test_args_string(self):
1063 # args is a string
1064 fd, fname = mkstemp()
1065 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001066 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001067 fobj.write("#!/bin/sh\n")
1068 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1069 sys.executable)
1070 os.chmod(fname, 0o700)
1071 p = subprocess.Popen(fname)
1072 p.wait()
1073 os.remove(fname)
1074 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001075
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001076 def test_invalid_args(self):
1077 # invalid arguments should raise ValueError
1078 self.assertRaises(ValueError, subprocess.call,
1079 [sys.executable, "-c",
1080 "import sys; sys.exit(47)"],
1081 startupinfo=47)
1082 self.assertRaises(ValueError, subprocess.call,
1083 [sys.executable, "-c",
1084 "import sys; sys.exit(47)"],
1085 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001086
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001087 def test_shell_sequence(self):
1088 # Run command through the shell (sequence)
1089 newenv = os.environ.copy()
1090 newenv["FRUIT"] = "apple"
1091 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1092 stdout=subprocess.PIPE,
1093 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001094 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001095 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001096
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001097 def test_shell_string(self):
1098 # Run command through the shell (string)
1099 newenv = os.environ.copy()
1100 newenv["FRUIT"] = "apple"
1101 p = subprocess.Popen("echo $FRUIT", shell=1,
1102 stdout=subprocess.PIPE,
1103 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001104 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001105 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001106
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001107 def test_call_string(self):
1108 # call() function with string argument on UNIX
1109 fd, fname = mkstemp()
1110 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001111 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001112 fobj.write("#!/bin/sh\n")
1113 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1114 sys.executable)
1115 os.chmod(fname, 0o700)
1116 rc = subprocess.call(fname)
1117 os.remove(fname)
1118 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001119
Stefan Krah9542cc62010-07-19 14:20:53 +00001120 def test_specific_shell(self):
1121 # Issue #9265: Incorrect name passed as arg[0].
1122 shells = []
1123 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1124 for name in ['bash', 'ksh']:
1125 sh = os.path.join(prefix, name)
1126 if os.path.isfile(sh):
1127 shells.append(sh)
1128 if not shells: # Will probably work for any shell but csh.
1129 self.skipTest("bash or ksh required for this test")
1130 sh = '/bin/sh'
1131 if os.path.isfile(sh) and not os.path.islink(sh):
1132 # Test will fail if /bin/sh is a symlink to csh.
1133 shells.append(sh)
1134 for sh in shells:
1135 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1136 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001137 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001138 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1139
Florent Xicluna4886d242010-03-08 13:27:26 +00001140 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001141 # Do not inherit file handles from the parent.
1142 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001143 p = subprocess.Popen([sys.executable, "-c", """if 1:
1144 import sys, time
1145 sys.stdout.write('x\\n')
1146 sys.stdout.flush()
1147 time.sleep(30)
1148 """],
1149 close_fds=True,
1150 stdin=subprocess.PIPE,
1151 stdout=subprocess.PIPE,
1152 stderr=subprocess.PIPE)
1153 # Wait for the interpreter to be completely initialized before
1154 # sending any signal.
1155 p.stdout.read(1)
1156 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001157 return p
1158
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001159 def _kill_dead_process(self, method, *args):
1160 # Do not inherit file handles from the parent.
1161 # It should fix failures on some platforms.
1162 p = subprocess.Popen([sys.executable, "-c", """if 1:
1163 import sys, time
1164 sys.stdout.write('x\\n')
1165 sys.stdout.flush()
1166 """],
1167 close_fds=True,
1168 stdin=subprocess.PIPE,
1169 stdout=subprocess.PIPE,
1170 stderr=subprocess.PIPE)
1171 # Wait for the interpreter to be completely initialized before
1172 # sending any signal.
1173 p.stdout.read(1)
1174 # The process should end after this
1175 time.sleep(1)
1176 # This shouldn't raise even though the child is now dead
1177 getattr(p, method)(*args)
1178 p.communicate()
1179
Florent Xicluna4886d242010-03-08 13:27:26 +00001180 def test_send_signal(self):
1181 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001182 _, stderr = p.communicate()
1183 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001184 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001185
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001186 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001187 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001188 _, stderr = p.communicate()
1189 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001190 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001191
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001192 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001193 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001194 _, stderr = p.communicate()
1195 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001196 self.assertEqual(p.wait(), -signal.SIGTERM)
1197
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001198 def test_send_signal_dead(self):
1199 # Sending a signal to a dead process
1200 self._kill_dead_process('send_signal', signal.SIGINT)
1201
1202 def test_kill_dead(self):
1203 # Killing a dead process
1204 self._kill_dead_process('kill')
1205
1206 def test_terminate_dead(self):
1207 # Terminating a dead process
1208 self._kill_dead_process('terminate')
1209
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001210 def check_close_std_fds(self, fds):
1211 # Issue #9905: test that subprocess pipes still work properly with
1212 # some standard fds closed
1213 stdin = 0
1214 newfds = []
1215 for a in fds:
1216 b = os.dup(a)
1217 newfds.append(b)
1218 if a == 0:
1219 stdin = b
1220 try:
1221 for fd in fds:
1222 os.close(fd)
1223 out, err = subprocess.Popen([sys.executable, "-c",
1224 'import sys;'
1225 'sys.stdout.write("apple");'
1226 'sys.stdout.flush();'
1227 'sys.stderr.write("orange")'],
1228 stdin=stdin,
1229 stdout=subprocess.PIPE,
1230 stderr=subprocess.PIPE).communicate()
1231 err = support.strip_python_stderr(err)
1232 self.assertEqual((out, err), (b'apple', b'orange'))
1233 finally:
1234 for b, a in zip(newfds, fds):
1235 os.dup2(b, a)
1236 for b in newfds:
1237 os.close(b)
1238
1239 def test_close_fd_0(self):
1240 self.check_close_std_fds([0])
1241
1242 def test_close_fd_1(self):
1243 self.check_close_std_fds([1])
1244
1245 def test_close_fd_2(self):
1246 self.check_close_std_fds([2])
1247
1248 def test_close_fds_0_1(self):
1249 self.check_close_std_fds([0, 1])
1250
1251 def test_close_fds_0_2(self):
1252 self.check_close_std_fds([0, 2])
1253
1254 def test_close_fds_1_2(self):
1255 self.check_close_std_fds([1, 2])
1256
1257 def test_close_fds_0_1_2(self):
1258 # Issue #10806: test that subprocess pipes still work properly with
1259 # all standard fds closed.
1260 self.check_close_std_fds([0, 1, 2])
1261
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001262 def test_remapping_std_fds(self):
1263 # open up some temporary files
1264 temps = [mkstemp() for i in range(3)]
1265 try:
1266 temp_fds = [fd for fd, fname in temps]
1267
1268 # unlink the files -- we won't need to reopen them
1269 for fd, fname in temps:
1270 os.unlink(fname)
1271
1272 # write some data to what will become stdin, and rewind
1273 os.write(temp_fds[1], b"STDIN")
1274 os.lseek(temp_fds[1], 0, 0)
1275
1276 # move the standard file descriptors out of the way
1277 saved_fds = [os.dup(fd) for fd in range(3)]
1278 try:
1279 # duplicate the file objects over the standard fd's
1280 for fd, temp_fd in enumerate(temp_fds):
1281 os.dup2(temp_fd, fd)
1282
1283 # now use those files in the "wrong" order, so that subprocess
1284 # has to rearrange them in the child
1285 p = subprocess.Popen([sys.executable, "-c",
1286 'import sys; got = sys.stdin.read();'
1287 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1288 stdin=temp_fds[1],
1289 stdout=temp_fds[2],
1290 stderr=temp_fds[0])
1291 p.wait()
1292 finally:
1293 # restore the original fd's underneath sys.stdin, etc.
1294 for std, saved in enumerate(saved_fds):
1295 os.dup2(saved, std)
1296 os.close(saved)
1297
1298 for fd in temp_fds:
1299 os.lseek(fd, 0, 0)
1300
1301 out = os.read(temp_fds[2], 1024)
1302 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1303 self.assertEqual(out, b"got STDIN")
1304 self.assertEqual(err, b"err")
1305
1306 finally:
1307 for fd in temp_fds:
1308 os.close(fd)
1309
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001310 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1311 # open up some temporary files
1312 temps = [mkstemp() for i in range(3)]
1313 temp_fds = [fd for fd, fname in temps]
1314 try:
1315 # unlink the files -- we won't need to reopen them
1316 for fd, fname in temps:
1317 os.unlink(fname)
1318
1319 # save a copy of the standard file descriptors
1320 saved_fds = [os.dup(fd) for fd in range(3)]
1321 try:
1322 # duplicate the temp files over the standard fd's 0, 1, 2
1323 for fd, temp_fd in enumerate(temp_fds):
1324 os.dup2(temp_fd, fd)
1325
1326 # write some data to what will become stdin, and rewind
1327 os.write(stdin_no, b"STDIN")
1328 os.lseek(stdin_no, 0, 0)
1329
1330 # now use those files in the given order, so that subprocess
1331 # has to rearrange them in the child
1332 p = subprocess.Popen([sys.executable, "-c",
1333 'import sys; got = sys.stdin.read();'
1334 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1335 stdin=stdin_no,
1336 stdout=stdout_no,
1337 stderr=stderr_no)
1338 p.wait()
1339
1340 for fd in temp_fds:
1341 os.lseek(fd, 0, 0)
1342
1343 out = os.read(stdout_no, 1024)
1344 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1345 finally:
1346 for std, saved in enumerate(saved_fds):
1347 os.dup2(saved, std)
1348 os.close(saved)
1349
1350 self.assertEqual(out, b"got STDIN")
1351 self.assertEqual(err, b"err")
1352
1353 finally:
1354 for fd in temp_fds:
1355 os.close(fd)
1356
1357 # When duping fds, if there arises a situation where one of the fds is
1358 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1359 # This tests all combinations of this.
1360 def test_swap_fds(self):
1361 self.check_swap_fds(0, 1, 2)
1362 self.check_swap_fds(0, 2, 1)
1363 self.check_swap_fds(1, 0, 2)
1364 self.check_swap_fds(1, 2, 0)
1365 self.check_swap_fds(2, 0, 1)
1366 self.check_swap_fds(2, 1, 0)
1367
Victor Stinner13bb71c2010-04-23 21:41:56 +00001368 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001369 def prepare():
1370 raise ValueError("surrogate:\uDCff")
1371
1372 try:
1373 subprocess.call(
1374 [sys.executable, "-c", "pass"],
1375 preexec_fn=prepare)
1376 except ValueError as err:
1377 # Pure Python implementations keeps the message
1378 self.assertIsNone(subprocess._posixsubprocess)
1379 self.assertEqual(str(err), "surrogate:\uDCff")
1380 except RuntimeError as err:
1381 # _posixsubprocess uses a default message
1382 self.assertIsNotNone(subprocess._posixsubprocess)
1383 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1384 else:
1385 self.fail("Expected ValueError or RuntimeError")
1386
Victor Stinner13bb71c2010-04-23 21:41:56 +00001387 def test_undecodable_env(self):
1388 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001389 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001390 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001391 env = os.environ.copy()
1392 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001393 # Use C locale to get ascii for the locale encoding to force
1394 # surrogate-escaping of \xFF in the child process; otherwise it can
1395 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001396 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001397 stdout = subprocess.check_output(
1398 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001399 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001400 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001401 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001402
1403 # test bytes
1404 key = key.encode("ascii", "surrogateescape")
1405 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001406 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001407 env = os.environ.copy()
1408 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001409 stdout = subprocess.check_output(
1410 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001411 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001412 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001413 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001414
Victor Stinnerb745a742010-05-18 17:17:23 +00001415 def test_bytes_program(self):
1416 abs_program = os.fsencode(sys.executable)
1417 path, program = os.path.split(sys.executable)
1418 program = os.fsencode(program)
1419
1420 # absolute bytes path
1421 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001422 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001423
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001424 # absolute bytes path as a string
1425 cmd = b"'" + abs_program + b"' -c pass"
1426 exitcode = subprocess.call(cmd, shell=True)
1427 self.assertEqual(exitcode, 0)
1428
Victor Stinnerb745a742010-05-18 17:17:23 +00001429 # bytes program, unicode PATH
1430 env = os.environ.copy()
1431 env["PATH"] = path
1432 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001433 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001434
1435 # bytes program, bytes PATH
1436 envb = os.environb.copy()
1437 envb[b"PATH"] = os.fsencode(path)
1438 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001439 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001440
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001441 def test_pipe_cloexec(self):
1442 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1443 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1444
1445 p1 = subprocess.Popen([sys.executable, sleeper],
1446 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1447 stderr=subprocess.PIPE, close_fds=False)
1448
1449 self.addCleanup(p1.communicate, b'')
1450
1451 p2 = subprocess.Popen([sys.executable, fd_status],
1452 stdout=subprocess.PIPE, close_fds=False)
1453
1454 output, error = p2.communicate()
1455 result_fds = set(map(int, output.split(b',')))
1456 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1457 p1.stderr.fileno()])
1458
1459 self.assertFalse(result_fds & unwanted_fds,
1460 "Expected no fds from %r to be open in child, "
1461 "found %r" %
1462 (unwanted_fds, result_fds & unwanted_fds))
1463
1464 def test_pipe_cloexec_real_tools(self):
1465 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1466 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1467
1468 subdata = b'zxcvbn'
1469 data = subdata * 4 + b'\n'
1470
1471 p1 = subprocess.Popen([sys.executable, qcat],
1472 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1473 close_fds=False)
1474
1475 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1476 stdin=p1.stdout, stdout=subprocess.PIPE,
1477 close_fds=False)
1478
1479 self.addCleanup(p1.wait)
1480 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001481 def kill_p1():
1482 try:
1483 p1.terminate()
1484 except ProcessLookupError:
1485 pass
1486 def kill_p2():
1487 try:
1488 p2.terminate()
1489 except ProcessLookupError:
1490 pass
1491 self.addCleanup(kill_p1)
1492 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001493
1494 p1.stdin.write(data)
1495 p1.stdin.close()
1496
1497 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1498
1499 self.assertTrue(readfiles, "The child hung")
1500 self.assertEqual(p2.stdout.read(), data)
1501
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001502 p1.stdout.close()
1503 p2.stdout.close()
1504
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001505 def test_close_fds(self):
1506 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1507
1508 fds = os.pipe()
1509 self.addCleanup(os.close, fds[0])
1510 self.addCleanup(os.close, fds[1])
1511
1512 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001513 # add a bunch more fds
1514 for _ in range(9):
1515 fd = os.open("/dev/null", os.O_RDONLY)
1516 self.addCleanup(os.close, fd)
1517 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001518
1519 p = subprocess.Popen([sys.executable, fd_status],
1520 stdout=subprocess.PIPE, close_fds=False)
1521 output, ignored = p.communicate()
1522 remaining_fds = set(map(int, output.split(b',')))
1523
1524 self.assertEqual(remaining_fds & open_fds, open_fds,
1525 "Some fds were closed")
1526
1527 p = subprocess.Popen([sys.executable, fd_status],
1528 stdout=subprocess.PIPE, close_fds=True)
1529 output, ignored = p.communicate()
1530 remaining_fds = set(map(int, output.split(b',')))
1531
1532 self.assertFalse(remaining_fds & open_fds,
1533 "Some fds were left open")
1534 self.assertIn(1, remaining_fds, "Subprocess failed")
1535
Gregory P. Smith8facece2012-01-21 14:01:08 -08001536 # Keep some of the fd's we opened open in the subprocess.
1537 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1538 fds_to_keep = set(open_fds.pop() for _ in range(8))
1539 p = subprocess.Popen([sys.executable, fd_status],
1540 stdout=subprocess.PIPE, close_fds=True,
1541 pass_fds=())
1542 output, ignored = p.communicate()
1543 remaining_fds = set(map(int, output.split(b',')))
1544
1545 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1546 "Some fds not in pass_fds were left open")
1547 self.assertIn(1, remaining_fds, "Subprocess failed")
1548
Victor Stinner88701e22011-06-01 13:13:04 +02001549 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1550 # descriptor of a pipe closed in the parent process is valid in the
1551 # child process according to fstat(), but the mode of the file
1552 # descriptor is invalid, and read or write raise an error.
1553 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001554 def test_pass_fds(self):
1555 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1556
1557 open_fds = set()
1558
1559 for x in range(5):
1560 fds = os.pipe()
1561 self.addCleanup(os.close, fds[0])
1562 self.addCleanup(os.close, fds[1])
1563 open_fds.update(fds)
1564
1565 for fd in open_fds:
1566 p = subprocess.Popen([sys.executable, fd_status],
1567 stdout=subprocess.PIPE, close_fds=True,
1568 pass_fds=(fd, ))
1569 output, ignored = p.communicate()
1570
1571 remaining_fds = set(map(int, output.split(b',')))
1572 to_be_closed = open_fds - {fd}
1573
1574 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1575 self.assertFalse(remaining_fds & to_be_closed,
1576 "fd to be closed passed")
1577
1578 # pass_fds overrides close_fds with a warning.
1579 with self.assertWarns(RuntimeWarning) as context:
1580 self.assertFalse(subprocess.call(
1581 [sys.executable, "-c", "import sys; sys.exit(0)"],
1582 close_fds=False, pass_fds=(fd, )))
1583 self.assertIn('overriding close_fds', str(context.warning))
1584
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001585 def test_stdout_stdin_are_single_inout_fd(self):
1586 with io.open(os.devnull, "r+") as inout:
1587 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1588 stdout=inout, stdin=inout)
1589 p.wait()
1590
1591 def test_stdout_stderr_are_single_inout_fd(self):
1592 with io.open(os.devnull, "r+") as inout:
1593 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1594 stdout=inout, stderr=inout)
1595 p.wait()
1596
1597 def test_stderr_stdin_are_single_inout_fd(self):
1598 with io.open(os.devnull, "r+") as inout:
1599 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1600 stderr=inout, stdin=inout)
1601 p.wait()
1602
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001603 def test_wait_when_sigchild_ignored(self):
1604 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1605 sigchild_ignore = support.findfile("sigchild_ignore.py",
1606 subdir="subprocessdata")
1607 p = subprocess.Popen([sys.executable, sigchild_ignore],
1608 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1609 stdout, stderr = p.communicate()
1610 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001611 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001612 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001613
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001614 def test_select_unbuffered(self):
1615 # Issue #11459: bufsize=0 should really set the pipes as
1616 # unbuffered (and therefore let select() work properly).
1617 select = support.import_module("select")
1618 p = subprocess.Popen([sys.executable, "-c",
1619 'import sys;'
1620 'sys.stdout.write("apple")'],
1621 stdout=subprocess.PIPE,
1622 bufsize=0)
1623 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001624 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001625 try:
1626 self.assertEqual(f.read(4), b"appl")
1627 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1628 finally:
1629 p.wait()
1630
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001631 def test_zombie_fast_process_del(self):
1632 # Issue #12650: on Unix, if Popen.__del__() was called before the
1633 # process exited, it wouldn't be added to subprocess._active, and would
1634 # remain a zombie.
1635 # spawn a Popen, and delete its reference before it exits
1636 p = subprocess.Popen([sys.executable, "-c",
1637 'import sys, time;'
1638 'time.sleep(0.2)'],
1639 stdout=subprocess.PIPE,
1640 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001641 self.addCleanup(p.stdout.close)
1642 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001643 ident = id(p)
1644 pid = p.pid
1645 del p
1646 # check that p is in the active processes list
1647 self.assertIn(ident, [id(o) for o in subprocess._active])
1648
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001649 def test_leak_fast_process_del_killed(self):
1650 # Issue #12650: on Unix, if Popen.__del__() was called before the
1651 # process exited, and the process got killed by a signal, it would never
1652 # be removed from subprocess._active, which triggered a FD and memory
1653 # leak.
1654 # spawn a Popen, delete its reference and kill it
1655 p = subprocess.Popen([sys.executable, "-c",
1656 'import time;'
1657 'time.sleep(3)'],
1658 stdout=subprocess.PIPE,
1659 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001660 self.addCleanup(p.stdout.close)
1661 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001662 ident = id(p)
1663 pid = p.pid
1664 del p
1665 os.kill(pid, signal.SIGKILL)
1666 # check that p is in the active processes list
1667 self.assertIn(ident, [id(o) for o in subprocess._active])
1668
1669 # let some time for the process to exit, and create a new Popen: this
1670 # should trigger the wait() of p
1671 time.sleep(0.2)
1672 with self.assertRaises(EnvironmentError) as c:
1673 with subprocess.Popen(['nonexisting_i_hope'],
1674 stdout=subprocess.PIPE,
1675 stderr=subprocess.PIPE) as proc:
1676 pass
1677 # p should have been wait()ed on, and removed from the _active list
1678 self.assertRaises(OSError, os.waitpid, pid, 0)
1679 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1680
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001681
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001682@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001683class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001684
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001685 def test_startupinfo(self):
1686 # startupinfo argument
1687 # We uses hardcoded constants, because we do not want to
1688 # depend on win32all.
1689 STARTF_USESHOWWINDOW = 1
1690 SW_MAXIMIZE = 3
1691 startupinfo = subprocess.STARTUPINFO()
1692 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1693 startupinfo.wShowWindow = SW_MAXIMIZE
1694 # Since Python is a console process, it won't be affected
1695 # by wShowWindow, but the argument should be silently
1696 # ignored
1697 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001698 startupinfo=startupinfo)
1699
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001700 def test_creationflags(self):
1701 # creationflags argument
1702 CREATE_NEW_CONSOLE = 16
1703 sys.stderr.write(" a DOS box should flash briefly ...\n")
1704 subprocess.call(sys.executable +
1705 ' -c "import time; time.sleep(0.25)"',
1706 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001707
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001708 def test_invalid_args(self):
1709 # invalid arguments should raise ValueError
1710 self.assertRaises(ValueError, subprocess.call,
1711 [sys.executable, "-c",
1712 "import sys; sys.exit(47)"],
1713 preexec_fn=lambda: 1)
1714 self.assertRaises(ValueError, subprocess.call,
1715 [sys.executable, "-c",
1716 "import sys; sys.exit(47)"],
1717 stdout=subprocess.PIPE,
1718 close_fds=True)
1719
1720 def test_close_fds(self):
1721 # close file descriptors
1722 rc = subprocess.call([sys.executable, "-c",
1723 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001724 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001725 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001726
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001727 def test_shell_sequence(self):
1728 # Run command through the shell (sequence)
1729 newenv = os.environ.copy()
1730 newenv["FRUIT"] = "physalis"
1731 p = subprocess.Popen(["set"], shell=1,
1732 stdout=subprocess.PIPE,
1733 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001734 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001735 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001736
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001737 def test_shell_string(self):
1738 # Run command through the shell (string)
1739 newenv = os.environ.copy()
1740 newenv["FRUIT"] = "physalis"
1741 p = subprocess.Popen("set", shell=1,
1742 stdout=subprocess.PIPE,
1743 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001744 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001745 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001746
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001747 def test_call_string(self):
1748 # call() function with string argument on Windows
1749 rc = subprocess.call(sys.executable +
1750 ' -c "import sys; sys.exit(47)"')
1751 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001752
Florent Xicluna4886d242010-03-08 13:27:26 +00001753 def _kill_process(self, method, *args):
1754 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001755 p = subprocess.Popen([sys.executable, "-c", """if 1:
1756 import sys, time
1757 sys.stdout.write('x\\n')
1758 sys.stdout.flush()
1759 time.sleep(30)
1760 """],
1761 stdin=subprocess.PIPE,
1762 stdout=subprocess.PIPE,
1763 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001764 self.addCleanup(p.stdout.close)
1765 self.addCleanup(p.stderr.close)
1766 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001767 # Wait for the interpreter to be completely initialized before
1768 # sending any signal.
1769 p.stdout.read(1)
1770 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001771 _, stderr = p.communicate()
1772 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001773 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001774 self.assertNotEqual(returncode, 0)
1775
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001776 def _kill_dead_process(self, method, *args):
1777 p = subprocess.Popen([sys.executable, "-c", """if 1:
1778 import sys, time
1779 sys.stdout.write('x\\n')
1780 sys.stdout.flush()
1781 sys.exit(42)
1782 """],
1783 stdin=subprocess.PIPE,
1784 stdout=subprocess.PIPE,
1785 stderr=subprocess.PIPE)
1786 self.addCleanup(p.stdout.close)
1787 self.addCleanup(p.stderr.close)
1788 self.addCleanup(p.stdin.close)
1789 # Wait for the interpreter to be completely initialized before
1790 # sending any signal.
1791 p.stdout.read(1)
1792 # The process should end after this
1793 time.sleep(1)
1794 # This shouldn't raise even though the child is now dead
1795 getattr(p, method)(*args)
1796 _, stderr = p.communicate()
1797 self.assertStderrEqual(stderr, b'')
1798 rc = p.wait()
1799 self.assertEqual(rc, 42)
1800
Florent Xicluna4886d242010-03-08 13:27:26 +00001801 def test_send_signal(self):
1802 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001803
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001804 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001805 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001806
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001807 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001808 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001809
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001810 def test_send_signal_dead(self):
1811 self._kill_dead_process('send_signal', signal.SIGTERM)
1812
1813 def test_kill_dead(self):
1814 self._kill_dead_process('kill')
1815
1816 def test_terminate_dead(self):
1817 self._kill_dead_process('terminate')
1818
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001819
Brett Cannona23810f2008-05-26 19:04:21 +00001820# The module says:
1821# "NB This only works (and is only relevant) for UNIX."
1822#
1823# Actually, getoutput should work on any platform with an os.popen, but
1824# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001825@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001826class CommandTests(unittest.TestCase):
1827 def test_getoutput(self):
1828 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1829 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1830 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001831
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001832 # we use mkdtemp in the next line to create an empty directory
1833 # under our exclusive control; from that, we can invent a pathname
1834 # that we _know_ won't exist. This is guaranteed to fail.
1835 dir = None
1836 try:
1837 dir = tempfile.mkdtemp()
1838 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001839
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001840 status, output = subprocess.getstatusoutput('cat ' + name)
1841 self.assertNotEqual(status, 0)
1842 finally:
1843 if dir is not None:
1844 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001845
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001846
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001847@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1848 "poll system call not supported")
1849class ProcessTestCaseNoPoll(ProcessTestCase):
1850 def setUp(self):
1851 subprocess._has_poll = False
1852 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001853
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001854 def tearDown(self):
1855 subprocess._has_poll = True
1856 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001857
1858
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001859class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001860 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001861 def test_eintr_retry_call(self):
1862 record_calls = []
1863 def fake_os_func(*args):
1864 record_calls.append(args)
1865 if len(record_calls) == 2:
1866 raise OSError(errno.EINTR, "fake interrupted system call")
1867 return tuple(reversed(args))
1868
1869 self.assertEqual((999, 256),
1870 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1871 self.assertEqual([(256, 999)], record_calls)
1872 # This time there will be an EINTR so it will loop once.
1873 self.assertEqual((666,),
1874 subprocess._eintr_retry_call(fake_os_func, 666))
1875 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1876
1877
Tim Golden126c2962010-08-11 14:20:40 +00001878@unittest.skipUnless(mswindows, "Windows-specific tests")
1879class CommandsWithSpaces (BaseTestCase):
1880
1881 def setUp(self):
1882 super().setUp()
1883 f, fname = mkstemp(".py", "te st")
1884 self.fname = fname.lower ()
1885 os.write(f, b"import sys;"
1886 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1887 )
1888 os.close(f)
1889
1890 def tearDown(self):
1891 os.remove(self.fname)
1892 super().tearDown()
1893
1894 def with_spaces(self, *args, **kwargs):
1895 kwargs['stdout'] = subprocess.PIPE
1896 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001897 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001898 self.assertEqual(
1899 p.stdout.read ().decode("mbcs"),
1900 "2 [%r, 'ab cd']" % self.fname
1901 )
1902
1903 def test_shell_string_with_spaces(self):
1904 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001905 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1906 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001907
1908 def test_shell_sequence_with_spaces(self):
1909 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001910 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001911
1912 def test_noshell_string_with_spaces(self):
1913 # call() function with string argument with spaces on Windows
1914 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1915 "ab cd"))
1916
1917 def test_noshell_sequence_with_spaces(self):
1918 # call() function with sequence argument with spaces on Windows
1919 self.with_spaces([sys.executable, self.fname, "ab cd"])
1920
Brian Curtin79cdb662010-12-03 02:46:02 +00001921
Georg Brandla86b2622012-02-20 21:34:57 +01001922class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00001923
1924 def test_pipe(self):
1925 with subprocess.Popen([sys.executable, "-c",
1926 "import sys;"
1927 "sys.stdout.write('stdout');"
1928 "sys.stderr.write('stderr');"],
1929 stdout=subprocess.PIPE,
1930 stderr=subprocess.PIPE) as proc:
1931 self.assertEqual(proc.stdout.read(), b"stdout")
1932 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1933
1934 self.assertTrue(proc.stdout.closed)
1935 self.assertTrue(proc.stderr.closed)
1936
1937 def test_returncode(self):
1938 with subprocess.Popen([sys.executable, "-c",
1939 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07001940 pass
1941 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00001942 self.assertEqual(proc.returncode, 100)
1943
1944 def test_communicate_stdin(self):
1945 with subprocess.Popen([sys.executable, "-c",
1946 "import sys;"
1947 "sys.exit(sys.stdin.read() == 'context')"],
1948 stdin=subprocess.PIPE) as proc:
1949 proc.communicate(b"context")
1950 self.assertEqual(proc.returncode, 1)
1951
1952 def test_invalid_args(self):
1953 with self.assertRaises(EnvironmentError) as c:
1954 with subprocess.Popen(['nonexisting_i_hope'],
1955 stdout=subprocess.PIPE,
1956 stderr=subprocess.PIPE) as proc:
1957 pass
1958
1959 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1960 raise c.exception
1961
1962
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001963def test_main():
1964 unit_tests = (ProcessTestCase,
1965 POSIXProcessTestCase,
1966 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001967 CommandTests,
1968 ProcessTestCaseNoPoll,
1969 HelperFunctionTests,
1970 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02001971 ContextManagerTests,
1972 )
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001973
1974 support.run_unittest(*unit_tests)
1975 support.reap_children()
1976
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001977if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001978 unittest.main()