blob: 74ce0912cb33c6f0011e404f1521c3037a59bec6 [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
Andrew Svetlov47ec25d2012-08-19 16:25:37 +030017import textwrap
Benjamin Peterson964561b2011-12-10 12:31:42 -050018
19try:
20 import resource
21except ImportError:
22 resource = None
23
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000024mswindows = (sys.platform == "win32")
25
26#
27# Depends on the following external programs: Python
28#
29
30if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000031 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
32 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000033else:
34 SETBINARY = ''
35
Florent Xiclunab1e94e82010-02-27 22:12:37 +000036
37try:
38 mkstemp = tempfile.mkstemp
39except AttributeError:
40 # tempfile.mkstemp is not available
41 def mkstemp():
42 """Replacement for mkstemp, calling mktemp."""
43 fname = tempfile.mktemp()
44 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
45
Tim Peters3761e8d2004-10-13 04:07:12 +000046
Florent Xiclunac049d872010-03-27 22:47:23 +000047class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000048 def setUp(self):
49 # Try to minimize the number of children we have so this test
50 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000051 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000052
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000053 def tearDown(self):
54 for inst in subprocess._active:
55 inst.wait()
56 subprocess._cleanup()
57 self.assertFalse(subprocess._active, "subprocess._active not empty")
58
Florent Xiclunab1e94e82010-02-27 22:12:37 +000059 def assertStderrEqual(self, stderr, expected, msg=None):
60 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
61 # shutdown time. That frustrates tests trying to check stderr produced
62 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000063 actual = support.strip_python_stderr(stderr)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040064 # strip_python_stderr also strips whitespace, so we do too.
65 expected = expected.strip()
Florent Xiclunab1e94e82010-02-27 22:12:37 +000066 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000067
Florent Xiclunac049d872010-03-27 22:47:23 +000068
69class ProcessTestCase(BaseTestCase):
70
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000071 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000072 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000073 rc = subprocess.call([sys.executable, "-c",
74 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000075 self.assertEqual(rc, 47)
76
Reid Kleckner31aa7dd2011-03-14 12:02:10 -040077 def test_call_timeout(self):
78 # call() function with timeout argument; we want to test that the child
79 # process gets killed when the timeout expires. If the child isn't
80 # killed, this call will deadlock since subprocess.call waits for the
81 # child.
82 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
83 [sys.executable, "-c", "while True: pass"],
84 timeout=0.1)
85
Peter Astrand454f7672005-01-01 09:36:35 +000086 def test_check_call_zero(self):
87 # check_call() function with zero return code
88 rc = subprocess.check_call([sys.executable, "-c",
89 "import sys; sys.exit(0)"])
90 self.assertEqual(rc, 0)
91
92 def test_check_call_nonzero(self):
93 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000094 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +000095 subprocess.check_call([sys.executable, "-c",
96 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000097 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000098
Georg Brandlf9734072008-12-07 15:30:06 +000099 def test_check_output(self):
100 # check_output() function with zero return code
101 output = subprocess.check_output(
102 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +0000103 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000104
105 def test_check_output_nonzero(self):
106 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000107 with self.assertRaises(subprocess.CalledProcessError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000108 subprocess.check_output(
109 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000110 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +0000111
112 def test_check_output_stderr(self):
113 # check_output() function stderr redirected to stdout
114 output = subprocess.check_output(
115 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
116 stderr=subprocess.STDOUT)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000117 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +0000118
119 def test_check_output_stdout_arg(self):
120 # check_output() function stderr redirected to stdout
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000121 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000122 output = subprocess.check_output(
123 [sys.executable, "-c", "print('will not be run')"],
124 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000125 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000126 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000127
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400128 def test_check_output_timeout(self):
129 # check_output() function with timeout arg
130 with self.assertRaises(subprocess.TimeoutExpired) as c:
131 output = subprocess.check_output(
132 [sys.executable, "-c",
Victor Stinner149b1c72011-06-06 23:43:02 +0200133 "import sys, time\n"
134 "sys.stdout.write('BDFL')\n"
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400135 "sys.stdout.flush()\n"
Victor Stinner149b1c72011-06-06 23:43:02 +0200136 "time.sleep(3600)"],
Reid Klecknerda9ac722011-03-16 17:08:21 -0400137 # Some heavily loaded buildbots (sparc Debian 3.x) require
138 # this much time to start and print.
139 timeout=3)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400140 self.fail("Expected TimeoutExpired.")
141 self.assertEqual(c.exception.output, b'BDFL')
142
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000143 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000144 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000145 newenv = os.environ.copy()
146 newenv["FRUIT"] = "banana"
147 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000148 'import sys, os;'
149 'sys.exit(os.getenv("FRUIT")=="banana")'],
150 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000151 self.assertEqual(rc, 1)
152
Victor Stinner87b9bc32011-06-01 00:57:47 +0200153 def test_invalid_args(self):
154 # Popen() called with invalid arguments should raise TypeError
155 # but Popen.__del__ should not complain (issue #12085)
156 with support.captured_stderr() as s:
157 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
158 argcount = subprocess.Popen.__init__.__code__.co_argcount
159 too_many_args = [0] * (argcount + 1)
160 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
161 self.assertEqual(s.getvalue(), '')
162
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000163 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000164 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000165 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000166 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000167 self.addCleanup(p.stdout.close)
168 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000169 p.wait()
170 self.assertEqual(p.stdin, None)
171
172 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000173 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000174 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000175 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000176 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000177 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000178 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000179 self.addCleanup(p.stdin.close)
180 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000181 p.wait()
182 self.assertEqual(p.stdout, None)
183
184 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000185 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000186 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000187 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000188 self.addCleanup(p.stdout.close)
189 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000190 p.wait()
191 self.assertEqual(p.stderr, None)
192
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100193 @unittest.skipIf(sys.base_prefix != sys.prefix,
194 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000195 def test_executable_with_cwd(self):
Florent Xicluna1d1ab972010-03-11 01:53:10 +0000196 python_dir = os.path.dirname(os.path.realpath(sys.executable))
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000197 p = subprocess.Popen(["somethingyoudonthave", "-c",
198 "import sys; sys.exit(47)"],
199 executable=sys.executable, cwd=python_dir)
200 p.wait()
201 self.assertEqual(p.returncode, 47)
202
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100203 @unittest.skipIf(sys.base_prefix != sys.prefix,
204 'Test is not venv-compatible')
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000205 @unittest.skipIf(sysconfig.is_python_build(),
206 "need an installed Python. See #7774")
207 def test_executable_without_cwd(self):
208 # For a normal installation, it should work without 'cwd'
209 # argument. For test runs in the build directory, see #7774.
210 p = subprocess.Popen(["somethingyoudonthave", "-c",
211 "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000212 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000213 p.wait()
214 self.assertEqual(p.returncode, 47)
215
216 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000217 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000218 p = subprocess.Popen([sys.executable, "-c",
219 'import sys; sys.exit(sys.stdin.read() == "pear")'],
220 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000221 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000222 p.stdin.close()
223 p.wait()
224 self.assertEqual(p.returncode, 1)
225
226 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000227 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000228 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000229 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000230 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000231 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000232 os.lseek(d, 0, 0)
233 p = subprocess.Popen([sys.executable, "-c",
234 'import sys; sys.exit(sys.stdin.read() == "pear")'],
235 stdin=d)
236 p.wait()
237 self.assertEqual(p.returncode, 1)
238
239 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000240 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000241 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000242 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000243 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000244 tf.seek(0)
245 p = subprocess.Popen([sys.executable, "-c",
246 'import sys; sys.exit(sys.stdin.read() == "pear")'],
247 stdin=tf)
248 p.wait()
249 self.assertEqual(p.returncode, 1)
250
251 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000252 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000253 p = subprocess.Popen([sys.executable, "-c",
254 'import sys; sys.stdout.write("orange")'],
255 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000256 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000257 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000258
259 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000260 # stdout is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000261 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000262 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000263 d = tf.fileno()
264 p = subprocess.Popen([sys.executable, "-c",
265 'import sys; sys.stdout.write("orange")'],
266 stdout=d)
267 p.wait()
268 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000269 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000270
271 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000272 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000273 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000274 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000275 p = subprocess.Popen([sys.executable, "-c",
276 'import sys; sys.stdout.write("orange")'],
277 stdout=tf)
278 p.wait()
279 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000280 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000281
282 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000283 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000284 p = subprocess.Popen([sys.executable, "-c",
285 'import sys; sys.stderr.write("strawberry")'],
286 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000287 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000288 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000289
290 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000291 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000292 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000293 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000294 d = tf.fileno()
295 p = subprocess.Popen([sys.executable, "-c",
296 'import sys; sys.stderr.write("strawberry")'],
297 stderr=d)
298 p.wait()
299 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000300 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000301
302 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000303 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000304 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000305 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000306 p = subprocess.Popen([sys.executable, "-c",
307 'import sys; sys.stderr.write("strawberry")'],
308 stderr=tf)
309 p.wait()
310 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000311 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000312
313 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000314 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000315 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000316 'import sys;'
317 'sys.stdout.write("apple");'
318 'sys.stdout.flush();'
319 'sys.stderr.write("orange")'],
320 stdout=subprocess.PIPE,
321 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000322 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000323 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000324
325 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000326 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000327 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000328 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000329 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000330 'import sys;'
331 'sys.stdout.write("apple");'
332 'sys.stdout.flush();'
333 'sys.stderr.write("orange")'],
334 stdout=tf,
335 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000336 p.wait()
337 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000338 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000339
Thomas Wouters89f507f2006-12-13 04:49:30 +0000340 def test_stdout_filedes_of_stdout(self):
341 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000342 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000343 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000344 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000345
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200346 def test_stdout_devnull(self):
347 p = subprocess.Popen([sys.executable, "-c",
348 'for i in range(10240):'
349 'print("x" * 1024)'],
350 stdout=subprocess.DEVNULL)
351 p.wait()
352 self.assertEqual(p.stdout, None)
353
354 def test_stderr_devnull(self):
355 p = subprocess.Popen([sys.executable, "-c",
356 'import sys\n'
357 'for i in range(10240):'
358 'sys.stderr.write("x" * 1024)'],
359 stderr=subprocess.DEVNULL)
360 p.wait()
361 self.assertEqual(p.stderr, None)
362
363 def test_stdin_devnull(self):
364 p = subprocess.Popen([sys.executable, "-c",
365 'import sys;'
366 'sys.stdin.read(1)'],
367 stdin=subprocess.DEVNULL)
368 p.wait()
369 self.assertEqual(p.stdin, None)
370
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000371 def test_cwd(self):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000372 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000373 # We cannot use os.path.realpath to canonicalize the path,
374 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
375 cwd = os.getcwd()
376 os.chdir(tmpdir)
377 tmpdir = os.getcwd()
378 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000379 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000380 'import sys,os;'
381 'sys.stdout.write(os.getcwd())'],
382 stdout=subprocess.PIPE,
383 cwd=tmpdir)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000384 self.addCleanup(p.stdout.close)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000385 normcase = os.path.normcase
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000386 self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
387 normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000388
389 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000390 newenv = os.environ.copy()
391 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200392 with subprocess.Popen([sys.executable, "-c",
393 'import sys,os;'
394 'sys.stdout.write(os.getenv("FRUIT"))'],
395 stdout=subprocess.PIPE,
396 env=newenv) as p:
397 stdout, stderr = p.communicate()
398 self.assertEqual(stdout, b"orange")
399
Victor Stinner62d51182011-06-23 01:02:25 +0200400 # Windows requires at least the SYSTEMROOT environment variable to start
401 # Python
402 @unittest.skipIf(sys.platform == 'win32',
403 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200404 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200405 'the python library cannot be loaded '
406 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200407 def test_empty_env(self):
408 with subprocess.Popen([sys.executable, "-c",
409 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200410 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200411 stdout=subprocess.PIPE,
412 env={}) as p:
413 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200414 self.assertIn(stdout.strip(),
415 (b"[]",
416 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
417 # environment
418 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000419
Peter Astrandcbac93c2005-03-03 20:24:28 +0000420 def test_communicate_stdin(self):
421 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000422 'import sys;'
423 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000424 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000425 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000426 self.assertEqual(p.returncode, 1)
427
428 def test_communicate_stdout(self):
429 p = subprocess.Popen([sys.executable, "-c",
430 'import sys; sys.stdout.write("pineapple")'],
431 stdout=subprocess.PIPE)
432 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000433 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000434 self.assertEqual(stderr, None)
435
436 def test_communicate_stderr(self):
437 p = subprocess.Popen([sys.executable, "-c",
438 'import sys; sys.stderr.write("pineapple")'],
439 stderr=subprocess.PIPE)
440 (stdout, stderr) = p.communicate()
441 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000442 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000443
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000444 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000445 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000446 'import sys,os;'
447 'sys.stderr.write("pineapple");'
448 'sys.stdout.write(sys.stdin.read())'],
449 stdin=subprocess.PIPE,
450 stdout=subprocess.PIPE,
451 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000452 self.addCleanup(p.stdout.close)
453 self.addCleanup(p.stderr.close)
454 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000455 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000456 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000457 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000458
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400459 def test_communicate_timeout(self):
460 p = subprocess.Popen([sys.executable, "-c",
461 'import sys,os,time;'
462 'sys.stderr.write("pineapple\\n");'
463 'time.sleep(1);'
464 'sys.stderr.write("pear\\n");'
465 'sys.stdout.write(sys.stdin.read())'],
466 universal_newlines=True,
467 stdin=subprocess.PIPE,
468 stdout=subprocess.PIPE,
469 stderr=subprocess.PIPE)
470 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
471 timeout=0.3)
472 # Make sure we can keep waiting for it, and that we get the whole output
473 # after it completes.
474 (stdout, stderr) = p.communicate()
475 self.assertEqual(stdout, "banana")
476 self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
477
478 def test_communicate_timeout_large_ouput(self):
Ross Lagerwall003c7a32012-02-12 09:02:01 +0200479 # Test an expiring timeout while the child is outputting lots of data.
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400480 p = subprocess.Popen([sys.executable, "-c",
481 'import sys,os,time;'
482 'sys.stdout.write("a" * (64 * 1024));'
483 'time.sleep(0.2);'
484 'sys.stdout.write("a" * (64 * 1024));'
485 'time.sleep(0.2);'
486 'sys.stdout.write("a" * (64 * 1024));'
487 'time.sleep(0.2);'
488 'sys.stdout.write("a" * (64 * 1024));'],
489 stdout=subprocess.PIPE)
490 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
491 (stdout, _) = p.communicate()
492 self.assertEqual(len(stdout), 4 * 64 * 1024)
493
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000494 # Test for the fd leak reported in http://bugs.python.org/issue2791.
495 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000496 for stdin_pipe in (False, True):
497 for stdout_pipe in (False, True):
498 for stderr_pipe in (False, True):
499 options = {}
500 if stdin_pipe:
501 options['stdin'] = subprocess.PIPE
502 if stdout_pipe:
503 options['stdout'] = subprocess.PIPE
504 if stderr_pipe:
505 options['stderr'] = subprocess.PIPE
506 if not options:
507 continue
508 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
509 p.communicate()
510 if p.stdin is not None:
511 self.assertTrue(p.stdin.closed)
512 if p.stdout is not None:
513 self.assertTrue(p.stdout.closed)
514 if p.stderr is not None:
515 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000516
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000517 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000518 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000519 p = subprocess.Popen([sys.executable, "-c",
520 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000521 (stdout, stderr) = p.communicate()
522 self.assertEqual(stdout, None)
523 self.assertEqual(stderr, None)
524
525 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000526 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000527 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000528 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000529 x, y = os.pipe()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000530 os.close(x)
531 os.close(y)
532 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000533 'import sys,os;'
534 'sys.stdout.write(sys.stdin.read(47));'
Charles-François Natali2d517212011-05-29 16:36:44 +0200535 'sys.stderr.write("x" * %d);'
536 'sys.stdout.write(sys.stdin.read())' %
537 support.PIPE_MAX_SIZE],
Guido van Rossum98297ee2007-11-06 21:34:58 +0000538 stdin=subprocess.PIPE,
539 stdout=subprocess.PIPE,
540 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000541 self.addCleanup(p.stdout.close)
542 self.addCleanup(p.stderr.close)
543 self.addCleanup(p.stdin.close)
Charles-François Natali2d517212011-05-29 16:36:44 +0200544 string_to_write = b"a" * support.PIPE_MAX_SIZE
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000545 (stdout, stderr) = p.communicate(string_to_write)
546 self.assertEqual(stdout, string_to_write)
547
548 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000549 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000550 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000551 'import sys,os;'
552 'sys.stdout.write(sys.stdin.read())'],
553 stdin=subprocess.PIPE,
554 stdout=subprocess.PIPE,
555 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000556 self.addCleanup(p.stdout.close)
557 self.addCleanup(p.stderr.close)
558 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000559 p.stdin.write(b"banana")
560 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000561 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000562 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000563
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000564 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000565 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000566 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200567 'buf = sys.stdout.buffer;'
568 'buf.write(sys.stdin.readline().encode());'
569 'buf.flush();'
570 'buf.write(b"line2\\n");'
571 'buf.flush();'
572 'buf.write(sys.stdin.read().encode());'
573 'buf.flush();'
574 'buf.write(b"line4\\n");'
575 'buf.flush();'
576 'buf.write(b"line5\\r\\n");'
577 'buf.flush();'
578 'buf.write(b"line6\\r");'
579 'buf.flush();'
580 'buf.write(b"\\nline7");'
581 'buf.flush();'
582 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200583 stdin=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000584 stdout=subprocess.PIPE,
585 universal_newlines=1)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200586 p.stdin.write("line1\n")
587 self.assertEqual(p.stdout.readline(), "line1\n")
588 p.stdin.write("line3\n")
589 p.stdin.close()
Brian Curtin3c6a9512010-11-05 03:58:52 +0000590 self.addCleanup(p.stdout.close)
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200591 self.assertEqual(p.stdout.readline(),
592 "line2\n")
593 self.assertEqual(p.stdout.read(6),
594 "line3\n")
595 self.assertEqual(p.stdout.read(),
596 "line4\nline5\nline6\nline7\nline8")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000597
598 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000599 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000600 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000601 'import sys,os;' + SETBINARY +
Antoine Pitrouec2d2692012-08-05 00:23:40 +0200602 'buf = sys.stdout.buffer;'
603 'buf.write(b"line2\\n");'
604 'buf.flush();'
605 'buf.write(b"line4\\n");'
606 'buf.flush();'
607 'buf.write(b"line5\\r\\n");'
608 'buf.flush();'
609 'buf.write(b"line6\\r");'
610 'buf.flush();'
611 'buf.write(b"\\nline7");'
612 'buf.flush();'
613 'buf.write(b"\\nline8");'],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200614 stderr=subprocess.PIPE,
615 stdout=subprocess.PIPE,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000616 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000617 self.addCleanup(p.stdout.close)
618 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000619 (stdout, stderr) = p.communicate()
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200620 self.assertEqual(stdout,
621 "line2\nline4\nline5\nline6\nline7\nline8")
622
623 def test_universal_newlines_communicate_stdin(self):
624 # universal newlines through communicate(), with only stdin
625 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300626 'import sys,os;' + SETBINARY + textwrap.dedent('''
627 s = sys.stdin.readline()
628 assert s == "line1\\n", repr(s)
629 s = sys.stdin.read()
630 assert s == "line3\\n", repr(s)
631 ''')],
Antoine Pitrouab85ff32011-07-23 22:03:45 +0200632 stdin=subprocess.PIPE,
633 universal_newlines=1)
634 (stdout, stderr) = p.communicate("line1\nline3\n")
635 self.assertEqual(p.returncode, 0)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000636
Andrew Svetlovf3765072012-08-14 18:35:17 +0300637 def test_universal_newlines_communicate_input_none(self):
638 # Test communicate(input=None) with universal newlines.
639 #
640 # We set stdout to PIPE because, as of this writing, a different
641 # code path is tested when the number of pipes is zero or one.
642 p = subprocess.Popen([sys.executable, "-c", "pass"],
643 stdin=subprocess.PIPE,
644 stdout=subprocess.PIPE,
645 universal_newlines=True)
646 p.communicate()
647 self.assertEqual(p.returncode, 0)
648
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300649 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300650 # universal newlines through communicate(), with stdin, stdout, stderr
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300651 p = subprocess.Popen([sys.executable, "-c",
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300652 'import sys,os;' + SETBINARY + textwrap.dedent('''
653 s = sys.stdin.buffer.readline()
654 sys.stdout.buffer.write(s)
655 sys.stdout.buffer.write(b"line2\\r")
656 sys.stderr.buffer.write(b"eline2\\n")
657 s = sys.stdin.buffer.read()
658 sys.stdout.buffer.write(s)
659 sys.stdout.buffer.write(b"line4\\n")
660 sys.stdout.buffer.write(b"line5\\r\\n")
661 sys.stderr.buffer.write(b"eline6\\r")
662 sys.stderr.buffer.write(b"eline7\\r\\nz")
663 ''')],
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300664 stdin=subprocess.PIPE,
665 stderr=subprocess.PIPE,
666 stdout=subprocess.PIPE,
Andrew Svetlov47ec25d2012-08-19 16:25:37 +0300667 universal_newlines=True)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300668 self.addCleanup(p.stdout.close)
669 self.addCleanup(p.stderr.close)
670 (stdout, stderr) = p.communicate("line1\nline3\n")
671 self.assertEqual(p.returncode, 0)
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300672 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300673 # Python debug build push something like "[42442 refs]\n"
674 # to stderr at exit of subprocess.
Andrew Svetlov943c5b32012-08-16 20:17:47 +0300675 # Don't use assertStderrEqual because it strips CR and LF from output.
676 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
Andrew Svetlov5395d2f2012-08-15 22:46:43 +0300677
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000678 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000679 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000680 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000681 max_handles = 1026 # too much for most UNIX systems
682 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000683 max_handles = 2050 # too much for (at least some) Windows setups
684 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400685 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000686 try:
687 for i in range(max_handles):
688 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400689 tmpfile = os.path.join(tmpdir, support.TESTFN)
690 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000691 except OSError as e:
692 if e.errno != errno.EMFILE:
693 raise
694 break
695 else:
696 self.skipTest("failed to reach the file descriptor limit "
697 "(tried %d)" % max_handles)
698 # Close a couple of them (should be enough for a subprocess)
699 for i in range(10):
700 os.close(handles.pop())
701 # Loop creating some subprocesses. If one of them leaks some fds,
702 # the next loop iteration will fail by reaching the max fd limit.
703 for i in range(15):
704 p = subprocess.Popen([sys.executable, "-c",
705 "import sys;"
706 "sys.stdout.write(sys.stdin.read())"],
707 stdin=subprocess.PIPE,
708 stdout=subprocess.PIPE,
709 stderr=subprocess.PIPE)
710 data = p.communicate(b"lime")[0]
711 self.assertEqual(data, b"lime")
712 finally:
713 for h in handles:
714 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400715 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000716
717 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000718 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
719 '"a b c" d e')
720 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
721 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000722 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
723 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000724 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
725 'a\\\\\\b "de fg" h')
726 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
727 'a\\\\\\"b c d')
728 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
729 '"a\\\\b c" d e')
730 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
731 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000732 self.assertEqual(subprocess.list2cmdline(['ab', '']),
733 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000734
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000735 def test_poll(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200736 p = subprocess.Popen([sys.executable, "-c",
Ross Lagerwalle7ad4192012-02-22 06:02:07 +0200737 "import os; os.read(0, 1)"],
738 stdin=subprocess.PIPE)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200739 self.addCleanup(p.stdin.close)
740 self.assertIsNone(p.poll())
741 os.write(p.stdin.fileno(), b'A')
742 p.wait()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000743 # Subsequent invocations should just return the returncode
744 self.assertEqual(p.poll(), 0)
745
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000746 def test_wait(self):
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200747 p = subprocess.Popen([sys.executable, "-c", "pass"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000748 self.assertEqual(p.wait(), 0)
749 # Subsequent invocations should just return the returncode
750 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000751
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400752 def test_wait_timeout(self):
753 p = subprocess.Popen([sys.executable,
Reid Kleckner93479cc2011-03-14 19:32:41 -0400754 "-c", "import time; time.sleep(0.1)"])
Reid Kleckner2b228f02011-03-16 16:57:54 -0400755 with self.assertRaises(subprocess.TimeoutExpired) as c:
756 p.wait(timeout=0.01)
757 self.assertIn("0.01", str(c.exception)) # For coverage of __str__.
Reid Klecknerda9ac722011-03-16 17:08:21 -0400758 # Some heavily loaded buildbots (sparc Debian 3.x) require this much
759 # time to start.
760 self.assertEqual(p.wait(timeout=3), 0)
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400761
Peter Astrand738131d2004-11-30 21:04:45 +0000762 def test_invalid_bufsize(self):
763 # an invalid type of the bufsize argument should raise
764 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000765 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000766 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000767
Guido van Rossum46a05a72007-06-07 21:56:45 +0000768 def test_bufsize_is_none(self):
769 # bufsize=None should be the same as bufsize=0.
770 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
771 self.assertEqual(p.wait(), 0)
772 # Again with keyword arg
773 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
774 self.assertEqual(p.wait(), 0)
775
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000776 def test_leaking_fds_on_error(self):
777 # see bug #5179: Popen leaks file descriptors to PIPEs if
778 # the child fails to execute; this will eventually exhaust
779 # the maximum number of open fds. 1024 seems a very common
780 # value for that limit, but Windows has 2048, so we loop
781 # 1024 times (each call leaked two fds).
782 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000783 # Windows raises IOError. Others raise OSError.
784 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000785 subprocess.Popen(['nonexisting_i_hope'],
786 stdout=subprocess.PIPE,
787 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400788 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400789 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000790 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000791
Victor Stinnerb3693582010-05-21 20:13:12 +0000792 def test_issue8780(self):
793 # Ensure that stdout is inherited from the parent
794 # if stdout=PIPE is not used
795 code = ';'.join((
796 'import subprocess, sys',
797 'retcode = subprocess.call('
798 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
799 'assert retcode == 0'))
800 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000801 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000802
Tim Goldenaf5ac392010-08-06 13:03:56 +0000803 def test_handles_closed_on_exception(self):
804 # If CreateProcess exits with an error, ensure the
805 # duplicate output handles are released
806 ifhandle, ifname = mkstemp()
807 ofhandle, ofname = mkstemp()
808 efhandle, efname = mkstemp()
809 try:
810 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
811 stderr=efhandle)
812 except OSError:
813 os.close(ifhandle)
814 os.remove(ifname)
815 os.close(ofhandle)
816 os.remove(ofname)
817 os.close(efhandle)
818 os.remove(efname)
819 self.assertFalse(os.path.exists(ifname))
820 self.assertFalse(os.path.exists(ofname))
821 self.assertFalse(os.path.exists(efname))
822
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200823 def test_communicate_epipe(self):
824 # Issue 10963: communicate() should hide EPIPE
825 p = subprocess.Popen([sys.executable, "-c", 'pass'],
826 stdin=subprocess.PIPE,
827 stdout=subprocess.PIPE,
828 stderr=subprocess.PIPE)
829 self.addCleanup(p.stdout.close)
830 self.addCleanup(p.stderr.close)
831 self.addCleanup(p.stdin.close)
832 p.communicate(b"x" * 2**20)
833
834 def test_communicate_epipe_only_stdin(self):
835 # Issue 10963: communicate() should hide EPIPE
836 p = subprocess.Popen([sys.executable, "-c", 'pass'],
837 stdin=subprocess.PIPE)
838 self.addCleanup(p.stdin.close)
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200839 p.wait()
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200840 p.communicate(b"x" * 2**20)
841
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200842 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
843 "Requires signal.SIGUSR1")
844 @unittest.skipUnless(hasattr(os, 'kill'),
845 "Requires os.kill")
846 @unittest.skipUnless(hasattr(os, 'getppid'),
847 "Requires os.getppid")
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200848 def test_communicate_eintr(self):
849 # Issue #12493: communicate() should handle EINTR
850 def handler(signum, frame):
851 pass
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200852 old_handler = signal.signal(signal.SIGUSR1, handler)
853 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200854
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200855 args = [sys.executable, "-c",
856 'import os, signal;'
857 'os.kill(os.getppid(), signal.SIGUSR1)']
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200858 for stream in ('stdout', 'stderr'):
859 kw = {stream: subprocess.PIPE}
860 with subprocess.Popen(args, **kw) as process:
Ross Lagerwallab66d2a2012-02-12 09:01:30 +0200861 # communicate() will be interrupted by SIGUSR1
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200862 process.communicate()
863
Tim Peterse718f612004-10-12 21:51:32 +0000864
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000865# context manager
866class _SuppressCoreFiles(object):
867 """Try to prevent core files from being created."""
868 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000869
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000870 def __enter__(self):
871 """Try to save previous ulimit, then set it to (0, 0)."""
Benjamin Peterson964561b2011-12-10 12:31:42 -0500872 if resource is not None:
873 try:
874 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
875 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
876 except (ValueError, resource.error):
877 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000878
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000879 if sys.platform == 'darwin':
880 # Check if the 'Crash Reporter' on OSX was configured
881 # in 'Developer' mode and warn that it will get triggered
882 # when it is.
883 #
884 # This assumes that this context manager is used in tests
885 # that might trigger the next manager.
886 value = subprocess.Popen(['/usr/bin/defaults', 'read',
887 'com.apple.CrashReporter', 'DialogType'],
888 stdout=subprocess.PIPE).communicate()[0]
889 if value.strip() == b'developer':
890 print("this tests triggers the Crash Reporter, "
891 "that is intentional", end='')
892 sys.stdout.flush()
893
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000894 def __exit__(self, *args):
895 """Return core file behavior to default."""
896 if self.old_limit is None:
897 return
Benjamin Peterson964561b2011-12-10 12:31:42 -0500898 if resource is not None:
899 try:
900 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
901 except (ValueError, resource.error):
902 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000903
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000904
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000905@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000906class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000907
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000908 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000909 nonexistent_dir = "/_this/pa.th/does/not/exist"
910 try:
911 os.chdir(nonexistent_dir)
912 except OSError as e:
913 # This avoids hard coding the errno value or the OS perror()
914 # string and instead capture the exception that we want to see
915 # below for comparison.
916 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000917 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000918 else:
919 self.fail("chdir to nonexistant directory %s succeeded." %
920 nonexistent_dir)
921
922 # Error in the child re-raised in the parent.
923 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000924 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000925 cwd=nonexistent_dir)
926 except OSError as e:
927 # Test that the child process chdir failure actually makes
928 # it up to the parent process as the correct exception.
929 self.assertEqual(desired_exception.errno, e.errno)
930 self.assertEqual(desired_exception.strerror, e.strerror)
931 else:
932 self.fail("Expected OSError: %s" % desired_exception)
933
934 def test_restore_signals(self):
935 # Code coverage for both values of restore_signals to make sure it
936 # at least does not blow up.
937 # A test for behavior would be complex. Contributions welcome.
938 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
939 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
940
941 def test_start_new_session(self):
942 # For code coverage of calling setsid(). We don't care if we get an
943 # EPERM error from it depending on the test execution environment, that
944 # still indicates that it was called.
945 try:
946 output = subprocess.check_output(
947 [sys.executable, "-c",
948 "import os; print(os.getpgid(os.getpid()))"],
949 start_new_session=True)
950 except OSError as e:
951 if e.errno != errno.EPERM:
952 raise
953 else:
954 parent_pgid = os.getpgid(os.getpid())
955 child_pgid = int(output)
956 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000957
958 def test_run_abort(self):
959 # returncode handles signal termination
960 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000961 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000962 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000963 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000964 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000965
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000966 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000967 # DISCLAIMER: Setting environment variables is *not* a good use
968 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000969 p = subprocess.Popen([sys.executable, "-c",
970 'import sys,os;'
971 'sys.stdout.write(os.getenv("FRUIT"))'],
972 stdout=subprocess.PIPE,
973 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000974 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000975 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000976
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000977 def test_preexec_exception(self):
978 def raise_it():
979 raise ValueError("What if two swallows carried a coconut?")
980 try:
981 p = subprocess.Popen([sys.executable, "-c", ""],
982 preexec_fn=raise_it)
983 except RuntimeError as e:
984 self.assertTrue(
985 subprocess._posixsubprocess,
986 "Expected a ValueError from the preexec_fn")
987 except ValueError as e:
988 self.assertIn("coconut", e.args[0])
989 else:
990 self.fail("Exception raised by preexec_fn did not make it "
991 "to the parent process.")
992
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000993 def test_preexec_gc_module_failure(self):
994 # This tests the code that disables garbage collection if the child
995 # process will execute any Python.
996 def raise_runtime_error():
997 raise RuntimeError("this shouldn't escape")
998 enabled = gc.isenabled()
999 orig_gc_disable = gc.disable
1000 orig_gc_isenabled = gc.isenabled
1001 try:
1002 gc.disable()
1003 self.assertFalse(gc.isenabled())
1004 subprocess.call([sys.executable, '-c', ''],
1005 preexec_fn=lambda: None)
1006 self.assertFalse(gc.isenabled(),
1007 "Popen enabled gc when it shouldn't.")
1008
1009 gc.enable()
1010 self.assertTrue(gc.isenabled())
1011 subprocess.call([sys.executable, '-c', ''],
1012 preexec_fn=lambda: None)
1013 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
1014
1015 gc.disable = raise_runtime_error
1016 self.assertRaises(RuntimeError, subprocess.Popen,
1017 [sys.executable, '-c', ''],
1018 preexec_fn=lambda: None)
1019
1020 del gc.isenabled # force an AttributeError
1021 self.assertRaises(AttributeError, subprocess.Popen,
1022 [sys.executable, '-c', ''],
1023 preexec_fn=lambda: None)
1024 finally:
1025 gc.disable = orig_gc_disable
1026 gc.isenabled = orig_gc_isenabled
1027 if not enabled:
1028 gc.disable()
1029
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001030 def test_args_string(self):
1031 # args is a string
1032 fd, fname = mkstemp()
1033 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001034 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001035 fobj.write("#!/bin/sh\n")
1036 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1037 sys.executable)
1038 os.chmod(fname, 0o700)
1039 p = subprocess.Popen(fname)
1040 p.wait()
1041 os.remove(fname)
1042 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001043
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001044 def test_invalid_args(self):
1045 # invalid arguments should raise ValueError
1046 self.assertRaises(ValueError, subprocess.call,
1047 [sys.executable, "-c",
1048 "import sys; sys.exit(47)"],
1049 startupinfo=47)
1050 self.assertRaises(ValueError, subprocess.call,
1051 [sys.executable, "-c",
1052 "import sys; sys.exit(47)"],
1053 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001054
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001055 def test_shell_sequence(self):
1056 # Run command through the shell (sequence)
1057 newenv = os.environ.copy()
1058 newenv["FRUIT"] = "apple"
1059 p = subprocess.Popen(["echo $FRUIT"], shell=1,
1060 stdout=subprocess.PIPE,
1061 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001062 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001063 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001064
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001065 def test_shell_string(self):
1066 # Run command through the shell (string)
1067 newenv = os.environ.copy()
1068 newenv["FRUIT"] = "apple"
1069 p = subprocess.Popen("echo $FRUIT", shell=1,
1070 stdout=subprocess.PIPE,
1071 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001072 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001073 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +00001074
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001075 def test_call_string(self):
1076 # call() function with string argument on UNIX
1077 fd, fname = mkstemp()
1078 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +00001079 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001080 fobj.write("#!/bin/sh\n")
1081 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
1082 sys.executable)
1083 os.chmod(fname, 0o700)
1084 rc = subprocess.call(fname)
1085 os.remove(fname)
1086 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +00001087
Stefan Krah9542cc62010-07-19 14:20:53 +00001088 def test_specific_shell(self):
1089 # Issue #9265: Incorrect name passed as arg[0].
1090 shells = []
1091 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
1092 for name in ['bash', 'ksh']:
1093 sh = os.path.join(prefix, name)
1094 if os.path.isfile(sh):
1095 shells.append(sh)
1096 if not shells: # Will probably work for any shell but csh.
1097 self.skipTest("bash or ksh required for this test")
1098 sh = '/bin/sh'
1099 if os.path.isfile(sh) and not os.path.islink(sh):
1100 # Test will fail if /bin/sh is a symlink to csh.
1101 shells.append(sh)
1102 for sh in shells:
1103 p = subprocess.Popen("echo $0", executable=sh, shell=True,
1104 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +00001105 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +00001106 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
1107
Florent Xicluna4886d242010-03-08 13:27:26 +00001108 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +00001109 # Do not inherit file handles from the parent.
1110 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +00001111 p = subprocess.Popen([sys.executable, "-c", """if 1:
1112 import sys, time
1113 sys.stdout.write('x\\n')
1114 sys.stdout.flush()
1115 time.sleep(30)
1116 """],
1117 close_fds=True,
1118 stdin=subprocess.PIPE,
1119 stdout=subprocess.PIPE,
1120 stderr=subprocess.PIPE)
1121 # Wait for the interpreter to be completely initialized before
1122 # sending any signal.
1123 p.stdout.read(1)
1124 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +00001125 return p
1126
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001127 def _kill_dead_process(self, method, *args):
1128 # Do not inherit file handles from the parent.
1129 # It should fix failures on some platforms.
1130 p = subprocess.Popen([sys.executable, "-c", """if 1:
1131 import sys, time
1132 sys.stdout.write('x\\n')
1133 sys.stdout.flush()
1134 """],
1135 close_fds=True,
1136 stdin=subprocess.PIPE,
1137 stdout=subprocess.PIPE,
1138 stderr=subprocess.PIPE)
1139 # Wait for the interpreter to be completely initialized before
1140 # sending any signal.
1141 p.stdout.read(1)
1142 # The process should end after this
1143 time.sleep(1)
1144 # This shouldn't raise even though the child is now dead
1145 getattr(p, method)(*args)
1146 p.communicate()
1147
Florent Xicluna4886d242010-03-08 13:27:26 +00001148 def test_send_signal(self):
1149 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +00001150 _, stderr = p.communicate()
1151 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001152 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +00001153
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001154 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001155 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +00001156 _, stderr = p.communicate()
1157 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001158 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +00001159
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001160 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001161 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +00001162 _, stderr = p.communicate()
1163 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001164 self.assertEqual(p.wait(), -signal.SIGTERM)
1165
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001166 def test_send_signal_dead(self):
1167 # Sending a signal to a dead process
1168 self._kill_dead_process('send_signal', signal.SIGINT)
1169
1170 def test_kill_dead(self):
1171 # Killing a dead process
1172 self._kill_dead_process('kill')
1173
1174 def test_terminate_dead(self):
1175 # Terminating a dead process
1176 self._kill_dead_process('terminate')
1177
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +00001178 def check_close_std_fds(self, fds):
1179 # Issue #9905: test that subprocess pipes still work properly with
1180 # some standard fds closed
1181 stdin = 0
1182 newfds = []
1183 for a in fds:
1184 b = os.dup(a)
1185 newfds.append(b)
1186 if a == 0:
1187 stdin = b
1188 try:
1189 for fd in fds:
1190 os.close(fd)
1191 out, err = subprocess.Popen([sys.executable, "-c",
1192 'import sys;'
1193 'sys.stdout.write("apple");'
1194 'sys.stdout.flush();'
1195 'sys.stderr.write("orange")'],
1196 stdin=stdin,
1197 stdout=subprocess.PIPE,
1198 stderr=subprocess.PIPE).communicate()
1199 err = support.strip_python_stderr(err)
1200 self.assertEqual((out, err), (b'apple', b'orange'))
1201 finally:
1202 for b, a in zip(newfds, fds):
1203 os.dup2(b, a)
1204 for b in newfds:
1205 os.close(b)
1206
1207 def test_close_fd_0(self):
1208 self.check_close_std_fds([0])
1209
1210 def test_close_fd_1(self):
1211 self.check_close_std_fds([1])
1212
1213 def test_close_fd_2(self):
1214 self.check_close_std_fds([2])
1215
1216 def test_close_fds_0_1(self):
1217 self.check_close_std_fds([0, 1])
1218
1219 def test_close_fds_0_2(self):
1220 self.check_close_std_fds([0, 2])
1221
1222 def test_close_fds_1_2(self):
1223 self.check_close_std_fds([1, 2])
1224
1225 def test_close_fds_0_1_2(self):
1226 # Issue #10806: test that subprocess pipes still work properly with
1227 # all standard fds closed.
1228 self.check_close_std_fds([0, 1, 2])
1229
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001230 def test_remapping_std_fds(self):
1231 # open up some temporary files
1232 temps = [mkstemp() for i in range(3)]
1233 try:
1234 temp_fds = [fd for fd, fname in temps]
1235
1236 # unlink the files -- we won't need to reopen them
1237 for fd, fname in temps:
1238 os.unlink(fname)
1239
1240 # write some data to what will become stdin, and rewind
1241 os.write(temp_fds[1], b"STDIN")
1242 os.lseek(temp_fds[1], 0, 0)
1243
1244 # move the standard file descriptors out of the way
1245 saved_fds = [os.dup(fd) for fd in range(3)]
1246 try:
1247 # duplicate the file objects over the standard fd's
1248 for fd, temp_fd in enumerate(temp_fds):
1249 os.dup2(temp_fd, fd)
1250
1251 # now use those files in the "wrong" order, so that subprocess
1252 # has to rearrange them in the child
1253 p = subprocess.Popen([sys.executable, "-c",
1254 'import sys; got = sys.stdin.read();'
1255 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1256 stdin=temp_fds[1],
1257 stdout=temp_fds[2],
1258 stderr=temp_fds[0])
1259 p.wait()
1260 finally:
1261 # restore the original fd's underneath sys.stdin, etc.
1262 for std, saved in enumerate(saved_fds):
1263 os.dup2(saved, std)
1264 os.close(saved)
1265
1266 for fd in temp_fds:
1267 os.lseek(fd, 0, 0)
1268
1269 out = os.read(temp_fds[2], 1024)
1270 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1271 self.assertEqual(out, b"got STDIN")
1272 self.assertEqual(err, b"err")
1273
1274 finally:
1275 for fd in temp_fds:
1276 os.close(fd)
1277
Ross Lagerwalld98646e2011-07-27 07:16:31 +02001278 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
1279 # open up some temporary files
1280 temps = [mkstemp() for i in range(3)]
1281 temp_fds = [fd for fd, fname in temps]
1282 try:
1283 # unlink the files -- we won't need to reopen them
1284 for fd, fname in temps:
1285 os.unlink(fname)
1286
1287 # save a copy of the standard file descriptors
1288 saved_fds = [os.dup(fd) for fd in range(3)]
1289 try:
1290 # duplicate the temp files over the standard fd's 0, 1, 2
1291 for fd, temp_fd in enumerate(temp_fds):
1292 os.dup2(temp_fd, fd)
1293
1294 # write some data to what will become stdin, and rewind
1295 os.write(stdin_no, b"STDIN")
1296 os.lseek(stdin_no, 0, 0)
1297
1298 # now use those files in the given order, so that subprocess
1299 # has to rearrange them in the child
1300 p = subprocess.Popen([sys.executable, "-c",
1301 'import sys; got = sys.stdin.read();'
1302 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1303 stdin=stdin_no,
1304 stdout=stdout_no,
1305 stderr=stderr_no)
1306 p.wait()
1307
1308 for fd in temp_fds:
1309 os.lseek(fd, 0, 0)
1310
1311 out = os.read(stdout_no, 1024)
1312 err = support.strip_python_stderr(os.read(stderr_no, 1024))
1313 finally:
1314 for std, saved in enumerate(saved_fds):
1315 os.dup2(saved, std)
1316 os.close(saved)
1317
1318 self.assertEqual(out, b"got STDIN")
1319 self.assertEqual(err, b"err")
1320
1321 finally:
1322 for fd in temp_fds:
1323 os.close(fd)
1324
1325 # When duping fds, if there arises a situation where one of the fds is
1326 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
1327 # This tests all combinations of this.
1328 def test_swap_fds(self):
1329 self.check_swap_fds(0, 1, 2)
1330 self.check_swap_fds(0, 2, 1)
1331 self.check_swap_fds(1, 0, 2)
1332 self.check_swap_fds(1, 2, 0)
1333 self.check_swap_fds(2, 0, 1)
1334 self.check_swap_fds(2, 1, 0)
1335
Victor Stinner13bb71c2010-04-23 21:41:56 +00001336 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001337 def prepare():
1338 raise ValueError("surrogate:\uDCff")
1339
1340 try:
1341 subprocess.call(
1342 [sys.executable, "-c", "pass"],
1343 preexec_fn=prepare)
1344 except ValueError as err:
1345 # Pure Python implementations keeps the message
1346 self.assertIsNone(subprocess._posixsubprocess)
1347 self.assertEqual(str(err), "surrogate:\uDCff")
1348 except RuntimeError as err:
1349 # _posixsubprocess uses a default message
1350 self.assertIsNotNone(subprocess._posixsubprocess)
1351 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1352 else:
1353 self.fail("Expected ValueError or RuntimeError")
1354
Victor Stinner13bb71c2010-04-23 21:41:56 +00001355 def test_undecodable_env(self):
1356 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001357 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001358 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001359 env = os.environ.copy()
1360 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001361 # Use C locale to get ascii for the locale encoding to force
1362 # surrogate-escaping of \xFF in the child process; otherwise it can
1363 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001364 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001365 stdout = subprocess.check_output(
1366 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001367 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001368 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001369 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001370
1371 # test bytes
1372 key = key.encode("ascii", "surrogateescape")
1373 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001374 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001375 env = os.environ.copy()
1376 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001377 stdout = subprocess.check_output(
1378 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001379 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001380 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001381 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001382
Victor Stinnerb745a742010-05-18 17:17:23 +00001383 def test_bytes_program(self):
1384 abs_program = os.fsencode(sys.executable)
1385 path, program = os.path.split(sys.executable)
1386 program = os.fsencode(program)
1387
1388 # absolute bytes path
1389 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001390 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001391
Victor Stinner7b3b20a2011-03-03 12:54:05 +00001392 # absolute bytes path as a string
1393 cmd = b"'" + abs_program + b"' -c pass"
1394 exitcode = subprocess.call(cmd, shell=True)
1395 self.assertEqual(exitcode, 0)
1396
Victor Stinnerb745a742010-05-18 17:17:23 +00001397 # bytes program, unicode PATH
1398 env = os.environ.copy()
1399 env["PATH"] = path
1400 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001401 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001402
1403 # bytes program, bytes PATH
1404 envb = os.environb.copy()
1405 envb[b"PATH"] = os.fsencode(path)
1406 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001407 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001408
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001409 def test_pipe_cloexec(self):
1410 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1411 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1412
1413 p1 = subprocess.Popen([sys.executable, sleeper],
1414 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1415 stderr=subprocess.PIPE, close_fds=False)
1416
1417 self.addCleanup(p1.communicate, b'')
1418
1419 p2 = subprocess.Popen([sys.executable, fd_status],
1420 stdout=subprocess.PIPE, close_fds=False)
1421
1422 output, error = p2.communicate()
1423 result_fds = set(map(int, output.split(b',')))
1424 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1425 p1.stderr.fileno()])
1426
1427 self.assertFalse(result_fds & unwanted_fds,
1428 "Expected no fds from %r to be open in child, "
1429 "found %r" %
1430 (unwanted_fds, result_fds & unwanted_fds))
1431
1432 def test_pipe_cloexec_real_tools(self):
1433 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1434 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1435
1436 subdata = b'zxcvbn'
1437 data = subdata * 4 + b'\n'
1438
1439 p1 = subprocess.Popen([sys.executable, qcat],
1440 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1441 close_fds=False)
1442
1443 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1444 stdin=p1.stdout, stdout=subprocess.PIPE,
1445 close_fds=False)
1446
1447 self.addCleanup(p1.wait)
1448 self.addCleanup(p2.wait)
Gregory P. Smith886455c2012-01-21 22:05:10 -08001449 def kill_p1():
1450 try:
1451 p1.terminate()
1452 except ProcessLookupError:
1453 pass
1454 def kill_p2():
1455 try:
1456 p2.terminate()
1457 except ProcessLookupError:
1458 pass
1459 self.addCleanup(kill_p1)
1460 self.addCleanup(kill_p2)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001461
1462 p1.stdin.write(data)
1463 p1.stdin.close()
1464
1465 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1466
1467 self.assertTrue(readfiles, "The child hung")
1468 self.assertEqual(p2.stdout.read(), data)
1469
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001470 p1.stdout.close()
1471 p2.stdout.close()
1472
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001473 def test_close_fds(self):
1474 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1475
1476 fds = os.pipe()
1477 self.addCleanup(os.close, fds[0])
1478 self.addCleanup(os.close, fds[1])
1479
1480 open_fds = set(fds)
Gregory P. Smith8facece2012-01-21 14:01:08 -08001481 # add a bunch more fds
1482 for _ in range(9):
1483 fd = os.open("/dev/null", os.O_RDONLY)
1484 self.addCleanup(os.close, fd)
1485 open_fds.add(fd)
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001486
1487 p = subprocess.Popen([sys.executable, fd_status],
1488 stdout=subprocess.PIPE, close_fds=False)
1489 output, ignored = p.communicate()
1490 remaining_fds = set(map(int, output.split(b',')))
1491
1492 self.assertEqual(remaining_fds & open_fds, open_fds,
1493 "Some fds were closed")
1494
1495 p = subprocess.Popen([sys.executable, fd_status],
1496 stdout=subprocess.PIPE, close_fds=True)
1497 output, ignored = p.communicate()
1498 remaining_fds = set(map(int, output.split(b',')))
1499
1500 self.assertFalse(remaining_fds & open_fds,
1501 "Some fds were left open")
1502 self.assertIn(1, remaining_fds, "Subprocess failed")
1503
Gregory P. Smith8facece2012-01-21 14:01:08 -08001504 # Keep some of the fd's we opened open in the subprocess.
1505 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
1506 fds_to_keep = set(open_fds.pop() for _ in range(8))
1507 p = subprocess.Popen([sys.executable, fd_status],
1508 stdout=subprocess.PIPE, close_fds=True,
1509 pass_fds=())
1510 output, ignored = p.communicate()
1511 remaining_fds = set(map(int, output.split(b',')))
1512
1513 self.assertFalse(remaining_fds & fds_to_keep & open_fds,
1514 "Some fds not in pass_fds were left open")
1515 self.assertIn(1, remaining_fds, "Subprocess failed")
1516
Victor Stinner88701e22011-06-01 13:13:04 +02001517 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1518 # descriptor of a pipe closed in the parent process is valid in the
1519 # child process according to fstat(), but the mode of the file
1520 # descriptor is invalid, and read or write raise an error.
1521 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001522 def test_pass_fds(self):
1523 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1524
1525 open_fds = set()
1526
1527 for x in range(5):
1528 fds = os.pipe()
1529 self.addCleanup(os.close, fds[0])
1530 self.addCleanup(os.close, fds[1])
1531 open_fds.update(fds)
1532
1533 for fd in open_fds:
1534 p = subprocess.Popen([sys.executable, fd_status],
1535 stdout=subprocess.PIPE, close_fds=True,
1536 pass_fds=(fd, ))
1537 output, ignored = p.communicate()
1538
1539 remaining_fds = set(map(int, output.split(b',')))
1540 to_be_closed = open_fds - {fd}
1541
1542 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1543 self.assertFalse(remaining_fds & to_be_closed,
1544 "fd to be closed passed")
1545
1546 # pass_fds overrides close_fds with a warning.
1547 with self.assertWarns(RuntimeWarning) as context:
1548 self.assertFalse(subprocess.call(
1549 [sys.executable, "-c", "import sys; sys.exit(0)"],
1550 close_fds=False, pass_fds=(fd, )))
1551 self.assertIn('overriding close_fds', str(context.warning))
1552
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001553 def test_stdout_stdin_are_single_inout_fd(self):
1554 with io.open(os.devnull, "r+") as inout:
1555 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1556 stdout=inout, stdin=inout)
1557 p.wait()
1558
1559 def test_stdout_stderr_are_single_inout_fd(self):
1560 with io.open(os.devnull, "r+") as inout:
1561 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1562 stdout=inout, stderr=inout)
1563 p.wait()
1564
1565 def test_stderr_stdin_are_single_inout_fd(self):
1566 with io.open(os.devnull, "r+") as inout:
1567 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1568 stderr=inout, stdin=inout)
1569 p.wait()
1570
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001571 def test_wait_when_sigchild_ignored(self):
1572 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1573 sigchild_ignore = support.findfile("sigchild_ignore.py",
1574 subdir="subprocessdata")
1575 p = subprocess.Popen([sys.executable, sigchild_ignore],
1576 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1577 stdout, stderr = p.communicate()
1578 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001579 " non-zero with this error:\n%s" %
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001580 stderr.decode('utf-8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001581
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001582 def test_select_unbuffered(self):
1583 # Issue #11459: bufsize=0 should really set the pipes as
1584 # unbuffered (and therefore let select() work properly).
1585 select = support.import_module("select")
1586 p = subprocess.Popen([sys.executable, "-c",
1587 'import sys;'
1588 'sys.stdout.write("apple")'],
1589 stdout=subprocess.PIPE,
1590 bufsize=0)
1591 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001592 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001593 try:
1594 self.assertEqual(f.read(4), b"appl")
1595 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1596 finally:
1597 p.wait()
1598
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001599 def test_zombie_fast_process_del(self):
1600 # Issue #12650: on Unix, if Popen.__del__() was called before the
1601 # process exited, it wouldn't be added to subprocess._active, and would
1602 # remain a zombie.
1603 # spawn a Popen, and delete its reference before it exits
1604 p = subprocess.Popen([sys.executable, "-c",
1605 'import sys, time;'
1606 'time.sleep(0.2)'],
1607 stdout=subprocess.PIPE,
1608 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001609 self.addCleanup(p.stdout.close)
1610 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001611 ident = id(p)
1612 pid = p.pid
1613 del p
1614 # check that p is in the active processes list
1615 self.assertIn(ident, [id(o) for o in subprocess._active])
1616
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001617 def test_leak_fast_process_del_killed(self):
1618 # Issue #12650: on Unix, if Popen.__del__() was called before the
1619 # process exited, and the process got killed by a signal, it would never
1620 # be removed from subprocess._active, which triggered a FD and memory
1621 # leak.
1622 # spawn a Popen, delete its reference and kill it
1623 p = subprocess.Popen([sys.executable, "-c",
1624 'import time;'
1625 'time.sleep(3)'],
1626 stdout=subprocess.PIPE,
1627 stderr=subprocess.PIPE)
Nadeem Vawda0d7cda32011-08-19 05:12:01 +02001628 self.addCleanup(p.stdout.close)
1629 self.addCleanup(p.stderr.close)
Charles-François Natali134a8ba2011-08-18 18:49:39 +02001630 ident = id(p)
1631 pid = p.pid
1632 del p
1633 os.kill(pid, signal.SIGKILL)
1634 # check that p is in the active processes list
1635 self.assertIn(ident, [id(o) for o in subprocess._active])
1636
1637 # let some time for the process to exit, and create a new Popen: this
1638 # should trigger the wait() of p
1639 time.sleep(0.2)
1640 with self.assertRaises(EnvironmentError) as c:
1641 with subprocess.Popen(['nonexisting_i_hope'],
1642 stdout=subprocess.PIPE,
1643 stderr=subprocess.PIPE) as proc:
1644 pass
1645 # p should have been wait()ed on, and removed from the _active list
1646 self.assertRaises(OSError, os.waitpid, pid, 0)
1647 self.assertNotIn(ident, [id(o) for o in subprocess._active])
1648
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001649
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001650@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001651class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001652
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001653 def test_startupinfo(self):
1654 # startupinfo argument
1655 # We uses hardcoded constants, because we do not want to
1656 # depend on win32all.
1657 STARTF_USESHOWWINDOW = 1
1658 SW_MAXIMIZE = 3
1659 startupinfo = subprocess.STARTUPINFO()
1660 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1661 startupinfo.wShowWindow = SW_MAXIMIZE
1662 # Since Python is a console process, it won't be affected
1663 # by wShowWindow, but the argument should be silently
1664 # ignored
1665 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001666 startupinfo=startupinfo)
1667
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001668 def test_creationflags(self):
1669 # creationflags argument
1670 CREATE_NEW_CONSOLE = 16
1671 sys.stderr.write(" a DOS box should flash briefly ...\n")
1672 subprocess.call(sys.executable +
1673 ' -c "import time; time.sleep(0.25)"',
1674 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001675
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001676 def test_invalid_args(self):
1677 # invalid arguments should raise ValueError
1678 self.assertRaises(ValueError, subprocess.call,
1679 [sys.executable, "-c",
1680 "import sys; sys.exit(47)"],
1681 preexec_fn=lambda: 1)
1682 self.assertRaises(ValueError, subprocess.call,
1683 [sys.executable, "-c",
1684 "import sys; sys.exit(47)"],
1685 stdout=subprocess.PIPE,
1686 close_fds=True)
1687
1688 def test_close_fds(self):
1689 # close file descriptors
1690 rc = subprocess.call([sys.executable, "-c",
1691 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001692 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001693 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001694
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001695 def test_shell_sequence(self):
1696 # Run command through the shell (sequence)
1697 newenv = os.environ.copy()
1698 newenv["FRUIT"] = "physalis"
1699 p = subprocess.Popen(["set"], shell=1,
1700 stdout=subprocess.PIPE,
1701 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001702 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001703 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001704
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001705 def test_shell_string(self):
1706 # Run command through the shell (string)
1707 newenv = os.environ.copy()
1708 newenv["FRUIT"] = "physalis"
1709 p = subprocess.Popen("set", shell=1,
1710 stdout=subprocess.PIPE,
1711 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001712 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001713 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001714
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001715 def test_call_string(self):
1716 # call() function with string argument on Windows
1717 rc = subprocess.call(sys.executable +
1718 ' -c "import sys; sys.exit(47)"')
1719 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001720
Florent Xicluna4886d242010-03-08 13:27:26 +00001721 def _kill_process(self, method, *args):
1722 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001723 p = subprocess.Popen([sys.executable, "-c", """if 1:
1724 import sys, time
1725 sys.stdout.write('x\\n')
1726 sys.stdout.flush()
1727 time.sleep(30)
1728 """],
1729 stdin=subprocess.PIPE,
1730 stdout=subprocess.PIPE,
1731 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001732 self.addCleanup(p.stdout.close)
1733 self.addCleanup(p.stderr.close)
1734 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001735 # Wait for the interpreter to be completely initialized before
1736 # sending any signal.
1737 p.stdout.read(1)
1738 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001739 _, stderr = p.communicate()
1740 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001741 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001742 self.assertNotEqual(returncode, 0)
1743
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001744 def _kill_dead_process(self, method, *args):
1745 p = subprocess.Popen([sys.executable, "-c", """if 1:
1746 import sys, time
1747 sys.stdout.write('x\\n')
1748 sys.stdout.flush()
1749 sys.exit(42)
1750 """],
1751 stdin=subprocess.PIPE,
1752 stdout=subprocess.PIPE,
1753 stderr=subprocess.PIPE)
1754 self.addCleanup(p.stdout.close)
1755 self.addCleanup(p.stderr.close)
1756 self.addCleanup(p.stdin.close)
1757 # Wait for the interpreter to be completely initialized before
1758 # sending any signal.
1759 p.stdout.read(1)
1760 # The process should end after this
1761 time.sleep(1)
1762 # This shouldn't raise even though the child is now dead
1763 getattr(p, method)(*args)
1764 _, stderr = p.communicate()
1765 self.assertStderrEqual(stderr, b'')
1766 rc = p.wait()
1767 self.assertEqual(rc, 42)
1768
Florent Xicluna4886d242010-03-08 13:27:26 +00001769 def test_send_signal(self):
1770 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001771
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001772 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001773 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001774
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001775 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001776 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001777
Antoine Pitrou1f9a8352012-03-11 19:29:12 +01001778 def test_send_signal_dead(self):
1779 self._kill_dead_process('send_signal', signal.SIGTERM)
1780
1781 def test_kill_dead(self):
1782 self._kill_dead_process('kill')
1783
1784 def test_terminate_dead(self):
1785 self._kill_dead_process('terminate')
1786
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001787
Brett Cannona23810f2008-05-26 19:04:21 +00001788# The module says:
1789# "NB This only works (and is only relevant) for UNIX."
1790#
1791# Actually, getoutput should work on any platform with an os.popen, but
1792# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001793@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001794class CommandTests(unittest.TestCase):
1795 def test_getoutput(self):
1796 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1797 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1798 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001799
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001800 # we use mkdtemp in the next line to create an empty directory
1801 # under our exclusive control; from that, we can invent a pathname
1802 # that we _know_ won't exist. This is guaranteed to fail.
1803 dir = None
1804 try:
1805 dir = tempfile.mkdtemp()
1806 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001807
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001808 status, output = subprocess.getstatusoutput('cat ' + name)
1809 self.assertNotEqual(status, 0)
1810 finally:
1811 if dir is not None:
1812 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001813
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001814
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001815@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1816 "poll system call not supported")
1817class ProcessTestCaseNoPoll(ProcessTestCase):
1818 def setUp(self):
1819 subprocess._has_poll = False
1820 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001821
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001822 def tearDown(self):
1823 subprocess._has_poll = True
1824 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001825
1826
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001827class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001828 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001829 def test_eintr_retry_call(self):
1830 record_calls = []
1831 def fake_os_func(*args):
1832 record_calls.append(args)
1833 if len(record_calls) == 2:
1834 raise OSError(errno.EINTR, "fake interrupted system call")
1835 return tuple(reversed(args))
1836
1837 self.assertEqual((999, 256),
1838 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1839 self.assertEqual([(256, 999)], record_calls)
1840 # This time there will be an EINTR so it will loop once.
1841 self.assertEqual((666,),
1842 subprocess._eintr_retry_call(fake_os_func, 666))
1843 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1844
1845
Tim Golden126c2962010-08-11 14:20:40 +00001846@unittest.skipUnless(mswindows, "Windows-specific tests")
1847class CommandsWithSpaces (BaseTestCase):
1848
1849 def setUp(self):
1850 super().setUp()
1851 f, fname = mkstemp(".py", "te st")
1852 self.fname = fname.lower ()
1853 os.write(f, b"import sys;"
1854 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1855 )
1856 os.close(f)
1857
1858 def tearDown(self):
1859 os.remove(self.fname)
1860 super().tearDown()
1861
1862 def with_spaces(self, *args, **kwargs):
1863 kwargs['stdout'] = subprocess.PIPE
1864 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001865 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001866 self.assertEqual(
1867 p.stdout.read ().decode("mbcs"),
1868 "2 [%r, 'ab cd']" % self.fname
1869 )
1870
1871 def test_shell_string_with_spaces(self):
1872 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001873 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1874 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001875
1876 def test_shell_sequence_with_spaces(self):
1877 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001878 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001879
1880 def test_noshell_string_with_spaces(self):
1881 # call() function with string argument with spaces on Windows
1882 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1883 "ab cd"))
1884
1885 def test_noshell_sequence_with_spaces(self):
1886 # call() function with sequence argument with spaces on Windows
1887 self.with_spaces([sys.executable, self.fname, "ab cd"])
1888
Brian Curtin79cdb662010-12-03 02:46:02 +00001889
Georg Brandla86b2622012-02-20 21:34:57 +01001890class ContextManagerTests(BaseTestCase):
Brian Curtin79cdb662010-12-03 02:46:02 +00001891
1892 def test_pipe(self):
1893 with subprocess.Popen([sys.executable, "-c",
1894 "import sys;"
1895 "sys.stdout.write('stdout');"
1896 "sys.stderr.write('stderr');"],
1897 stdout=subprocess.PIPE,
1898 stderr=subprocess.PIPE) as proc:
1899 self.assertEqual(proc.stdout.read(), b"stdout")
1900 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1901
1902 self.assertTrue(proc.stdout.closed)
1903 self.assertTrue(proc.stderr.closed)
1904
1905 def test_returncode(self):
1906 with subprocess.Popen([sys.executable, "-c",
1907 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smith6b657452011-05-11 21:42:08 -07001908 pass
1909 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00001910 self.assertEqual(proc.returncode, 100)
1911
1912 def test_communicate_stdin(self):
1913 with subprocess.Popen([sys.executable, "-c",
1914 "import sys;"
1915 "sys.exit(sys.stdin.read() == 'context')"],
1916 stdin=subprocess.PIPE) as proc:
1917 proc.communicate(b"context")
1918 self.assertEqual(proc.returncode, 1)
1919
1920 def test_invalid_args(self):
1921 with self.assertRaises(EnvironmentError) as c:
1922 with subprocess.Popen(['nonexisting_i_hope'],
1923 stdout=subprocess.PIPE,
1924 stderr=subprocess.PIPE) as proc:
1925 pass
1926
1927 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1928 raise c.exception
1929
1930
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001931def test_main():
1932 unit_tests = (ProcessTestCase,
1933 POSIXProcessTestCase,
1934 Win32ProcessTestCase,
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001935 CommandTests,
1936 ProcessTestCaseNoPoll,
1937 HelperFunctionTests,
1938 CommandsWithSpaces,
Antoine Pitrouab85ff32011-07-23 22:03:45 +02001939 ContextManagerTests,
1940 )
Gregory P. Smith3b4652e2011-03-15 15:43:39 -04001941
1942 support.run_unittest(*unit_tests)
1943 support.reap_children()
1944
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001945if __name__ == "__main__":
Gregory P. Smith112bb3a2011-03-15 14:55:17 -04001946 unittest.main()