blob: c21d15b01112410a70701e56e196835b5d120a72 [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 Pitrouab85ff32011-07-23 22:03:45 +0200566 'sys.stdout.write(sys.stdin.readline());'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000567 'sys.stdout.flush();'
568 'sys.stdout.write("line2\\n");'
569 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200570 'sys.stdout.write(sys.stdin.read());'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000571 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200572 'sys.stdout.write("line4\\n");'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000573 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200574 'sys.stdout.write("line5\\r\\n");'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000575 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200576 'sys.stdout.write("line6\\r");'
577 'sys.stdout.flush();'
578 'sys.stdout.write("\\nline7");'
579 'sys.stdout.flush();'
580 'sys.stdout.write("\\nline8");'],
581 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000582 stdout=subprocess.PIPE,
583 universal_newlines=1)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200584 p.stdin.write("line1\n")
585 self.assertEqual(p.stdout.readline(), "line1\n")
586 p.stdin.write("line3\n")
587 p.stdin.close()
Brian Curtin3c6a9512010-11-05 03:58:52 +0000588 self.addCleanup(p.stdout.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200589 self.assertEqual(p.stdout.readline(),
590 "line2\n")
591 self.assertEqual(p.stdout.read(6),
592 "line3\n")
593 self.assertEqual(p.stdout.read(),
594 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000595
596 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000597 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000598 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000599 'import sys,os;' + SETBINARY +
Guido van Rossum98297ee2007-11-06 21:34:58 +0000600 'sys.stdout.write("line2\\n");'
601 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200602 'sys.stdout.write("line4\\n");'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000603 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200604 'sys.stdout.write("line5\\r\\n");'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000605 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200606 'sys.stdout.write("line6\\r");'
Guido van Rossum98297ee2007-11-06 21:34:58 +0000607 'sys.stdout.flush();'
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200608 'sys.stdout.write("\\nline7");'
609 'sys.stdout.flush();'
610 'sys.stdout.write("\\nline8");'],
611 stderr=subprocess.PIPE,
612 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000613 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000614 self.addCleanup(p.stdout.close)
615 self.addCleanup(p.stderr.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200616 # BUG: can't give a non-empty stdin because it breaks both the
617 # select- and poll-based communicate() implementations.
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
636 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000637 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000638 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000639 max_handles = 1026 # too much for most UNIX systems
640 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000641 max_handles = 2050 # too much for (at least some) Windows setups
642 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400643 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000644 try:
645 for i in range(max_handles):
646 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400647 tmpfile = os.path.join(tmpdir, support.TESTFN)
648 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000649 except OSError as e:
650 if e.errno != errno.EMFILE:
651 raise
652 break
653 else:
654 self.skipTest("failed to reach the file descriptor limit "
655 "(tried %d)" % max_handles)
656 # Close a couple of them (should be enough for a subprocess)
657 for i in range(10):
658 os.close(handles.pop())
659 # Loop creating some subprocesses. If one of them leaks some fds,
660 # the next loop iteration will fail by reaching the max fd limit.
661 for i in range(15):
662 p = subprocess.Popen([sys.executable, "-c",
663 "import sys;"
664 "sys.stdout.write(sys.stdin.read())"],
665 stdin=subprocess.PIPE,
666 stdout=subprocess.PIPE,
667 stderr=subprocess.PIPE)
668 data = p.communicate(b"lime")[0]
669 self.assertEqual(data, b"lime")
670 finally:
671 for h in handles:
672 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400673 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000674
675 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000676 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
677 '"a b c" d e')
678 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
679 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000680 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
681 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000682 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
683 'a\\\\\\b "de fg" h')
684 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
685 'a\\\\\\"b c d')
686 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
687 '"a\\\\b c" d e')
688 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
689 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000690 self.assertEqual(subprocess.list2cmdline(['ab', '']),
691 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000692
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000693 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200694 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +0200695 "import os; os.read(0, 1)"],
696 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200697 self.addCleanup(p.stdin.close)
698 self.assertIsNone(p.poll())
699 os.write(p.stdin.fileno(), b'A')
700 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000701 # Subsequent invocations should just return the returncode
702 self.assertEqual(p.poll(), 0)
703
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000704 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200705 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000706 self.assertEqual(p.wait(), 0)
707 # Subsequent invocations should just return the returncode
708 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000709
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400710 def test_wait_timeout(self):
711 p = subprocess.Popen([sys.executable,
Reid Kleckner93479cc2011-03-14 19:32:41 -0400712 "-c", "import time; time.sleep(0.1)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -0400713 with self.assertRaises(subprocess.TimeoutExpired) as c:
714 p.wait(timeout=0.01)
715 self.assertIn("0.01", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -0400716 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
717 # time to start.
718 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400719
Peter Astrand738131d2004-11-30 21:04:45 +0000720 def test_invalid_bufsize(self):
721 # an invalid type of the bufsize argument should raise
722 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000723 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000724 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000725
Guido van Rossum46a05a72007-06-07 21:56:45 +0000726 def test_bufsize_is_none(self):
727 # bufsize=None should be the same as bufsize=0.
728 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
729 self.assertEqual(p.wait(), 0)
730 # Again with keyword arg
731 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
732 self.assertEqual(p.wait(), 0)
733
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000734 def test_leaking_fds_on_error(self):
735 # see bug #5179: Popen leaks file descriptors to PIPEs if
736 # the child fails to execute; this will eventually exhaust
737 # the maximum number of open fds. 1024 seems a very common
738 # value for that limit, but Windows has 2048, so we loop
739 # 1024 times (each call leaked two fds).
740 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000741 # Windows raises IOError. Others raise OSError.
742 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000743 subprocess.Popen(['nonexisting_i_hope'],
744 stdout=subprocess.PIPE,
745 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400746 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400747 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000748 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000749
Victor Stinnerb3693582010-05-21 20:13:12 +0000750 def test_issue8780(self):
751 # Ensure that stdout is inherited from the parent
752 # if stdout=PIPE is not used
753 code = ';'.join((
754 'import subprocess, sys',
755 'retcode = subprocess.call('
756 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
757 'assert retcode == 0'))
758 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000759 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000760
Tim Goldenaf5ac392010-08-06 13:03:56 +0000761 def test_handles_closed_on_exception(self):
762 # If CreateProcess exits with an error, ensure the
763 # duplicate output handles are released
764 ifhandle, ifname = mkstemp()
765 ofhandle, ofname = mkstemp()
766 efhandle, efname = mkstemp()
767 try:
768 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
769 stderr=efhandle)
770 except OSError:
771 os.close(ifhandle)
772 os.remove(ifname)
773 os.close(ofhandle)
774 os.remove(ofname)
775 os.close(efhandle)
776 os.remove(efname)
777 self.assertFalse(os.path.exists(ifname))
778 self.assertFalse(os.path.exists(ofname))
779 self.assertFalse(os.path.exists(efname))
780
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200781 def test_communicate_epipe(self):
782 # Issue 10963: communicate() should hide EPIPE
783 p = subprocess.Popen([sys.executable, "-c", 'pass'],
784 stdin=subprocess.PIPE,
785 stdout=subprocess.PIPE,
786 stderr=subprocess.PIPE)
787 self.addCleanup(p.stdout.close)
788 self.addCleanup(p.stderr.close)
789 self.addCleanup(p.stdin.close)
790 p.communicate(b"x" * 2**20)
791
792 def test_communicate_epipe_only_stdin(self):
793 # Issue 10963: communicate() should hide EPIPE
794 p = subprocess.Popen([sys.executable, "-c", 'pass'],
795 stdin=subprocess.PIPE)
796 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200797 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200798 p.communicate(b"x" * 2**20)
799
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200800 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
801 "Requires signal.SIGUSR1")
802 @unittest.skipUnless(hasattr(os, 'kill'),
803 "Requires os.kill")
804 @unittest.skipUnless(hasattr(os, 'getppid'),
805 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200806 def test_communicate_eintr(self):
807 # Issue #12493: communicate() should handle EINTR
808 def handler(signum, frame):
809 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200810 old_handler = signal.signal(signal.SIGUSR1, handler)
811 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200812
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200813 args = [sys.executable, "-c",
814 'import os, signal;'
815 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200816 for stream in ('stdout', 'stderr'):
817 kw = {stream: subprocess.PIPE}
818 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200819 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200820 process.communicate()
821
Tim Peterse718f612004-10-12 21:51:32 +0000822
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000823# context manager
824class _SuppressCoreFiles(object):
825 """Try to prevent core files from being created."""
826 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000827
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000828 def __enter__(self):
829 """Try to save previous ulimit, then set it to (0, 0)."""
Benjamin Peterson964561b2011-12-10 12:31:42 -0500830 if resource is not None:
831 try:
832 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
833 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
834 except (ValueError, resource.error):
835 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000836
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000837 if sys.platform == 'darwin':
838 # Check if the 'Crash Reporter' on OSX was configured
839 # in 'Developer' mode and warn that it will get triggered
840 # when it is.
841 #
842 # This assumes that this context manager is used in tests
843 # that might trigger the next manager.
844 value = subprocess.Popen(['/usr/bin/defaults', 'read',
845 'com.apple.CrashReporter', 'DialogType'],
846 stdout=subprocess.PIPE).communicate()[0]
847 if value.strip() == b'developer':
848 print("this tests triggers the Crash Reporter, "
849 "that is intentional", end='')
850 sys.stdout.flush()
851
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000852 def __exit__(self, *args):
853 """Return core file behavior to default."""
854 if self.old_limit is None:
855 return
Benjamin Peterson964561b2011-12-10 12:31:42 -0500856 if resource is not None:
857 try:
858 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
859 except (ValueError, resource.error):
860 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000861
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000862
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000863@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000864class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000865
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000866 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000867 nonexistent_dir = "/_this/pa.th/does/not/exist"
868 try:
869 os.chdir(nonexistent_dir)
870 except OSError as e:
871 # This avoids hard coding the errno value or the OS perror()
872 # string and instead capture the exception that we want to see
873 # below for comparison.
874 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000875 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000876 else:
877 self.fail("chdir to nonexistant directory %s succeeded." %
878 nonexistent_dir)
879
880 # Error in the child re-raised in the parent.
881 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000882 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000883 cwd=nonexistent_dir)
884 except OSError as e:
885 # Test that the child process chdir failure actually makes
886 # it up to the parent process as the correct exception.
887 self.assertEqual(desired_exception.errno, e.errno)
888 self.assertEqual(desired_exception.strerror, e.strerror)
889 else:
890 self.fail("Expected OSError: %s" % desired_exception)
891
892 def test_restore_signals(self):
893 # Code coverage for both values of restore_signals to make sure it
894 # at least does not blow up.
895 # A test for behavior would be complex. Contributions welcome.
896 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
897 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
898
899 def test_start_new_session(self):
900 # For code coverage of calling setsid(). We don't care if we get an
901 # EPERM error from it depending on the test execution environment, that
902 # still indicates that it was called.
903 try:
904 output = subprocess.check_output(
905 [sys.executable, "-c",
906 "import os; print(os.getpgid(os.getpid()))"],
907 start_new_session=True)
908 except OSError as e:
909 if e.errno != errno.EPERM:
910 raise
911 else:
912 parent_pgid = os.getpgid(os.getpid())
913 child_pgid = int(output)
914 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000915
916 def test_run_abort(self):
917 # returncode handles signal termination
918 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000919 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000920 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000921 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000922 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000923
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000924 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000925 # DISCLAIMER: Setting environment variables is *not* a good use
926 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000927 p = subprocess.Popen([sys.executable, "-c",
928 'import sys,os;'
929 'sys.stdout.write(os.getenv("FRUIT"))'],
930 stdout=subprocess.PIPE,
931 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000932 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000933 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000934
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000935 def test_preexec_exception(self):
936 def raise_it():
937 raise ValueError("What if two swallows carried a coconut?")
938 try:
939 p = subprocess.Popen([sys.executable, "-c", ""],
940 preexec_fn=raise_it)
941 except RuntimeError as e:
942 self.assertTrue(
943 subprocess._posixsubprocess,
944 "Expected a ValueError from the preexec_fn")
945 except ValueError as e:
946 self.assertIn("coconut", e.args[0])
947 else:
948 self.fail("Exception raised by preexec_fn did not make it "
949 "to the parent process.")
950
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000951 def test_preexec_gc_module_failure(self):
952 # This tests the code that disables garbage collection if the child
953 # process will execute any Python.
954 def raise_runtime_error():
955 raise RuntimeError("this shouldn't escape")
956 enabled = gc.isenabled()
957 orig_gc_disable = gc.disable
958 orig_gc_isenabled = gc.isenabled
959 try:
960 gc.disable()
961 self.assertFalse(gc.isenabled())
962 subprocess.call([sys.executable, '-c', ''],
963 preexec_fn=lambda: None)
964 self.assertFalse(gc.isenabled(),
965 "Popen enabled gc when it shouldn't.")
966
967 gc.enable()
968 self.assertTrue(gc.isenabled())
969 subprocess.call([sys.executable, '-c', ''],
970 preexec_fn=lambda: None)
971 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
972
973 gc.disable = raise_runtime_error
974 self.assertRaises(RuntimeError, subprocess.Popen,
975 [sys.executable, '-c', ''],
976 preexec_fn=lambda: None)
977
978 del gc.isenabled # force an AttributeError
979 self.assertRaises(AttributeError, subprocess.Popen,
980 [sys.executable, '-c', ''],
981 preexec_fn=lambda: None)
982 finally:
983 gc.disable = orig_gc_disable
984 gc.isenabled = orig_gc_isenabled
985 if not enabled:
986 gc.disable()
987
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000988 def test_args_string(self):
989 # args is a string
990 fd, fname = mkstemp()
991 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000992 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000993 fobj.write("#!/bin/sh\n")
994 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
995 sys.executable)
996 os.chmod(fname, 0o700)
997 p = subprocess.Popen(fname)
998 p.wait()
999 os.remove(fname)
1000 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001001
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001002 def test_invalid_args(self):
1003 # invalid arguments should raise ValueError
1004 self.assertRaises(ValueError, subprocess.call,
1005 [sys.executable, "-c",
1006 "import sys; sys.exit(47)"],
1007 startupinfo=47)
1008 self.assertRaises(ValueError, subprocess.call,
1009 [sys.executable, "-c",
1010 "import sys; sys.exit(47)"],
1011 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001012
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001013 def test_shell_sequence(self):
1014 # Run command through the shell (sequence)
1015 newenv = os.environ.copy()
1016 newenv["FRUIT"] = "apple"
1017 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1018 stdout=subprocess.PIPE,
1019 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001020 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001021 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001022
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001023 def test_shell_string(self):
1024 # Run command through the shell (string)
1025 newenv = os.environ.copy()
1026 newenv["FRUIT"] = "apple"
1027 p = subprocess.Popen("echo $FRUIT", shell=1,
1028 stdout=subprocess.PIPE,
1029 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001030 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001031 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001032
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001033 def test_call_string(self):
1034 # call() function with string argument on UNIX
1035 fd, fname = mkstemp()
1036 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001037 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001038 fobj.write("#!/bin/sh\n")
1039 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1040 sys.executable)
1041 os.chmod(fname, 0o700)
1042 rc = subprocess.call(fname)
1043 os.remove(fname)
1044 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001045
Stefan Krah9542cc62010-07-19 14:20:53 +00001046 def test_specific_shell(self):
1047 # Issue #9265: Incorrect name passed as arg[0].
1048 shells = []
1049 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1050 for name in ['bash', 'ksh']:
1051 sh = os.path.join(prefix, name)
1052 if os.path.isfile(sh):
1053 shells.append(sh)
1054 if not shells: # Will probably work for any shell but csh.
1055 self.skipTest("bash or ksh required for this test")
1056 sh = '/bin/sh'
1057 if os.path.isfile(sh) and not os.path.islink(sh):
1058 # Test will fail if /bin/sh is a symlink to csh.
1059 shells.append(sh)
1060 for sh in shells:
1061 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1062 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001063 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001064 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1065
Florent Xicluna4886d242010-03-08 13:27:26 +00001066 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001067 # Do not inherit file handles from the parent.
1068 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001069 p = subprocess.Popen([sys.executable, "-c", """if 1:
1070 import sys, time
1071 sys.stdout.write('x\\n')
1072 sys.stdout.flush()
1073 time.sleep(30)
1074 """],
1075 close_fds=True,
1076 stdin=subprocess.PIPE,
1077 stdout=subprocess.PIPE,
1078 stderr=subprocess.PIPE)
1079 # Wait for the interpreter to be completely initialized before
1080 # sending any signal.
1081 p.stdout.read(1)
1082 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001083 return p
1084
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001085 def _kill_dead_process(self, method, *args):
1086 # Do not inherit file handles from the parent.
1087 # It should fix failures on some platforms.
1088 p = subprocess.Popen([sys.executable, "-c", """if 1:
1089 import sys, time
1090 sys.stdout.write('x\\n')
1091 sys.stdout.flush()
1092 """],
1093 close_fds=True,
1094 stdin=subprocess.PIPE,
1095 stdout=subprocess.PIPE,
1096 stderr=subprocess.PIPE)
1097 # Wait for the interpreter to be completely initialized before
1098 # sending any signal.
1099 p.stdout.read(1)
1100 # The process should end after this
1101 time.sleep(1)
1102 # This shouldn't raise even though the child is now dead
1103 getattr(p, method)(*args)
1104 p.communicate()
1105
Florent Xicluna4886d242010-03-08 13:27:26 +00001106 def test_send_signal(self):
1107 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001108 _, stderr = p.communicate()
1109 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001110 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001111
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001112 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001113 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001114 _, stderr = p.communicate()
1115 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001116 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001117
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001118 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001119 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001120 _, stderr = p.communicate()
1121 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001122 self.assertEqual(p.wait(), -signal.SIGTERM)
1123
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001124 def test_send_signal_dead(self):
1125 # Sending a signal to a dead process
1126 self._kill_dead_process('send_signal', signal.SIGINT)
1127
1128 def test_kill_dead(self):
1129 # Killing a dead process
1130 self._kill_dead_process('kill')
1131
1132 def test_terminate_dead(self):
1133 # Terminating a dead process
1134 self._kill_dead_process('terminate')
1135
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001136 def check_close_std_fds(self, fds):
1137 # Issue #9905: test that subprocess pipes still work properly with
1138 # some standard fds closed
1139 stdin = 0
1140 newfds = []
1141 for a in fds:
1142 b = os.dup(a)
1143 newfds.append(b)
1144 if a == 0:
1145 stdin = b
1146 try:
1147 for fd in fds:
1148 os.close(fd)
1149 out, err = subprocess.Popen([sys.executable, "-c",
1150 'import sys;'
1151 'sys.stdout.write("apple");'
1152 'sys.stdout.flush();'
1153 'sys.stderr.write("orange")'],
1154 stdin=stdin,
1155 stdout=subprocess.PIPE,
1156 stderr=subprocess.PIPE).communicate()
1157 err = support.strip_python_stderr(err)
1158 self.assertEqual((out, err), (b'apple', b'orange'))
1159 finally:
1160 for b, a in zip(newfds, fds):
1161 os.dup2(b, a)
1162 for b in newfds:
1163 os.close(b)
1164
1165 def test_close_fd_0(self):
1166 self.check_close_std_fds([0])
1167
1168 def test_close_fd_1(self):
1169 self.check_close_std_fds([1])
1170
1171 def test_close_fd_2(self):
1172 self.check_close_std_fds([2])
1173
1174 def test_close_fds_0_1(self):
1175 self.check_close_std_fds([0, 1])
1176
1177 def test_close_fds_0_2(self):
1178 self.check_close_std_fds([0, 2])
1179
1180 def test_close_fds_1_2(self):
1181 self.check_close_std_fds([1, 2])
1182
1183 def test_close_fds_0_1_2(self):
1184 # Issue #10806: test that subprocess pipes still work properly with
1185 # all standard fds closed.
1186 self.check_close_std_fds([0, 1, 2])
1187
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001188 def test_remapping_std_fds(self):
1189 # open up some temporary files
1190 temps = [mkstemp() for i in range(3)]
1191 try:
1192 temp_fds = [fd for fd, fname in temps]
1193
1194 # unlink the files -- we won't need to reopen them
1195 for fd, fname in temps:
1196 os.unlink(fname)
1197
1198 # write some data to what will become stdin, and rewind
1199 os.write(temp_fds[1], b"STDIN")
1200 os.lseek(temp_fds[1], 0, 0)
1201
1202 # move the standard file descriptors out of the way
1203 saved_fds = [os.dup(fd) for fd in range(3)]
1204 try:
1205 # duplicate the file objects over the standard fd's
1206 for fd, temp_fd in enumerate(temp_fds):
1207 os.dup2(temp_fd, fd)
1208
1209 # now use those files in the "wrong" order, so that subprocess
1210 # has to rearrange them in the child
1211 p = subprocess.Popen([sys.executable, "-c",
1212 'import sys; got = sys.stdin.read();'
1213 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1214 stdin=temp_fds[1],
1215 stdout=temp_fds[2],
1216 stderr=temp_fds[0])
1217 p.wait()
1218 finally:
1219 # restore the original fd's underneath sys.stdin, etc.
1220 for std, saved in enumerate(saved_fds):
1221 os.dup2(saved, std)
1222 os.close(saved)
1223
1224 for fd in temp_fds:
1225 os.lseek(fd, 0, 0)
1226
1227 out = os.read(temp_fds[2], 1024)
1228 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1229 self.assertEqual(out, b"got STDIN")
1230 self.assertEqual(err, b"err")
1231
1232 finally:
1233 for fd in temp_fds:
1234 os.close(fd)
1235
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001236 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1237 # open up some temporary files
1238 temps = [mkstemp() for i in range(3)]
1239 temp_fds = [fd for fd, fname in temps]
1240 try:
1241 # unlink the files -- we won't need to reopen them
1242 for fd, fname in temps:
1243 os.unlink(fname)
1244
1245 # save a copy of the standard file descriptors
1246 saved_fds = [os.dup(fd) for fd in range(3)]
1247 try:
1248 # duplicate the temp files over the standard fd's 0, 1, 2
1249 for fd, temp_fd in enumerate(temp_fds):
1250 os.dup2(temp_fd, fd)
1251
1252 # write some data to what will become stdin, and rewind
1253 os.write(stdin_no, b"STDIN")
1254 os.lseek(stdin_no, 0, 0)
1255
1256 # now use those files in the given order, so that subprocess
1257 # has to rearrange them in the child
1258 p = subprocess.Popen([sys.executable, "-c",
1259 'import sys; got = sys.stdin.read();'
1260 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1261 stdin=stdin_no,
1262 stdout=stdout_no,
1263 stderr=stderr_no)
1264 p.wait()
1265
1266 for fd in temp_fds:
1267 os.lseek(fd, 0, 0)
1268
1269 out = os.read(stdout_no, 1024)
1270 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1271 finally:
1272 for std, saved in enumerate(saved_fds):
1273 os.dup2(saved, std)
1274 os.close(saved)
1275
1276 self.assertEqual(out, b"got STDIN")
1277 self.assertEqual(err, b"err")
1278
1279 finally:
1280 for fd in temp_fds:
1281 os.close(fd)
1282
1283 # When duping fds, if there arises a situation where one of the fds is
1284 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1285 # This tests all combinations of this.
1286 def test_swap_fds(self):
1287 self.check_swap_fds(0, 1, 2)
1288 self.check_swap_fds(0, 2, 1)
1289 self.check_swap_fds(1, 0, 2)
1290 self.check_swap_fds(1, 2, 0)
1291 self.check_swap_fds(2, 0, 1)
1292 self.check_swap_fds(2, 1, 0)
1293
Victor Stinner13bb71c2010-04-23 21:41:56 +00001294 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001295 def prepare():
1296 raise ValueError("surrogate:\uDCff")
1297
1298 try:
1299 subprocess.call(
1300 [sys.executable, "-c", "pass"],
1301 preexec_fn=prepare)
1302 except ValueError as err:
1303 # Pure Python implementations keeps the message
1304 self.assertIsNone(subprocess._posixsubprocess)
1305 self.assertEqual(str(err), "surrogate:\uDCff")
1306 except RuntimeError as err:
1307 # _posixsubprocess uses a default message
1308 self.assertIsNotNone(subprocess._posixsubprocess)
1309 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1310 else:
1311 self.fail("Expected ValueError or RuntimeError")
1312
Victor Stinner13bb71c2010-04-23 21:41:56 +00001313 def test_undecodable_env(self):
1314 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001315 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001316 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001317 env = os.environ.copy()
1318 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001319 # Use C locale to get ascii for the locale encoding to force
1320 # surrogate-escaping of \xFF in the child process; otherwise it can
1321 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001322 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001323 stdout = subprocess.check_output(
1324 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001325 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001326 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001327 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001328
1329 # test bytes
1330 key = key.encode("ascii", "surrogateescape")
1331 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001332 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001333 env = os.environ.copy()
1334 env[key] = value
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
Victor Stinnerb745a742010-05-18 17:17:23 +00001341 def test_bytes_program(self):
1342 abs_program = os.fsencode(sys.executable)
1343 path, program = os.path.split(sys.executable)
1344 program = os.fsencode(program)
1345
1346 # absolute bytes path
1347 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001348 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001349
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001350 # absolute bytes path as a string
1351 cmd = b"'" + abs_program + b"' -c pass"
1352 exitcode = subprocess.call(cmd, shell=True)
1353 self.assertEqual(exitcode, 0)
1354
Victor Stinnerb745a742010-05-18 17:17:23 +00001355 # bytes program, unicode PATH
1356 env = os.environ.copy()
1357 env["PATH"] = path
1358 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001359 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001360
1361 # bytes program, bytes PATH
1362 envb = os.environb.copy()
1363 envb[b"PATH"] = os.fsencode(path)
1364 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001365 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001366
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001367 def test_pipe_cloexec(self):
1368 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1369 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1370
1371 p1 = subprocess.Popen([sys.executable, sleeper],
1372 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1373 stderr=subprocess.PIPE, close_fds=False)
1374
1375 self.addCleanup(p1.communicate, b'')
1376
1377 p2 = subprocess.Popen([sys.executable, fd_status],
1378 stdout=subprocess.PIPE, close_fds=False)
1379
1380 output, error = p2.communicate()
1381 result_fds = set(map(int, output.split(b',')))
1382 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1383 p1.stderr.fileno()])
1384
1385 self.assertFalse(result_fds & unwanted_fds,
1386 "Expected no fds from %r to be open in child, "
1387 "found %r" %
1388 (unwanted_fds, result_fds & unwanted_fds))
1389
1390 def test_pipe_cloexec_real_tools(self):
1391 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1392 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1393
1394 subdata = b'zxcvbn'
1395 data = subdata * 4 + b'\n'
1396
1397 p1 = subprocess.Popen([sys.executable, qcat],
1398 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1399 close_fds=False)
1400
1401 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1402 stdin=p1.stdout, stdout=subprocess.PIPE,
1403 close_fds=False)
1404
1405 self.addCleanup(p1.wait)
1406 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001407 def kill_p1():
1408 try:
1409 p1.terminate()
1410 except ProcessLookupError:
1411 pass
1412 def kill_p2():
1413 try:
1414 p2.terminate()
1415 except ProcessLookupError:
1416 pass
1417 self.addCleanup(kill_p1)
1418 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001419
1420 p1.stdin.write(data)
1421 p1.stdin.close()
1422
1423 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1424
1425 self.assertTrue(readfiles, "The child hung")
1426 self.assertEqual(p2.stdout.read(), data)
1427
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001428 p1.stdout.close()
1429 p2.stdout.close()
1430
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001431 def test_close_fds(self):
1432 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1433
1434 fds = os.pipe()
1435 self.addCleanup(os.close, fds[0])
1436 self.addCleanup(os.close, fds[1])
1437
1438 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001439 # add a bunch more fds
1440 for _ in range(9):
1441 fd = os.open("/dev/null", os.O_RDONLY)
1442 self.addCleanup(os.close, fd)
1443 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001444
1445 p = subprocess.Popen([sys.executable, fd_status],
1446 stdout=subprocess.PIPE, close_fds=False)
1447 output, ignored = p.communicate()
1448 remaining_fds = set(map(int, output.split(b',')))
1449
1450 self.assertEqual(remaining_fds & open_fds, open_fds,
1451 "Some fds were closed")
1452
1453 p = subprocess.Popen([sys.executable, fd_status],
1454 stdout=subprocess.PIPE, close_fds=True)
1455 output, ignored = p.communicate()
1456 remaining_fds = set(map(int, output.split(b',')))
1457
1458 self.assertFalse(remaining_fds & open_fds,
1459 "Some fds were left open")
1460 self.assertIn(1, remaining_fds, "Subprocess failed")
1461
Gregory P. Smith8facece2012-01-21 14:01:08 -08001462 # Keep some of the fd's we opened open in the subprocess.
1463 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1464 fds_to_keep = set(open_fds.pop() for _ in range(8))
1465 p = subprocess.Popen([sys.executable, fd_status],
1466 stdout=subprocess.PIPE, close_fds=True,
1467 pass_fds=())
1468 output, ignored = p.communicate()
1469 remaining_fds = set(map(int, output.split(b',')))
1470
1471 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1472 "Some fds not in pass_fds were left open")
1473 self.assertIn(1, remaining_fds, "Subprocess failed")
1474
Victor Stinner88701e22011-06-01 13:13:04 +02001475 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1476 # descriptor of a pipe closed in the parent process is valid in the
1477 # child process according to fstat(), but the mode of the file
1478 # descriptor is invalid, and read or write raise an error.
1479 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001480 def test_pass_fds(self):
1481 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1482
1483 open_fds = set()
1484
1485 for x in range(5):
1486 fds = os.pipe()
1487 self.addCleanup(os.close, fds[0])
1488 self.addCleanup(os.close, fds[1])
1489 open_fds.update(fds)
1490
1491 for fd in open_fds:
1492 p = subprocess.Popen([sys.executable, fd_status],
1493 stdout=subprocess.PIPE, close_fds=True,
1494 pass_fds=(fd, ))
1495 output, ignored = p.communicate()
1496
1497 remaining_fds = set(map(int, output.split(b',')))
1498 to_be_closed = open_fds - {fd}
1499
1500 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1501 self.assertFalse(remaining_fds & to_be_closed,
1502 "fd to be closed passed")
1503
1504 # pass_fds overrides close_fds with a warning.
1505 with self.assertWarns(RuntimeWarning) as context:
1506 self.assertFalse(subprocess.call(
1507 [sys.executable, "-c", "import sys; sys.exit(0)"],
1508 close_fds=False, pass_fds=(fd, )))
1509 self.assertIn('overriding close_fds', str(context.warning))
1510
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001511 def test_stdout_stdin_are_single_inout_fd(self):
1512 with io.open(os.devnull, "r+") as inout:
1513 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1514 stdout=inout, stdin=inout)
1515 p.wait()
1516
1517 def test_stdout_stderr_are_single_inout_fd(self):
1518 with io.open(os.devnull, "r+") as inout:
1519 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1520 stdout=inout, stderr=inout)
1521 p.wait()
1522
1523 def test_stderr_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 stderr=inout, stdin=inout)
1527 p.wait()
1528
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001529 def test_wait_when_sigchild_ignored(self):
1530 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1531 sigchild_ignore = support.findfile("sigchild_ignore.py",
1532 subdir="subprocessdata")
1533 p = subprocess.Popen([sys.executable, sigchild_ignore],
1534 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1535 stdout, stderr = p.communicate()
1536 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001537 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001538 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001539
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001540 def test_select_unbuffered(self):
1541 # Issue #11459: bufsize=0 should really set the pipes as
1542 # unbuffered (and therefore let select() work properly).
1543 select = support.import_module("select")
1544 p = subprocess.Popen([sys.executable, "-c",
1545 'import sys;'
1546 'sys.stdout.write("apple")'],
1547 stdout=subprocess.PIPE,
1548 bufsize=0)
1549 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001550 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001551 try:
1552 self.assertEqual(f.read(4), b"appl")
1553 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1554 finally:
1555 p.wait()
1556
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001557 def test_zombie_fast_process_del(self):
1558 # Issue #12650: on Unix, if Popen.__del__() was called before the
1559 # process exited, it wouldn't be added to subprocess._active, and would
1560 # remain a zombie.
1561 # spawn a Popen, and delete its reference before it exits
1562 p = subprocess.Popen([sys.executable, "-c",
1563 'import sys, time;'
1564 'time.sleep(0.2)'],
1565 stdout=subprocess.PIPE,
1566 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001567 self.addCleanup(p.stdout.close)
1568 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001569 ident = id(p)
1570 pid = p.pid
1571 del p
1572 # check that p is in the active processes list
1573 self.assertIn(ident, [id(o) for o in subprocess._active])
1574
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001575 def test_leak_fast_process_del_killed(self):
1576 # Issue #12650: on Unix, if Popen.__del__() was called before the
1577 # process exited, and the process got killed by a signal, it would never
1578 # be removed from subprocess._active, which triggered a FD and memory
1579 # leak.
1580 # spawn a Popen, delete its reference and kill it
1581 p = subprocess.Popen([sys.executable, "-c",
1582 'import time;'
1583 'time.sleep(3)'],
1584 stdout=subprocess.PIPE,
1585 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001586 self.addCleanup(p.stdout.close)
1587 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001588 ident = id(p)
1589 pid = p.pid
1590 del p
1591 os.kill(pid, signal.SIGKILL)
1592 # check that p is in the active processes list
1593 self.assertIn(ident, [id(o) for o in subprocess._active])
1594
1595 # let some time for the process to exit, and create a new Popen: this
1596 # should trigger the wait() of p
1597 time.sleep(0.2)
1598 with self.assertRaises(EnvironmentError) as c:
1599 with subprocess.Popen(['nonexisting_i_hope'],
1600 stdout=subprocess.PIPE,
1601 stderr=subprocess.PIPE) as proc:
1602 pass
1603 # p should have been wait()ed on, and removed from the _active list
1604 self.assertRaises(OSError, os.waitpid, pid, 0)
1605 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1606
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001607
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001608@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001609class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001610
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001611 def test_startupinfo(self):
1612 # startupinfo argument
1613 # We uses hardcoded constants, because we do not want to
1614 # depend on win32all.
1615 STARTF_USESHOWWINDOW = 1
1616 SW_MAXIMIZE = 3
1617 startupinfo = subprocess.STARTUPINFO()
1618 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1619 startupinfo.wShowWindow = SW_MAXIMIZE
1620 # Since Python is a console process, it won't be affected
1621 # by wShowWindow, but the argument should be silently
1622 # ignored
1623 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001624 startupinfo=startupinfo)
1625
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001626 def test_creationflags(self):
1627 # creationflags argument
1628 CREATE_NEW_CONSOLE = 16
1629 sys.stderr.write(" a DOS box should flash briefly ...\n")
1630 subprocess.call(sys.executable +
1631 ' -c "import time; time.sleep(0.25)"',
1632 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001633
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001634 def test_invalid_args(self):
1635 # invalid arguments should raise ValueError
1636 self.assertRaises(ValueError, subprocess.call,
1637 [sys.executable, "-c",
1638 "import sys; sys.exit(47)"],
1639 preexec_fn=lambda: 1)
1640 self.assertRaises(ValueError, subprocess.call,
1641 [sys.executable, "-c",
1642 "import sys; sys.exit(47)"],
1643 stdout=subprocess.PIPE,
1644 close_fds=True)
1645
1646 def test_close_fds(self):
1647 # close file descriptors
1648 rc = subprocess.call([sys.executable, "-c",
1649 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001650 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001651 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001652
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001653 def test_shell_sequence(self):
1654 # Run command through the shell (sequence)
1655 newenv = os.environ.copy()
1656 newenv["FRUIT"] = "physalis"
1657 p = subprocess.Popen(["set"], shell=1,
1658 stdout=subprocess.PIPE,
1659 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001660 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001661 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001662
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001663 def test_shell_string(self):
1664 # Run command through the shell (string)
1665 newenv = os.environ.copy()
1666 newenv["FRUIT"] = "physalis"
1667 p = subprocess.Popen("set", shell=1,
1668 stdout=subprocess.PIPE,
1669 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001670 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001671 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001672
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001673 def test_call_string(self):
1674 # call() function with string argument on Windows
1675 rc = subprocess.call(sys.executable +
1676 ' -c "import sys; sys.exit(47)"')
1677 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001678
Florent Xicluna4886d242010-03-08 13:27:26 +00001679 def _kill_process(self, method, *args):
1680 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001681 p = subprocess.Popen([sys.executable, "-c", """if 1:
1682 import sys, time
1683 sys.stdout.write('x\\n')
1684 sys.stdout.flush()
1685 time.sleep(30)
1686 """],
1687 stdin=subprocess.PIPE,
1688 stdout=subprocess.PIPE,
1689 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001690 self.addCleanup(p.stdout.close)
1691 self.addCleanup(p.stderr.close)
1692 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001693 # Wait for the interpreter to be completely initialized before
1694 # sending any signal.
1695 p.stdout.read(1)
1696 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001697 _, stderr = p.communicate()
1698 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001699 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001700 self.assertNotEqual(returncode, 0)
1701
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001702 def _kill_dead_process(self, method, *args):
1703 p = subprocess.Popen([sys.executable, "-c", """if 1:
1704 import sys, time
1705 sys.stdout.write('x\\n')
1706 sys.stdout.flush()
1707 sys.exit(42)
1708 """],
1709 stdin=subprocess.PIPE,
1710 stdout=subprocess.PIPE,
1711 stderr=subprocess.PIPE)
1712 self.addCleanup(p.stdout.close)
1713 self.addCleanup(p.stderr.close)
1714 self.addCleanup(p.stdin.close)
1715 # Wait for the interpreter to be completely initialized before
1716 # sending any signal.
1717 p.stdout.read(1)
1718 # The process should end after this
1719 time.sleep(1)
1720 # This shouldn't raise even though the child is now dead
1721 getattr(p, method)(*args)
1722 _, stderr = p.communicate()
1723 self.assertStderrEqual(stderr, b'')
1724 rc = p.wait()
1725 self.assertEqual(rc, 42)
1726
Florent Xicluna4886d242010-03-08 13:27:26 +00001727 def test_send_signal(self):
1728 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001729
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001730 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001731 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001732
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001733 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001734 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001735
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001736 def test_send_signal_dead(self):
1737 self._kill_dead_process('send_signal', signal.SIGTERM)
1738
1739 def test_kill_dead(self):
1740 self._kill_dead_process('kill')
1741
1742 def test_terminate_dead(self):
1743 self._kill_dead_process('terminate')
1744
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001745
Brett Cannona23810f2008-05-26 19:04:21 +00001746# The module says:
1747# "NB This only works (and is only relevant) for UNIX."
1748#
1749# Actually, getoutput should work on any platform with an os.popen, but
1750# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001751@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001752class CommandTests(unittest.TestCase):
1753 def test_getoutput(self):
1754 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1755 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1756 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001757
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001758 # we use mkdtemp in the next line to create an empty directory
1759 # under our exclusive control; from that, we can invent a pathname
1760 # that we _know_ won't exist. This is guaranteed to fail.
1761 dir = None
1762 try:
1763 dir = tempfile.mkdtemp()
1764 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001765
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001766 status, output = subprocess.getstatusoutput('cat ' + name)
1767 self.assertNotEqual(status, 0)
1768 finally:
1769 if dir is not None:
1770 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001771
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001772
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001773@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1774 "poll system call not supported")
1775class ProcessTestCaseNoPoll(ProcessTestCase):
1776 def setUp(self):
1777 subprocess._has_poll = False
1778 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001779
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001780 def tearDown(self):
1781 subprocess._has_poll = True
1782 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001783
1784
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001785class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001786 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001787 def test_eintr_retry_call(self):
1788 record_calls = []
1789 def fake_os_func(*args):
1790 record_calls.append(args)
1791 if len(record_calls) == 2:
1792 raise OSError(errno.EINTR, "fake interrupted system call")
1793 return tuple(reversed(args))
1794
1795 self.assertEqual((999, 256),
1796 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1797 self.assertEqual([(256, 999)], record_calls)
1798 # This time there will be an EINTR so it will loop once.
1799 self.assertEqual((666,),
1800 subprocess._eintr_retry_call(fake_os_func, 666))
1801 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1802
1803
Tim Golden126c2962010-08-11 14:20:40 +00001804@unittest.skipUnless(mswindows, "Windows-specific tests")
1805class CommandsWithSpaces (BaseTestCase):
1806
1807 def setUp(self):
1808 super().setUp()
1809 f, fname = mkstemp(".py", "te st")
1810 self.fname = fname.lower ()
1811 os.write(f, b"import sys;"
1812 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1813 )
1814 os.close(f)
1815
1816 def tearDown(self):
1817 os.remove(self.fname)
1818 super().tearDown()
1819
1820 def with_spaces(self, *args, **kwargs):
1821 kwargs['stdout'] = subprocess.PIPE
1822 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001823 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001824 self.assertEqual(
1825 p.stdout.read ().decode("mbcs"),
1826 "2 [%r, 'ab cd']" % self.fname
1827 )
1828
1829 def test_shell_string_with_spaces(self):
1830 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001831 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1832 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001833
1834 def test_shell_sequence_with_spaces(self):
1835 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001836 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001837
1838 def test_noshell_string_with_spaces(self):
1839 # call() function with string argument with spaces on Windows
1840 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1841 "ab cd"))
1842
1843 def test_noshell_sequence_with_spaces(self):
1844 # call() function with sequence argument with spaces on Windows
1845 self.with_spaces([sys.executable, self.fname, "ab cd"])
1846
Brian Curtin79cdb662010-12-03 02:46:02 +00001847
Georg Brandla86b2622012-02-20 21:34:57 +01001848class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00001849
1850 def test_pipe(self):
1851 with subprocess.Popen([sys.executable, "-c",
1852 "import sys;"
1853 "sys.stdout.write('stdout');"
1854 "sys.stderr.write('stderr');"],
1855 stdout=subprocess.PIPE,
1856 stderr=subprocess.PIPE) as proc:
1857 self.assertEqual(proc.stdout.read(), b"stdout")
1858 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1859
1860 self.assertTrue(proc.stdout.closed)
1861 self.assertTrue(proc.stderr.closed)
1862
1863 def test_returncode(self):
1864 with subprocess.Popen([sys.executable, "-c",
1865 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07001866 pass
1867 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00001868 self.assertEqual(proc.returncode, 100)
1869
1870 def test_communicate_stdin(self):
1871 with subprocess.Popen([sys.executable, "-c",
1872 "import sys;"
1873 "sys.exit(sys.stdin.read() == 'context')"],
1874 stdin=subprocess.PIPE) as proc:
1875 proc.communicate(b"context")
1876 self.assertEqual(proc.returncode, 1)
1877
1878 def test_invalid_args(self):
1879 with self.assertRaises(EnvironmentError) as c:
1880 with subprocess.Popen(['nonexisting_i_hope'],
1881 stdout=subprocess.PIPE,
1882 stderr=subprocess.PIPE) as proc:
1883 pass
1884
1885 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1886 raise c.exception
1887
1888
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001889def test_main():
1890 unit_tests = (ProcessTestCase,
1891 POSIXProcessTestCase,
1892 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001893 CommandTests,
1894 ProcessTestCaseNoPoll,
1895 HelperFunctionTests,
1896 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02001897 ContextManagerTests,
1898 )
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001899
1900 support.run_unittest(*unit_tests)
1901 support.reap_children()
1902
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001903if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001904 unittest.main()