blob: e591d2fd56cbd17bf4800f5978650c4fffa25e69 [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
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000648 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000649 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000650 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000651 max_handles = 1026 # too much for most UNIX systems
652 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000653 max_handles = 2050 # too much for (at least some) Windows setups
654 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400655 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000656 try:
657 for i in range(max_handles):
658 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400659 tmpfile = os.path.join(tmpdir, support.TESTFN)
660 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000661 except OSError as e:
662 if e.errno != errno.EMFILE:
663 raise
664 break
665 else:
666 self.skipTest("failed to reach the file descriptor limit "
667 "(tried %d)" % max_handles)
668 # Close a couple of them (should be enough for a subprocess)
669 for i in range(10):
670 os.close(handles.pop())
671 # Loop creating some subprocesses. If one of them leaks some fds,
672 # the next loop iteration will fail by reaching the max fd limit.
673 for i in range(15):
674 p = subprocess.Popen([sys.executable, "-c",
675 "import sys;"
676 "sys.stdout.write(sys.stdin.read())"],
677 stdin=subprocess.PIPE,
678 stdout=subprocess.PIPE,
679 stderr=subprocess.PIPE)
680 data = p.communicate(b"lime")[0]
681 self.assertEqual(data, b"lime")
682 finally:
683 for h in handles:
684 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400685 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000686
687 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000688 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
689 '"a b c" d e')
690 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
691 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000692 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
693 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000694 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
695 'a\\\\\\b "de fg" h')
696 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
697 'a\\\\\\"b c d')
698 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
699 '"a\\\\b c" d e')
700 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
701 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000702 self.assertEqual(subprocess.list2cmdline(['ab', '']),
703 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000704
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000705 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200706 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +0200707 "import os; os.read(0, 1)"],
708 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200709 self.addCleanup(p.stdin.close)
710 self.assertIsNone(p.poll())
711 os.write(p.stdin.fileno(), b'A')
712 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000713 # Subsequent invocations should just return the returncode
714 self.assertEqual(p.poll(), 0)
715
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000716 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200717 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000718 self.assertEqual(p.wait(), 0)
719 # Subsequent invocations should just return the returncode
720 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000721
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400722 def test_wait_timeout(self):
723 p = subprocess.Popen([sys.executable,
Reid Kleckner93479cc2011-03-14 19:32:41 -0400724 "-c", "import time; time.sleep(0.1)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -0400725 with self.assertRaises(subprocess.TimeoutExpired) as c:
726 p.wait(timeout=0.01)
727 self.assertIn("0.01", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -0400728 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
729 # time to start.
730 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400731
Peter Astrand738131d2004-11-30 21:04:45 +0000732 def test_invalid_bufsize(self):
733 # an invalid type of the bufsize argument should raise
734 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000735 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000736 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000737
Guido van Rossum46a05a72007-06-07 21:56:45 +0000738 def test_bufsize_is_none(self):
739 # bufsize=None should be the same as bufsize=0.
740 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
741 self.assertEqual(p.wait(), 0)
742 # Again with keyword arg
743 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
744 self.assertEqual(p.wait(), 0)
745
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000746 def test_leaking_fds_on_error(self):
747 # see bug #5179: Popen leaks file descriptors to PIPEs if
748 # the child fails to execute; this will eventually exhaust
749 # the maximum number of open fds. 1024 seems a very common
750 # value for that limit, but Windows has 2048, so we loop
751 # 1024 times (each call leaked two fds).
752 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000753 # Windows raises IOError. Others raise OSError.
754 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000755 subprocess.Popen(['nonexisting_i_hope'],
756 stdout=subprocess.PIPE,
757 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400758 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400759 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000760 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000761
Victor Stinnerb3693582010-05-21 20:13:12 +0000762 def test_issue8780(self):
763 # Ensure that stdout is inherited from the parent
764 # if stdout=PIPE is not used
765 code = ';'.join((
766 'import subprocess, sys',
767 'retcode = subprocess.call('
768 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
769 'assert retcode == 0'))
770 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000771 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000772
Tim Goldenaf5ac392010-08-06 13:03:56 +0000773 def test_handles_closed_on_exception(self):
774 # If CreateProcess exits with an error, ensure the
775 # duplicate output handles are released
776 ifhandle, ifname = mkstemp()
777 ofhandle, ofname = mkstemp()
778 efhandle, efname = mkstemp()
779 try:
780 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
781 stderr=efhandle)
782 except OSError:
783 os.close(ifhandle)
784 os.remove(ifname)
785 os.close(ofhandle)
786 os.remove(ofname)
787 os.close(efhandle)
788 os.remove(efname)
789 self.assertFalse(os.path.exists(ifname))
790 self.assertFalse(os.path.exists(ofname))
791 self.assertFalse(os.path.exists(efname))
792
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200793 def test_communicate_epipe(self):
794 # Issue 10963: communicate() should hide EPIPE
795 p = subprocess.Popen([sys.executable, "-c", 'pass'],
796 stdin=subprocess.PIPE,
797 stdout=subprocess.PIPE,
798 stderr=subprocess.PIPE)
799 self.addCleanup(p.stdout.close)
800 self.addCleanup(p.stderr.close)
801 self.addCleanup(p.stdin.close)
802 p.communicate(b"x" * 2**20)
803
804 def test_communicate_epipe_only_stdin(self):
805 # Issue 10963: communicate() should hide EPIPE
806 p = subprocess.Popen([sys.executable, "-c", 'pass'],
807 stdin=subprocess.PIPE)
808 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200809 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200810 p.communicate(b"x" * 2**20)
811
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200812 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
813 "Requires signal.SIGUSR1")
814 @unittest.skipUnless(hasattr(os, 'kill'),
815 "Requires os.kill")
816 @unittest.skipUnless(hasattr(os, 'getppid'),
817 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200818 def test_communicate_eintr(self):
819 # Issue #12493: communicate() should handle EINTR
820 def handler(signum, frame):
821 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200822 old_handler = signal.signal(signal.SIGUSR1, handler)
823 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200824
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200825 args = [sys.executable, "-c",
826 'import os, signal;'
827 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200828 for stream in ('stdout', 'stderr'):
829 kw = {stream: subprocess.PIPE}
830 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200831 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200832 process.communicate()
833
Tim Peterse718f612004-10-12 21:51:32 +0000834
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000835# context manager
836class _SuppressCoreFiles(object):
837 """Try to prevent core files from being created."""
838 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000839
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000840 def __enter__(self):
841 """Try to save previous ulimit, then set it to (0, 0)."""
Benjamin Peterson964561b2011-12-10 12:31:42 -0500842 if resource is not None:
843 try:
844 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
845 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
846 except (ValueError, resource.error):
847 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000848
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000849 if sys.platform == 'darwin':
850 # Check if the 'Crash Reporter' on OSX was configured
851 # in 'Developer' mode and warn that it will get triggered
852 # when it is.
853 #
854 # This assumes that this context manager is used in tests
855 # that might trigger the next manager.
856 value = subprocess.Popen(['/usr/bin/defaults', 'read',
857 'com.apple.CrashReporter', 'DialogType'],
858 stdout=subprocess.PIPE).communicate()[0]
859 if value.strip() == b'developer':
860 print("this tests triggers the Crash Reporter, "
861 "that is intentional", end='')
862 sys.stdout.flush()
863
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000864 def __exit__(self, *args):
865 """Return core file behavior to default."""
866 if self.old_limit is None:
867 return
Benjamin Peterson964561b2011-12-10 12:31:42 -0500868 if resource is not None:
869 try:
870 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
871 except (ValueError, resource.error):
872 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000873
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000874
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000875@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000876class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000877
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000878 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000879 nonexistent_dir = "/_this/pa.th/does/not/exist"
880 try:
881 os.chdir(nonexistent_dir)
882 except OSError as e:
883 # This avoids hard coding the errno value or the OS perror()
884 # string and instead capture the exception that we want to see
885 # below for comparison.
886 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000887 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000888 else:
889 self.fail("chdir to nonexistant directory %s succeeded." %
890 nonexistent_dir)
891
892 # Error in the child re-raised in the parent.
893 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000894 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000895 cwd=nonexistent_dir)
896 except OSError as e:
897 # Test that the child process chdir failure actually makes
898 # it up to the parent process as the correct exception.
899 self.assertEqual(desired_exception.errno, e.errno)
900 self.assertEqual(desired_exception.strerror, e.strerror)
901 else:
902 self.fail("Expected OSError: %s" % desired_exception)
903
904 def test_restore_signals(self):
905 # Code coverage for both values of restore_signals to make sure it
906 # at least does not blow up.
907 # A test for behavior would be complex. Contributions welcome.
908 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
909 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
910
911 def test_start_new_session(self):
912 # For code coverage of calling setsid(). We don't care if we get an
913 # EPERM error from it depending on the test execution environment, that
914 # still indicates that it was called.
915 try:
916 output = subprocess.check_output(
917 [sys.executable, "-c",
918 "import os; print(os.getpgid(os.getpid()))"],
919 start_new_session=True)
920 except OSError as e:
921 if e.errno != errno.EPERM:
922 raise
923 else:
924 parent_pgid = os.getpgid(os.getpid())
925 child_pgid = int(output)
926 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000927
928 def test_run_abort(self):
929 # returncode handles signal termination
930 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000931 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000932 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000933 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000934 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000935
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000936 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000937 # DISCLAIMER: Setting environment variables is *not* a good use
938 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000939 p = subprocess.Popen([sys.executable, "-c",
940 'import sys,os;'
941 'sys.stdout.write(os.getenv("FRUIT"))'],
942 stdout=subprocess.PIPE,
943 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000944 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000945 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000946
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000947 def test_preexec_exception(self):
948 def raise_it():
949 raise ValueError("What if two swallows carried a coconut?")
950 try:
951 p = subprocess.Popen([sys.executable, "-c", ""],
952 preexec_fn=raise_it)
953 except RuntimeError as e:
954 self.assertTrue(
955 subprocess._posixsubprocess,
956 "Expected a ValueError from the preexec_fn")
957 except ValueError as e:
958 self.assertIn("coconut", e.args[0])
959 else:
960 self.fail("Exception raised by preexec_fn did not make it "
961 "to the parent process.")
962
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000963 def test_preexec_gc_module_failure(self):
964 # This tests the code that disables garbage collection if the child
965 # process will execute any Python.
966 def raise_runtime_error():
967 raise RuntimeError("this shouldn't escape")
968 enabled = gc.isenabled()
969 orig_gc_disable = gc.disable
970 orig_gc_isenabled = gc.isenabled
971 try:
972 gc.disable()
973 self.assertFalse(gc.isenabled())
974 subprocess.call([sys.executable, '-c', ''],
975 preexec_fn=lambda: None)
976 self.assertFalse(gc.isenabled(),
977 "Popen enabled gc when it shouldn't.")
978
979 gc.enable()
980 self.assertTrue(gc.isenabled())
981 subprocess.call([sys.executable, '-c', ''],
982 preexec_fn=lambda: None)
983 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
984
985 gc.disable = raise_runtime_error
986 self.assertRaises(RuntimeError, subprocess.Popen,
987 [sys.executable, '-c', ''],
988 preexec_fn=lambda: None)
989
990 del gc.isenabled # force an AttributeError
991 self.assertRaises(AttributeError, subprocess.Popen,
992 [sys.executable, '-c', ''],
993 preexec_fn=lambda: None)
994 finally:
995 gc.disable = orig_gc_disable
996 gc.isenabled = orig_gc_isenabled
997 if not enabled:
998 gc.disable()
999
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001000 def test_args_string(self):
1001 # args is a string
1002 fd, fname = mkstemp()
1003 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001004 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001005 fobj.write("#!/bin/sh\n")
1006 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1007 sys.executable)
1008 os.chmod(fname, 0o700)
1009 p = subprocess.Popen(fname)
1010 p.wait()
1011 os.remove(fname)
1012 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001013
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001014 def test_invalid_args(self):
1015 # invalid arguments should raise ValueError
1016 self.assertRaises(ValueError, subprocess.call,
1017 [sys.executable, "-c",
1018 "import sys; sys.exit(47)"],
1019 startupinfo=47)
1020 self.assertRaises(ValueError, subprocess.call,
1021 [sys.executable, "-c",
1022 "import sys; sys.exit(47)"],
1023 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001024
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001025 def test_shell_sequence(self):
1026 # Run command through the shell (sequence)
1027 newenv = os.environ.copy()
1028 newenv["FRUIT"] = "apple"
1029 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1030 stdout=subprocess.PIPE,
1031 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001032 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001033 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001034
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001035 def test_shell_string(self):
1036 # Run command through the shell (string)
1037 newenv = os.environ.copy()
1038 newenv["FRUIT"] = "apple"
1039 p = subprocess.Popen("echo $FRUIT", shell=1,
1040 stdout=subprocess.PIPE,
1041 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001042 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001043 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001044
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001045 def test_call_string(self):
1046 # call() function with string argument on UNIX
1047 fd, fname = mkstemp()
1048 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001049 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001050 fobj.write("#!/bin/sh\n")
1051 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1052 sys.executable)
1053 os.chmod(fname, 0o700)
1054 rc = subprocess.call(fname)
1055 os.remove(fname)
1056 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001057
Stefan Krah9542cc62010-07-19 14:20:53 +00001058 def test_specific_shell(self):
1059 # Issue #9265: Incorrect name passed as arg[0].
1060 shells = []
1061 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1062 for name in ['bash', 'ksh']:
1063 sh = os.path.join(prefix, name)
1064 if os.path.isfile(sh):
1065 shells.append(sh)
1066 if not shells: # Will probably work for any shell but csh.
1067 self.skipTest("bash or ksh required for this test")
1068 sh = '/bin/sh'
1069 if os.path.isfile(sh) and not os.path.islink(sh):
1070 # Test will fail if /bin/sh is a symlink to csh.
1071 shells.append(sh)
1072 for sh in shells:
1073 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1074 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001075 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001076 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1077
Florent Xicluna4886d242010-03-08 13:27:26 +00001078 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001079 # Do not inherit file handles from the parent.
1080 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001081 p = subprocess.Popen([sys.executable, "-c", """if 1:
1082 import sys, time
1083 sys.stdout.write('x\\n')
1084 sys.stdout.flush()
1085 time.sleep(30)
1086 """],
1087 close_fds=True,
1088 stdin=subprocess.PIPE,
1089 stdout=subprocess.PIPE,
1090 stderr=subprocess.PIPE)
1091 # Wait for the interpreter to be completely initialized before
1092 # sending any signal.
1093 p.stdout.read(1)
1094 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001095 return p
1096
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001097 def _kill_dead_process(self, method, *args):
1098 # Do not inherit file handles from the parent.
1099 # It should fix failures on some platforms.
1100 p = subprocess.Popen([sys.executable, "-c", """if 1:
1101 import sys, time
1102 sys.stdout.write('x\\n')
1103 sys.stdout.flush()
1104 """],
1105 close_fds=True,
1106 stdin=subprocess.PIPE,
1107 stdout=subprocess.PIPE,
1108 stderr=subprocess.PIPE)
1109 # Wait for the interpreter to be completely initialized before
1110 # sending any signal.
1111 p.stdout.read(1)
1112 # The process should end after this
1113 time.sleep(1)
1114 # This shouldn't raise even though the child is now dead
1115 getattr(p, method)(*args)
1116 p.communicate()
1117
Florent Xicluna4886d242010-03-08 13:27:26 +00001118 def test_send_signal(self):
1119 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001120 _, stderr = p.communicate()
1121 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001122 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001123
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001124 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001125 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001126 _, stderr = p.communicate()
1127 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001128 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001129
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001130 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001131 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001132 _, stderr = p.communicate()
1133 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001134 self.assertEqual(p.wait(), -signal.SIGTERM)
1135
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001136 def test_send_signal_dead(self):
1137 # Sending a signal to a dead process
1138 self._kill_dead_process('send_signal', signal.SIGINT)
1139
1140 def test_kill_dead(self):
1141 # Killing a dead process
1142 self._kill_dead_process('kill')
1143
1144 def test_terminate_dead(self):
1145 # Terminating a dead process
1146 self._kill_dead_process('terminate')
1147
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001148 def check_close_std_fds(self, fds):
1149 # Issue #9905: test that subprocess pipes still work properly with
1150 # some standard fds closed
1151 stdin = 0
1152 newfds = []
1153 for a in fds:
1154 b = os.dup(a)
1155 newfds.append(b)
1156 if a == 0:
1157 stdin = b
1158 try:
1159 for fd in fds:
1160 os.close(fd)
1161 out, err = subprocess.Popen([sys.executable, "-c",
1162 'import sys;'
1163 'sys.stdout.write("apple");'
1164 'sys.stdout.flush();'
1165 'sys.stderr.write("orange")'],
1166 stdin=stdin,
1167 stdout=subprocess.PIPE,
1168 stderr=subprocess.PIPE).communicate()
1169 err = support.strip_python_stderr(err)
1170 self.assertEqual((out, err), (b'apple', b'orange'))
1171 finally:
1172 for b, a in zip(newfds, fds):
1173 os.dup2(b, a)
1174 for b in newfds:
1175 os.close(b)
1176
1177 def test_close_fd_0(self):
1178 self.check_close_std_fds([0])
1179
1180 def test_close_fd_1(self):
1181 self.check_close_std_fds([1])
1182
1183 def test_close_fd_2(self):
1184 self.check_close_std_fds([2])
1185
1186 def test_close_fds_0_1(self):
1187 self.check_close_std_fds([0, 1])
1188
1189 def test_close_fds_0_2(self):
1190 self.check_close_std_fds([0, 2])
1191
1192 def test_close_fds_1_2(self):
1193 self.check_close_std_fds([1, 2])
1194
1195 def test_close_fds_0_1_2(self):
1196 # Issue #10806: test that subprocess pipes still work properly with
1197 # all standard fds closed.
1198 self.check_close_std_fds([0, 1, 2])
1199
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001200 def test_remapping_std_fds(self):
1201 # open up some temporary files
1202 temps = [mkstemp() for i in range(3)]
1203 try:
1204 temp_fds = [fd for fd, fname in temps]
1205
1206 # unlink the files -- we won't need to reopen them
1207 for fd, fname in temps:
1208 os.unlink(fname)
1209
1210 # write some data to what will become stdin, and rewind
1211 os.write(temp_fds[1], b"STDIN")
1212 os.lseek(temp_fds[1], 0, 0)
1213
1214 # move the standard file descriptors out of the way
1215 saved_fds = [os.dup(fd) for fd in range(3)]
1216 try:
1217 # duplicate the file objects over the standard fd's
1218 for fd, temp_fd in enumerate(temp_fds):
1219 os.dup2(temp_fd, fd)
1220
1221 # now use those files in the "wrong" order, so that subprocess
1222 # has to rearrange them in the child
1223 p = subprocess.Popen([sys.executable, "-c",
1224 'import sys; got = sys.stdin.read();'
1225 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1226 stdin=temp_fds[1],
1227 stdout=temp_fds[2],
1228 stderr=temp_fds[0])
1229 p.wait()
1230 finally:
1231 # restore the original fd's underneath sys.stdin, etc.
1232 for std, saved in enumerate(saved_fds):
1233 os.dup2(saved, std)
1234 os.close(saved)
1235
1236 for fd in temp_fds:
1237 os.lseek(fd, 0, 0)
1238
1239 out = os.read(temp_fds[2], 1024)
1240 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1241 self.assertEqual(out, b"got STDIN")
1242 self.assertEqual(err, b"err")
1243
1244 finally:
1245 for fd in temp_fds:
1246 os.close(fd)
1247
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001248 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1249 # open up some temporary files
1250 temps = [mkstemp() for i in range(3)]
1251 temp_fds = [fd for fd, fname in temps]
1252 try:
1253 # unlink the files -- we won't need to reopen them
1254 for fd, fname in temps:
1255 os.unlink(fname)
1256
1257 # save a copy of the standard file descriptors
1258 saved_fds = [os.dup(fd) for fd in range(3)]
1259 try:
1260 # duplicate the temp files over the standard fd's 0, 1, 2
1261 for fd, temp_fd in enumerate(temp_fds):
1262 os.dup2(temp_fd, fd)
1263
1264 # write some data to what will become stdin, and rewind
1265 os.write(stdin_no, b"STDIN")
1266 os.lseek(stdin_no, 0, 0)
1267
1268 # now use those files in the given order, so that subprocess
1269 # has to rearrange them in the child
1270 p = subprocess.Popen([sys.executable, "-c",
1271 'import sys; got = sys.stdin.read();'
1272 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1273 stdin=stdin_no,
1274 stdout=stdout_no,
1275 stderr=stderr_no)
1276 p.wait()
1277
1278 for fd in temp_fds:
1279 os.lseek(fd, 0, 0)
1280
1281 out = os.read(stdout_no, 1024)
1282 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1283 finally:
1284 for std, saved in enumerate(saved_fds):
1285 os.dup2(saved, std)
1286 os.close(saved)
1287
1288 self.assertEqual(out, b"got STDIN")
1289 self.assertEqual(err, b"err")
1290
1291 finally:
1292 for fd in temp_fds:
1293 os.close(fd)
1294
1295 # When duping fds, if there arises a situation where one of the fds is
1296 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1297 # This tests all combinations of this.
1298 def test_swap_fds(self):
1299 self.check_swap_fds(0, 1, 2)
1300 self.check_swap_fds(0, 2, 1)
1301 self.check_swap_fds(1, 0, 2)
1302 self.check_swap_fds(1, 2, 0)
1303 self.check_swap_fds(2, 0, 1)
1304 self.check_swap_fds(2, 1, 0)
1305
Victor Stinner13bb71c2010-04-23 21:41:56 +00001306 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001307 def prepare():
1308 raise ValueError("surrogate:\uDCff")
1309
1310 try:
1311 subprocess.call(
1312 [sys.executable, "-c", "pass"],
1313 preexec_fn=prepare)
1314 except ValueError as err:
1315 # Pure Python implementations keeps the message
1316 self.assertIsNone(subprocess._posixsubprocess)
1317 self.assertEqual(str(err), "surrogate:\uDCff")
1318 except RuntimeError as err:
1319 # _posixsubprocess uses a default message
1320 self.assertIsNotNone(subprocess._posixsubprocess)
1321 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1322 else:
1323 self.fail("Expected ValueError or RuntimeError")
1324
Victor Stinner13bb71c2010-04-23 21:41:56 +00001325 def test_undecodable_env(self):
1326 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001327 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001328 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001329 env = os.environ.copy()
1330 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001331 # Use C locale to get ascii for the locale encoding to force
1332 # surrogate-escaping of \xFF in the child process; otherwise it can
1333 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001334 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001335 stdout = subprocess.check_output(
1336 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001337 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001338 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001339 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001340
1341 # test bytes
1342 key = key.encode("ascii", "surrogateescape")
1343 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001344 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001345 env = os.environ.copy()
1346 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001347 stdout = subprocess.check_output(
1348 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001349 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001350 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001351 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001352
Victor Stinnerb745a742010-05-18 17:17:23 +00001353 def test_bytes_program(self):
1354 abs_program = os.fsencode(sys.executable)
1355 path, program = os.path.split(sys.executable)
1356 program = os.fsencode(program)
1357
1358 # absolute bytes path
1359 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001360 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001361
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001362 # absolute bytes path as a string
1363 cmd = b"'" + abs_program + b"' -c pass"
1364 exitcode = subprocess.call(cmd, shell=True)
1365 self.assertEqual(exitcode, 0)
1366
Victor Stinnerb745a742010-05-18 17:17:23 +00001367 # bytes program, unicode PATH
1368 env = os.environ.copy()
1369 env["PATH"] = path
1370 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001371 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001372
1373 # bytes program, bytes PATH
1374 envb = os.environb.copy()
1375 envb[b"PATH"] = os.fsencode(path)
1376 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001377 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001378
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001379 def test_pipe_cloexec(self):
1380 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1381 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1382
1383 p1 = subprocess.Popen([sys.executable, sleeper],
1384 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1385 stderr=subprocess.PIPE, close_fds=False)
1386
1387 self.addCleanup(p1.communicate, b'')
1388
1389 p2 = subprocess.Popen([sys.executable, fd_status],
1390 stdout=subprocess.PIPE, close_fds=False)
1391
1392 output, error = p2.communicate()
1393 result_fds = set(map(int, output.split(b',')))
1394 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1395 p1.stderr.fileno()])
1396
1397 self.assertFalse(result_fds & unwanted_fds,
1398 "Expected no fds from %r to be open in child, "
1399 "found %r" %
1400 (unwanted_fds, result_fds & unwanted_fds))
1401
1402 def test_pipe_cloexec_real_tools(self):
1403 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1404 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1405
1406 subdata = b'zxcvbn'
1407 data = subdata * 4 + b'\n'
1408
1409 p1 = subprocess.Popen([sys.executable, qcat],
1410 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1411 close_fds=False)
1412
1413 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1414 stdin=p1.stdout, stdout=subprocess.PIPE,
1415 close_fds=False)
1416
1417 self.addCleanup(p1.wait)
1418 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001419 def kill_p1():
1420 try:
1421 p1.terminate()
1422 except ProcessLookupError:
1423 pass
1424 def kill_p2():
1425 try:
1426 p2.terminate()
1427 except ProcessLookupError:
1428 pass
1429 self.addCleanup(kill_p1)
1430 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001431
1432 p1.stdin.write(data)
1433 p1.stdin.close()
1434
1435 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1436
1437 self.assertTrue(readfiles, "The child hung")
1438 self.assertEqual(p2.stdout.read(), data)
1439
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001440 p1.stdout.close()
1441 p2.stdout.close()
1442
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001443 def test_close_fds(self):
1444 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1445
1446 fds = os.pipe()
1447 self.addCleanup(os.close, fds[0])
1448 self.addCleanup(os.close, fds[1])
1449
1450 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001451 # add a bunch more fds
1452 for _ in range(9):
1453 fd = os.open("/dev/null", os.O_RDONLY)
1454 self.addCleanup(os.close, fd)
1455 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001456
1457 p = subprocess.Popen([sys.executable, fd_status],
1458 stdout=subprocess.PIPE, close_fds=False)
1459 output, ignored = p.communicate()
1460 remaining_fds = set(map(int, output.split(b',')))
1461
1462 self.assertEqual(remaining_fds & open_fds, open_fds,
1463 "Some fds were closed")
1464
1465 p = subprocess.Popen([sys.executable, fd_status],
1466 stdout=subprocess.PIPE, close_fds=True)
1467 output, ignored = p.communicate()
1468 remaining_fds = set(map(int, output.split(b',')))
1469
1470 self.assertFalse(remaining_fds & open_fds,
1471 "Some fds were left open")
1472 self.assertIn(1, remaining_fds, "Subprocess failed")
1473
Gregory P. Smith8facece2012-01-21 14:01:08 -08001474 # Keep some of the fd's we opened open in the subprocess.
1475 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1476 fds_to_keep = set(open_fds.pop() for _ in range(8))
1477 p = subprocess.Popen([sys.executable, fd_status],
1478 stdout=subprocess.PIPE, close_fds=True,
1479 pass_fds=())
1480 output, ignored = p.communicate()
1481 remaining_fds = set(map(int, output.split(b',')))
1482
1483 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1484 "Some fds not in pass_fds were left open")
1485 self.assertIn(1, remaining_fds, "Subprocess failed")
1486
Victor Stinner88701e22011-06-01 13:13:04 +02001487 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1488 # descriptor of a pipe closed in the parent process is valid in the
1489 # child process according to fstat(), but the mode of the file
1490 # descriptor is invalid, and read or write raise an error.
1491 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001492 def test_pass_fds(self):
1493 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1494
1495 open_fds = set()
1496
1497 for x in range(5):
1498 fds = os.pipe()
1499 self.addCleanup(os.close, fds[0])
1500 self.addCleanup(os.close, fds[1])
1501 open_fds.update(fds)
1502
1503 for fd in open_fds:
1504 p = subprocess.Popen([sys.executable, fd_status],
1505 stdout=subprocess.PIPE, close_fds=True,
1506 pass_fds=(fd, ))
1507 output, ignored = p.communicate()
1508
1509 remaining_fds = set(map(int, output.split(b',')))
1510 to_be_closed = open_fds - {fd}
1511
1512 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1513 self.assertFalse(remaining_fds & to_be_closed,
1514 "fd to be closed passed")
1515
1516 # pass_fds overrides close_fds with a warning.
1517 with self.assertWarns(RuntimeWarning) as context:
1518 self.assertFalse(subprocess.call(
1519 [sys.executable, "-c", "import sys; sys.exit(0)"],
1520 close_fds=False, pass_fds=(fd, )))
1521 self.assertIn('overriding close_fds', str(context.warning))
1522
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001523 def test_stdout_stdin_are_single_inout_fd(self):
1524 with io.open(os.devnull, "r+") as inout:
1525 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1526 stdout=inout, stdin=inout)
1527 p.wait()
1528
1529 def test_stdout_stderr_are_single_inout_fd(self):
1530 with io.open(os.devnull, "r+") as inout:
1531 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1532 stdout=inout, stderr=inout)
1533 p.wait()
1534
1535 def test_stderr_stdin_are_single_inout_fd(self):
1536 with io.open(os.devnull, "r+") as inout:
1537 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1538 stderr=inout, stdin=inout)
1539 p.wait()
1540
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001541 def test_wait_when_sigchild_ignored(self):
1542 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1543 sigchild_ignore = support.findfile("sigchild_ignore.py",
1544 subdir="subprocessdata")
1545 p = subprocess.Popen([sys.executable, sigchild_ignore],
1546 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1547 stdout, stderr = p.communicate()
1548 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001549 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001550 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001551
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001552 def test_select_unbuffered(self):
1553 # Issue #11459: bufsize=0 should really set the pipes as
1554 # unbuffered (and therefore let select() work properly).
1555 select = support.import_module("select")
1556 p = subprocess.Popen([sys.executable, "-c",
1557 'import sys;'
1558 'sys.stdout.write("apple")'],
1559 stdout=subprocess.PIPE,
1560 bufsize=0)
1561 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001562 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001563 try:
1564 self.assertEqual(f.read(4), b"appl")
1565 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1566 finally:
1567 p.wait()
1568
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001569 def test_zombie_fast_process_del(self):
1570 # Issue #12650: on Unix, if Popen.__del__() was called before the
1571 # process exited, it wouldn't be added to subprocess._active, and would
1572 # remain a zombie.
1573 # spawn a Popen, and delete its reference before it exits
1574 p = subprocess.Popen([sys.executable, "-c",
1575 'import sys, time;'
1576 'time.sleep(0.2)'],
1577 stdout=subprocess.PIPE,
1578 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001579 self.addCleanup(p.stdout.close)
1580 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001581 ident = id(p)
1582 pid = p.pid
1583 del p
1584 # check that p is in the active processes list
1585 self.assertIn(ident, [id(o) for o in subprocess._active])
1586
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001587 def test_leak_fast_process_del_killed(self):
1588 # Issue #12650: on Unix, if Popen.__del__() was called before the
1589 # process exited, and the process got killed by a signal, it would never
1590 # be removed from subprocess._active, which triggered a FD and memory
1591 # leak.
1592 # spawn a Popen, delete its reference and kill it
1593 p = subprocess.Popen([sys.executable, "-c",
1594 'import time;'
1595 'time.sleep(3)'],
1596 stdout=subprocess.PIPE,
1597 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001598 self.addCleanup(p.stdout.close)
1599 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001600 ident = id(p)
1601 pid = p.pid
1602 del p
1603 os.kill(pid, signal.SIGKILL)
1604 # check that p is in the active processes list
1605 self.assertIn(ident, [id(o) for o in subprocess._active])
1606
1607 # let some time for the process to exit, and create a new Popen: this
1608 # should trigger the wait() of p
1609 time.sleep(0.2)
1610 with self.assertRaises(EnvironmentError) as c:
1611 with subprocess.Popen(['nonexisting_i_hope'],
1612 stdout=subprocess.PIPE,
1613 stderr=subprocess.PIPE) as proc:
1614 pass
1615 # p should have been wait()ed on, and removed from the _active list
1616 self.assertRaises(OSError, os.waitpid, pid, 0)
1617 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1618
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001619
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001620@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001621class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001622
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001623 def test_startupinfo(self):
1624 # startupinfo argument
1625 # We uses hardcoded constants, because we do not want to
1626 # depend on win32all.
1627 STARTF_USESHOWWINDOW = 1
1628 SW_MAXIMIZE = 3
1629 startupinfo = subprocess.STARTUPINFO()
1630 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1631 startupinfo.wShowWindow = SW_MAXIMIZE
1632 # Since Python is a console process, it won't be affected
1633 # by wShowWindow, but the argument should be silently
1634 # ignored
1635 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001636 startupinfo=startupinfo)
1637
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001638 def test_creationflags(self):
1639 # creationflags argument
1640 CREATE_NEW_CONSOLE = 16
1641 sys.stderr.write(" a DOS box should flash briefly ...\n")
1642 subprocess.call(sys.executable +
1643 ' -c "import time; time.sleep(0.25)"',
1644 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001645
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001646 def test_invalid_args(self):
1647 # invalid arguments should raise ValueError
1648 self.assertRaises(ValueError, subprocess.call,
1649 [sys.executable, "-c",
1650 "import sys; sys.exit(47)"],
1651 preexec_fn=lambda: 1)
1652 self.assertRaises(ValueError, subprocess.call,
1653 [sys.executable, "-c",
1654 "import sys; sys.exit(47)"],
1655 stdout=subprocess.PIPE,
1656 close_fds=True)
1657
1658 def test_close_fds(self):
1659 # close file descriptors
1660 rc = subprocess.call([sys.executable, "-c",
1661 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001662 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001663 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001664
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001665 def test_shell_sequence(self):
1666 # Run command through the shell (sequence)
1667 newenv = os.environ.copy()
1668 newenv["FRUIT"] = "physalis"
1669 p = subprocess.Popen(["set"], shell=1,
1670 stdout=subprocess.PIPE,
1671 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001672 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001673 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001674
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001675 def test_shell_string(self):
1676 # Run command through the shell (string)
1677 newenv = os.environ.copy()
1678 newenv["FRUIT"] = "physalis"
1679 p = subprocess.Popen("set", shell=1,
1680 stdout=subprocess.PIPE,
1681 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001682 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001683 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001684
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001685 def test_call_string(self):
1686 # call() function with string argument on Windows
1687 rc = subprocess.call(sys.executable +
1688 ' -c "import sys; sys.exit(47)"')
1689 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001690
Florent Xicluna4886d242010-03-08 13:27:26 +00001691 def _kill_process(self, method, *args):
1692 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001693 p = subprocess.Popen([sys.executable, "-c", """if 1:
1694 import sys, time
1695 sys.stdout.write('x\\n')
1696 sys.stdout.flush()
1697 time.sleep(30)
1698 """],
1699 stdin=subprocess.PIPE,
1700 stdout=subprocess.PIPE,
1701 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001702 self.addCleanup(p.stdout.close)
1703 self.addCleanup(p.stderr.close)
1704 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001705 # Wait for the interpreter to be completely initialized before
1706 # sending any signal.
1707 p.stdout.read(1)
1708 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001709 _, stderr = p.communicate()
1710 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001711 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001712 self.assertNotEqual(returncode, 0)
1713
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001714 def _kill_dead_process(self, method, *args):
1715 p = subprocess.Popen([sys.executable, "-c", """if 1:
1716 import sys, time
1717 sys.stdout.write('x\\n')
1718 sys.stdout.flush()
1719 sys.exit(42)
1720 """],
1721 stdin=subprocess.PIPE,
1722 stdout=subprocess.PIPE,
1723 stderr=subprocess.PIPE)
1724 self.addCleanup(p.stdout.close)
1725 self.addCleanup(p.stderr.close)
1726 self.addCleanup(p.stdin.close)
1727 # Wait for the interpreter to be completely initialized before
1728 # sending any signal.
1729 p.stdout.read(1)
1730 # The process should end after this
1731 time.sleep(1)
1732 # This shouldn't raise even though the child is now dead
1733 getattr(p, method)(*args)
1734 _, stderr = p.communicate()
1735 self.assertStderrEqual(stderr, b'')
1736 rc = p.wait()
1737 self.assertEqual(rc, 42)
1738
Florent Xicluna4886d242010-03-08 13:27:26 +00001739 def test_send_signal(self):
1740 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001741
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001742 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001743 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001744
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001745 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001746 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001747
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001748 def test_send_signal_dead(self):
1749 self._kill_dead_process('send_signal', signal.SIGTERM)
1750
1751 def test_kill_dead(self):
1752 self._kill_dead_process('kill')
1753
1754 def test_terminate_dead(self):
1755 self._kill_dead_process('terminate')
1756
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001757
Brett Cannona23810f2008-05-26 19:04:21 +00001758# The module says:
1759# "NB This only works (and is only relevant) for UNIX."
1760#
1761# Actually, getoutput should work on any platform with an os.popen, but
1762# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001763@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001764class CommandTests(unittest.TestCase):
1765 def test_getoutput(self):
1766 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1767 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1768 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001769
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001770 # we use mkdtemp in the next line to create an empty directory
1771 # under our exclusive control; from that, we can invent a pathname
1772 # that we _know_ won't exist. This is guaranteed to fail.
1773 dir = None
1774 try:
1775 dir = tempfile.mkdtemp()
1776 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001777
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001778 status, output = subprocess.getstatusoutput('cat ' + name)
1779 self.assertNotEqual(status, 0)
1780 finally:
1781 if dir is not None:
1782 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001783
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001784
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001785@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1786 "poll system call not supported")
1787class ProcessTestCaseNoPoll(ProcessTestCase):
1788 def setUp(self):
1789 subprocess._has_poll = False
1790 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001791
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001792 def tearDown(self):
1793 subprocess._has_poll = True
1794 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001795
1796
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001797class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001798 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001799 def test_eintr_retry_call(self):
1800 record_calls = []
1801 def fake_os_func(*args):
1802 record_calls.append(args)
1803 if len(record_calls) == 2:
1804 raise OSError(errno.EINTR, "fake interrupted system call")
1805 return tuple(reversed(args))
1806
1807 self.assertEqual((999, 256),
1808 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1809 self.assertEqual([(256, 999)], record_calls)
1810 # This time there will be an EINTR so it will loop once.
1811 self.assertEqual((666,),
1812 subprocess._eintr_retry_call(fake_os_func, 666))
1813 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1814
1815
Tim Golden126c2962010-08-11 14:20:40 +00001816@unittest.skipUnless(mswindows, "Windows-specific tests")
1817class CommandsWithSpaces (BaseTestCase):
1818
1819 def setUp(self):
1820 super().setUp()
1821 f, fname = mkstemp(".py", "te st")
1822 self.fname = fname.lower ()
1823 os.write(f, b"import sys;"
1824 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1825 )
1826 os.close(f)
1827
1828 def tearDown(self):
1829 os.remove(self.fname)
1830 super().tearDown()
1831
1832 def with_spaces(self, *args, **kwargs):
1833 kwargs['stdout'] = subprocess.PIPE
1834 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001835 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001836 self.assertEqual(
1837 p.stdout.read ().decode("mbcs"),
1838 "2 [%r, 'ab cd']" % self.fname
1839 )
1840
1841 def test_shell_string_with_spaces(self):
1842 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001843 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1844 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001845
1846 def test_shell_sequence_with_spaces(self):
1847 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001848 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001849
1850 def test_noshell_string_with_spaces(self):
1851 # call() function with string argument with spaces on Windows
1852 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1853 "ab cd"))
1854
1855 def test_noshell_sequence_with_spaces(self):
1856 # call() function with sequence argument with spaces on Windows
1857 self.with_spaces([sys.executable, self.fname, "ab cd"])
1858
Brian Curtin79cdb662010-12-03 02:46:02 +00001859
Georg Brandla86b2622012-02-20 21:34:57 +01001860class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00001861
1862 def test_pipe(self):
1863 with subprocess.Popen([sys.executable, "-c",
1864 "import sys;"
1865 "sys.stdout.write('stdout');"
1866 "sys.stderr.write('stderr');"],
1867 stdout=subprocess.PIPE,
1868 stderr=subprocess.PIPE) as proc:
1869 self.assertEqual(proc.stdout.read(), b"stdout")
1870 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1871
1872 self.assertTrue(proc.stdout.closed)
1873 self.assertTrue(proc.stderr.closed)
1874
1875 def test_returncode(self):
1876 with subprocess.Popen([sys.executable, "-c",
1877 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07001878 pass
1879 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00001880 self.assertEqual(proc.returncode, 100)
1881
1882 def test_communicate_stdin(self):
1883 with subprocess.Popen([sys.executable, "-c",
1884 "import sys;"
1885 "sys.exit(sys.stdin.read() == 'context')"],
1886 stdin=subprocess.PIPE) as proc:
1887 proc.communicate(b"context")
1888 self.assertEqual(proc.returncode, 1)
1889
1890 def test_invalid_args(self):
1891 with self.assertRaises(EnvironmentError) as c:
1892 with subprocess.Popen(['nonexisting_i_hope'],
1893 stdout=subprocess.PIPE,
1894 stderr=subprocess.PIPE) as proc:
1895 pass
1896
1897 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1898 raise c.exception
1899
1900
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001901def test_main():
1902 unit_tests = (ProcessTestCase,
1903 POSIXProcessTestCase,
1904 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001905 CommandTests,
1906 ProcessTestCaseNoPoll,
1907 HelperFunctionTests,
1908 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02001909 ContextManagerTests,
1910 )
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001911
1912 support.run_unittest(*unit_tests)
1913 support.reap_children()
1914
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001915if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001916 unittest.main()