blob: 08f0ecfc1c4ed1681bc4142ddef2313306fafa71 [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. Smithe14e9c22011-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
Gregory P. Smith32ec9da2010-03-19 16:53:08 +000016try:
17 import gc
18except ImportError:
19 gc = None
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000020
21mswindows = (sys.platform == "win32")
22
23#
24# Depends on the following external programs: Python
25#
26
27if mswindows:
Tim Peters3b01a702004-10-12 22:19:32 +000028 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
29 'os.O_BINARY);')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000030else:
31 SETBINARY = ''
32
Florent Xiclunab1e94e82010-02-27 22:12:37 +000033
34try:
35 mkstemp = tempfile.mkstemp
36except AttributeError:
37 # tempfile.mkstemp is not available
38 def mkstemp():
39 """Replacement for mkstemp, calling mktemp."""
40 fname = tempfile.mktemp()
41 return os.open(fname, os.O_RDWR|os.O_CREAT), fname
42
Tim Peters3761e8d2004-10-13 04:07:12 +000043
Florent Xiclunac049d872010-03-27 22:47:23 +000044class BaseTestCase(unittest.TestCase):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000045 def setUp(self):
46 # Try to minimize the number of children we have so this test
47 # doesn't crash on some buildbots (Alphas in particular).
Florent Xiclunab1e94e82010-02-27 22:12:37 +000048 support.reap_children()
Thomas Wouters0e3f5912006-08-11 14:57:12 +000049
Florent Xiclunaf0cbd822010-03-04 21:50:56 +000050 def tearDown(self):
51 for inst in subprocess._active:
52 inst.wait()
53 subprocess._cleanup()
54 self.assertFalse(subprocess._active, "subprocess._active not empty")
55
Florent Xiclunab1e94e82010-02-27 22:12:37 +000056 def assertStderrEqual(self, stderr, expected, msg=None):
57 # In a debug build, stuff like "[6580 refs]" is printed to stderr at
58 # shutdown time. That frustrates tests trying to check stderr produced
59 # from a spawned Python process.
Antoine Pitrou62f68ed2010-08-04 11:48:56 +000060 actual = support.strip_python_stderr(stderr)
Florent Xiclunab1e94e82010-02-27 22:12:37 +000061 self.assertEqual(actual, expected, msg)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000062
Florent Xiclunac049d872010-03-27 22:47:23 +000063
64class ProcessTestCase(BaseTestCase):
65
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000066 def test_call_seq(self):
Tim Peters7b759da2004-10-12 22:29:54 +000067 # call() function with sequence argument
Tim Peters3b01a702004-10-12 22:19:32 +000068 rc = subprocess.call([sys.executable, "-c",
69 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +000070 self.assertEqual(rc, 47)
71
Peter Astrand454f7672005-01-01 09:36:35 +000072 def test_check_call_zero(self):
73 # check_call() function with zero return code
74 rc = subprocess.check_call([sys.executable, "-c",
75 "import sys; sys.exit(0)"])
76 self.assertEqual(rc, 0)
77
78 def test_check_call_nonzero(self):
79 # check_call() function with non-zero return code
Florent Xiclunab1e94e82010-02-27 22:12:37 +000080 with self.assertRaises(subprocess.CalledProcessError) as c:
Peter Astrand454f7672005-01-01 09:36:35 +000081 subprocess.check_call([sys.executable, "-c",
82 "import sys; sys.exit(47)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000083 self.assertEqual(c.exception.returncode, 47)
Peter Astrand454f7672005-01-01 09:36:35 +000084
Georg Brandlf9734072008-12-07 15:30:06 +000085 def test_check_output(self):
86 # check_output() function with zero return code
87 output = subprocess.check_output(
88 [sys.executable, "-c", "print('BDFL')"])
Benjamin Peterson577473f2010-01-19 00:09:57 +000089 self.assertIn(b'BDFL', output)
Georg Brandlf9734072008-12-07 15:30:06 +000090
91 def test_check_output_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:
Georg Brandlf9734072008-12-07 15:30:06 +000094 subprocess.check_output(
95 [sys.executable, "-c", "import sys; sys.exit(5)"])
Florent Xiclunab1e94e82010-02-27 22:12:37 +000096 self.assertEqual(c.exception.returncode, 5)
Georg Brandlf9734072008-12-07 15:30:06 +000097
98 def test_check_output_stderr(self):
99 # check_output() function stderr redirected to stdout
100 output = subprocess.check_output(
101 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
102 stderr=subprocess.STDOUT)
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_stdout_arg(self):
106 # check_output() function stderr redirected to stdout
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000107 with self.assertRaises(ValueError) as c:
Georg Brandlf9734072008-12-07 15:30:06 +0000108 output = subprocess.check_output(
109 [sys.executable, "-c", "print('will not be run')"],
110 stdout=sys.stdout)
Georg Brandlf9734072008-12-07 15:30:06 +0000111 self.fail("Expected ValueError when stdout arg supplied.")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000112 self.assertIn('stdout', c.exception.args[0])
Georg Brandlf9734072008-12-07 15:30:06 +0000113
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000114 def test_call_kwargs(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000115 # call() function with keyword args
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000116 newenv = os.environ.copy()
117 newenv["FRUIT"] = "banana"
118 rc = subprocess.call([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000119 'import sys, os;'
120 'sys.exit(os.getenv("FRUIT")=="banana")'],
121 env=newenv)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000122 self.assertEqual(rc, 1)
123
Victor Stinner87b9bc32011-06-01 00:57:47 +0200124 def test_invalid_args(self):
125 # Popen() called with invalid arguments should raise TypeError
126 # but Popen.__del__ should not complain (issue #12085)
127 with support.captured_stderr() as s:
128 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
129 argcount = subprocess.Popen.__init__.__code__.co_argcount
130 too_many_args = [0] * (argcount + 1)
131 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
132 self.assertEqual(s.getvalue(), '')
133
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000134 def test_stdin_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000135 # .stdin is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000136 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000137 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000138 self.addCleanup(p.stdout.close)
139 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000140 p.wait()
141 self.assertEqual(p.stdin, None)
142
143 def test_stdout_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000144 # .stdout is None when not redirected
Tim Peters29b6b4f2004-10-13 03:43:40 +0000145 p = subprocess.Popen([sys.executable, "-c",
Georg Brandl88fc6642007-02-09 21:28:07 +0000146 'print(" this bit of output is from a '
Tim Peters4052fe52004-10-13 03:29:54 +0000147 'test of stdout in a different '
Georg Brandl88fc6642007-02-09 21:28:07 +0000148 'process ...")'],
Tim Peters4052fe52004-10-13 03:29:54 +0000149 stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000150 self.addCleanup(p.stdin.close)
151 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000152 p.wait()
153 self.assertEqual(p.stdout, None)
154
155 def test_stderr_none(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000156 # .stderr is None when not redirected
Georg Brandl88fc6642007-02-09 21:28:07 +0000157 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000158 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000159 self.addCleanup(p.stdout.close)
160 self.addCleanup(p.stdin.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000161 p.wait()
162 self.assertEqual(p.stderr, None)
163
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000164 def test_executable_with_cwd(self):
Florent Xicluna1d1ab972010-03-11 01:53:10 +0000165 python_dir = os.path.dirname(os.path.realpath(sys.executable))
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000166 p = subprocess.Popen(["somethingyoudonthave", "-c",
167 "import sys; sys.exit(47)"],
168 executable=sys.executable, cwd=python_dir)
169 p.wait()
170 self.assertEqual(p.returncode, 47)
171
172 @unittest.skipIf(sysconfig.is_python_build(),
173 "need an installed Python. See #7774")
174 def test_executable_without_cwd(self):
175 # For a normal installation, it should work without 'cwd'
176 # argument. For test runs in the build directory, see #7774.
177 p = subprocess.Popen(["somethingyoudonthave", "-c",
178 "import sys; sys.exit(47)"],
Tim Peters3b01a702004-10-12 22:19:32 +0000179 executable=sys.executable)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000180 p.wait()
181 self.assertEqual(p.returncode, 47)
182
183 def test_stdin_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000184 # stdin redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000185 p = subprocess.Popen([sys.executable, "-c",
186 'import sys; sys.exit(sys.stdin.read() == "pear")'],
187 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000188 p.stdin.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000189 p.stdin.close()
190 p.wait()
191 self.assertEqual(p.returncode, 1)
192
193 def test_stdin_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000194 # stdin is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000195 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000196 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000197 d = tf.fileno()
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000198 os.write(d, b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000199 os.lseek(d, 0, 0)
200 p = subprocess.Popen([sys.executable, "-c",
201 'import sys; sys.exit(sys.stdin.read() == "pear")'],
202 stdin=d)
203 p.wait()
204 self.assertEqual(p.returncode, 1)
205
206 def test_stdin_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000207 # stdin is set to open file object
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000208 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000209 self.addCleanup(tf.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000210 tf.write(b"pear")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000211 tf.seek(0)
212 p = subprocess.Popen([sys.executable, "-c",
213 'import sys; sys.exit(sys.stdin.read() == "pear")'],
214 stdin=tf)
215 p.wait()
216 self.assertEqual(p.returncode, 1)
217
218 def test_stdout_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000219 # stdout redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000220 p = subprocess.Popen([sys.executable, "-c",
221 'import sys; sys.stdout.write("orange")'],
222 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000223 self.addCleanup(p.stdout.close)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000224 self.assertEqual(p.stdout.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000225
226 def test_stdout_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000227 # stdout 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()
231 p = subprocess.Popen([sys.executable, "-c",
232 'import sys; sys.stdout.write("orange")'],
233 stdout=d)
234 p.wait()
235 os.lseek(d, 0, 0)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000236 self.assertEqual(os.read(d, 1024), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000237
238 def test_stdout_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000239 # stdout is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000240 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000241 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000242 p = subprocess.Popen([sys.executable, "-c",
243 'import sys; sys.stdout.write("orange")'],
244 stdout=tf)
245 p.wait()
246 tf.seek(0)
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000247 self.assertEqual(tf.read(), b"orange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000248
249 def test_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000250 # stderr redirection
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000251 p = subprocess.Popen([sys.executable, "-c",
252 'import sys; sys.stderr.write("strawberry")'],
253 stderr=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000254 self.addCleanup(p.stderr.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000255 self.assertStderrEqual(p.stderr.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000256
257 def test_stderr_filedes(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000258 # stderr is set to open file descriptor
Tim Peterse718f612004-10-12 21:51:32 +0000259 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000260 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000261 d = tf.fileno()
262 p = subprocess.Popen([sys.executable, "-c",
263 'import sys; sys.stderr.write("strawberry")'],
264 stderr=d)
265 p.wait()
266 os.lseek(d, 0, 0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000267 self.assertStderrEqual(os.read(d, 1024), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000268
269 def test_stderr_fileobj(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000270 # stderr is set to open file object
Tim Peterse718f612004-10-12 21:51:32 +0000271 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000272 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000273 p = subprocess.Popen([sys.executable, "-c",
274 'import sys; sys.stderr.write("strawberry")'],
275 stderr=tf)
276 p.wait()
277 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000278 self.assertStderrEqual(tf.read(), b"strawberry")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000279
280 def test_stdout_stderr_pipe(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000281 # capture stdout and stderr to the same pipe
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000282 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000283 'import sys;'
284 'sys.stdout.write("apple");'
285 'sys.stdout.flush();'
286 'sys.stderr.write("orange")'],
287 stdout=subprocess.PIPE,
288 stderr=subprocess.STDOUT)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000289 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000290 self.assertStderrEqual(p.stdout.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000291
292 def test_stdout_stderr_file(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000293 # capture stdout and stderr to the same open file
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000294 tf = tempfile.TemporaryFile()
Benjamin Petersoncc221b22010-10-31 02:06:21 +0000295 self.addCleanup(tf.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000296 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000297 'import sys;'
298 'sys.stdout.write("apple");'
299 'sys.stdout.flush();'
300 'sys.stderr.write("orange")'],
301 stdout=tf,
302 stderr=tf)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000303 p.wait()
304 tf.seek(0)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000305 self.assertStderrEqual(tf.read(), b"appleorange")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000306
Thomas Wouters89f507f2006-12-13 04:49:30 +0000307 def test_stdout_filedes_of_stdout(self):
308 # stdout is set to 1 (#1531862).
Antoine Pitrou9cadb1b2008-09-15 23:02:56 +0000309 cmd = r"import sys, os; sys.exit(os.write(sys.stdout.fileno(), b'.\n'))"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000310 rc = subprocess.call([sys.executable, "-c", cmd], stdout=1)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000311 self.assertEqual(rc, 2)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000312
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000313 def test_cwd(self):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000314 tmpdir = tempfile.gettempdir()
Peter Astrand195404f2004-11-12 15:51:48 +0000315 # We cannot use os.path.realpath to canonicalize the path,
316 # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
317 cwd = os.getcwd()
318 os.chdir(tmpdir)
319 tmpdir = os.getcwd()
320 os.chdir(cwd)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000321 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000322 'import sys,os;'
323 'sys.stdout.write(os.getcwd())'],
324 stdout=subprocess.PIPE,
325 cwd=tmpdir)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000326 self.addCleanup(p.stdout.close)
Fredrik Lundh59c05592004-10-13 06:55:40 +0000327 normcase = os.path.normcase
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000328 self.assertEqual(normcase(p.stdout.read().decode("utf-8")),
329 normcase(tmpdir))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000330
331 def test_env(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000332 newenv = os.environ.copy()
333 newenv["FRUIT"] = "orange"
Victor Stinnerf1512a22011-06-21 17:18:38 +0200334 with subprocess.Popen([sys.executable, "-c",
335 'import sys,os;'
336 'sys.stdout.write(os.getenv("FRUIT"))'],
337 stdout=subprocess.PIPE,
338 env=newenv) as p:
339 stdout, stderr = p.communicate()
340 self.assertEqual(stdout, b"orange")
341
Victor Stinner62d51182011-06-23 01:02:25 +0200342 # Windows requires at least the SYSTEMROOT environment variable to start
343 # Python
344 @unittest.skipIf(sys.platform == 'win32',
345 'cannot test an empty env on Windows')
Victor Stinner237e5cb2011-06-22 21:28:43 +0200346 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') is not None,
Victor Stinner372309a2011-06-21 21:59:06 +0200347 'the python library cannot be loaded '
348 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200349 def test_empty_env(self):
350 with subprocess.Popen([sys.executable, "-c",
351 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200352 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200353 stdout=subprocess.PIPE,
354 env={}) as p:
355 stdout, stderr = p.communicate()
Victor Stinner237e5cb2011-06-22 21:28:43 +0200356 self.assertIn(stdout.strip(),
357 (b"[]",
358 # Mac OS X adds __CF_USER_TEXT_ENCODING variable to an empty
359 # environment
360 b"['__CF_USER_TEXT_ENCODING']"))
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000361
Peter Astrandcbac93c2005-03-03 20:24:28 +0000362 def test_communicate_stdin(self):
363 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000364 'import sys;'
365 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000366 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000367 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000368 self.assertEqual(p.returncode, 1)
369
370 def test_communicate_stdout(self):
371 p = subprocess.Popen([sys.executable, "-c",
372 'import sys; sys.stdout.write("pineapple")'],
373 stdout=subprocess.PIPE)
374 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000375 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000376 self.assertEqual(stderr, None)
377
378 def test_communicate_stderr(self):
379 p = subprocess.Popen([sys.executable, "-c",
380 'import sys; sys.stderr.write("pineapple")'],
381 stderr=subprocess.PIPE)
382 (stdout, stderr) = p.communicate()
383 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000384 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000385
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000386 def test_communicate(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000387 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000388 'import sys,os;'
389 'sys.stderr.write("pineapple");'
390 'sys.stdout.write(sys.stdin.read())'],
391 stdin=subprocess.PIPE,
392 stdout=subprocess.PIPE,
393 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000394 self.addCleanup(p.stdout.close)
395 self.addCleanup(p.stderr.close)
396 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000397 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000398 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000399 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000400
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000401 # Test for the fd leak reported in http://bugs.python.org/issue2791.
402 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000403 for stdin_pipe in (False, True):
404 for stdout_pipe in (False, True):
405 for stderr_pipe in (False, True):
406 options = {}
407 if stdin_pipe:
408 options['stdin'] = subprocess.PIPE
409 if stdout_pipe:
410 options['stdout'] = subprocess.PIPE
411 if stderr_pipe:
412 options['stderr'] = subprocess.PIPE
413 if not options:
414 continue
415 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
416 p.communicate()
417 if p.stdin is not None:
418 self.assertTrue(p.stdin.closed)
419 if p.stdout is not None:
420 self.assertTrue(p.stdout.closed)
421 if p.stderr is not None:
422 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000423
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000424 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000425 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000426 p = subprocess.Popen([sys.executable, "-c",
427 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000428 (stdout, stderr) = p.communicate()
429 self.assertEqual(stdout, None)
430 self.assertEqual(stderr, None)
431
432 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000433 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000434 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000435 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000436 x, y = os.pipe()
437 if mswindows:
438 pipe_buf = 512
439 else:
440 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
441 os.close(x)
442 os.close(y)
443 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000444 'import sys,os;'
445 'sys.stdout.write(sys.stdin.read(47));'
446 'sys.stderr.write("xyz"*%d);'
447 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
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)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000454 string_to_write = b"abc"*pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000455 (stdout, stderr) = p.communicate(string_to_write)
456 self.assertEqual(stdout, string_to_write)
457
458 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000459 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000460 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000461 'import sys,os;'
462 'sys.stdout.write(sys.stdin.read())'],
463 stdin=subprocess.PIPE,
464 stdout=subprocess.PIPE,
465 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000466 self.addCleanup(p.stdout.close)
467 self.addCleanup(p.stderr.close)
468 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000469 p.stdin.write(b"banana")
470 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000471 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000472 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000473
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000474 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000475 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000476 'import sys,os;' + SETBINARY +
477 'sys.stdout.write("line1\\n");'
478 'sys.stdout.flush();'
479 'sys.stdout.write("line2\\n");'
480 'sys.stdout.flush();'
481 'sys.stdout.write("line3\\r\\n");'
482 'sys.stdout.flush();'
483 'sys.stdout.write("line4\\r");'
484 'sys.stdout.flush();'
485 'sys.stdout.write("\\nline5");'
486 'sys.stdout.flush();'
487 'sys.stdout.write("\\nline6");'],
488 stdout=subprocess.PIPE,
489 universal_newlines=1)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000490 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000491 stdout = p.stdout.read()
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000492 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000493
494 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000495 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000496 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000497 'import sys,os;' + SETBINARY +
498 'sys.stdout.write("line1\\n");'
499 'sys.stdout.flush();'
500 'sys.stdout.write("line2\\n");'
501 'sys.stdout.flush();'
502 'sys.stdout.write("line3\\r\\n");'
503 'sys.stdout.flush();'
504 'sys.stdout.write("line4\\r");'
505 'sys.stdout.flush();'
506 'sys.stdout.write("\\nline5");'
507 'sys.stdout.flush();'
508 'sys.stdout.write("\\nline6");'],
509 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
510 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000511 self.addCleanup(p.stdout.close)
512 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000513 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000514 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000515
516 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000517 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000518 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000519 max_handles = 1026 # too much for most UNIX systems
520 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000521 max_handles = 2050 # too much for (at least some) Windows setups
522 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400523 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000524 try:
525 for i in range(max_handles):
526 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400527 tmpfile = os.path.join(tmpdir, support.TESTFN)
528 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000529 except OSError as e:
530 if e.errno != errno.EMFILE:
531 raise
532 break
533 else:
534 self.skipTest("failed to reach the file descriptor limit "
535 "(tried %d)" % max_handles)
536 # Close a couple of them (should be enough for a subprocess)
537 for i in range(10):
538 os.close(handles.pop())
539 # Loop creating some subprocesses. If one of them leaks some fds,
540 # the next loop iteration will fail by reaching the max fd limit.
541 for i in range(15):
542 p = subprocess.Popen([sys.executable, "-c",
543 "import sys;"
544 "sys.stdout.write(sys.stdin.read())"],
545 stdin=subprocess.PIPE,
546 stdout=subprocess.PIPE,
547 stderr=subprocess.PIPE)
548 data = p.communicate(b"lime")[0]
549 self.assertEqual(data, b"lime")
550 finally:
551 for h in handles:
552 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400553 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000554
555 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000556 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
557 '"a b c" d e')
558 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
559 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000560 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
561 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000562 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
563 'a\\\\\\b "de fg" h')
564 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
565 'a\\\\\\"b c d')
566 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
567 '"a\\\\b c" d e')
568 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
569 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000570 self.assertEqual(subprocess.list2cmdline(['ab', '']),
571 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000572
573
574 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000575 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000576 "-c", "import time; time.sleep(1)"])
577 count = 0
578 while p.poll() is None:
579 time.sleep(0.1)
580 count += 1
581 # We expect that the poll loop probably went around about 10 times,
582 # but, based on system scheduling we can't control, it's possible
583 # poll() never returned None. It "should be" very rare that it
584 # didn't go around at least twice.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000585 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000586 # Subsequent invocations should just return the returncode
587 self.assertEqual(p.poll(), 0)
588
589
590 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000591 p = subprocess.Popen([sys.executable,
592 "-c", "import time; time.sleep(2)"])
593 self.assertEqual(p.wait(), 0)
594 # Subsequent invocations should just return the returncode
595 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000596
Peter Astrand738131d2004-11-30 21:04:45 +0000597
598 def test_invalid_bufsize(self):
599 # an invalid type of the bufsize argument should raise
600 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000601 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000602 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000603
Guido van Rossum46a05a72007-06-07 21:56:45 +0000604 def test_bufsize_is_none(self):
605 # bufsize=None should be the same as bufsize=0.
606 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
607 self.assertEqual(p.wait(), 0)
608 # Again with keyword arg
609 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
610 self.assertEqual(p.wait(), 0)
611
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000612 def test_leaking_fds_on_error(self):
613 # see bug #5179: Popen leaks file descriptors to PIPEs if
614 # the child fails to execute; this will eventually exhaust
615 # the maximum number of open fds. 1024 seems a very common
616 # value for that limit, but Windows has 2048, so we loop
617 # 1024 times (each call leaked two fds).
618 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000619 # Windows raises IOError. Others raise OSError.
620 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000621 subprocess.Popen(['nonexisting_i_hope'],
622 stdout=subprocess.PIPE,
623 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400624 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400625 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000626 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000627
Victor Stinnerb3693582010-05-21 20:13:12 +0000628 def test_issue8780(self):
629 # Ensure that stdout is inherited from the parent
630 # if stdout=PIPE is not used
631 code = ';'.join((
632 'import subprocess, sys',
633 'retcode = subprocess.call('
634 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
635 'assert retcode == 0'))
636 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000637 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000638
Tim Goldenaf5ac392010-08-06 13:03:56 +0000639 def test_handles_closed_on_exception(self):
640 # If CreateProcess exits with an error, ensure the
641 # duplicate output handles are released
642 ifhandle, ifname = mkstemp()
643 ofhandle, ofname = mkstemp()
644 efhandle, efname = mkstemp()
645 try:
646 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
647 stderr=efhandle)
648 except OSError:
649 os.close(ifhandle)
650 os.remove(ifname)
651 os.close(ofhandle)
652 os.remove(ofname)
653 os.close(efhandle)
654 os.remove(efname)
655 self.assertFalse(os.path.exists(ifname))
656 self.assertFalse(os.path.exists(ofname))
657 self.assertFalse(os.path.exists(efname))
658
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200659 def test_communicate_epipe(self):
660 # Issue 10963: communicate() should hide EPIPE
661 p = subprocess.Popen([sys.executable, "-c", 'pass'],
662 stdin=subprocess.PIPE,
663 stdout=subprocess.PIPE,
664 stderr=subprocess.PIPE)
665 self.addCleanup(p.stdout.close)
666 self.addCleanup(p.stderr.close)
667 self.addCleanup(p.stdin.close)
668 p.communicate(b"x" * 2**20)
669
670 def test_communicate_epipe_only_stdin(self):
671 # Issue 10963: communicate() should hide EPIPE
672 p = subprocess.Popen([sys.executable, "-c", 'pass'],
673 stdin=subprocess.PIPE)
674 self.addCleanup(p.stdin.close)
675 time.sleep(2)
676 p.communicate(b"x" * 2**20)
677
Victor Stinner1848db82011-07-05 14:49:46 +0200678 @unittest.skipUnless(hasattr(signal, 'SIGALRM'),
679 "Requires signal.SIGALRM")
Victor Stinner2cfb6f32011-07-05 14:00:56 +0200680 def test_communicate_eintr(self):
681 # Issue #12493: communicate() should handle EINTR
682 def handler(signum, frame):
683 pass
684 old_handler = signal.signal(signal.SIGALRM, handler)
685 self.addCleanup(signal.signal, signal.SIGALRM, old_handler)
686
687 # the process is running for 2 seconds
688 args = [sys.executable, "-c", 'import time; time.sleep(2)']
689 for stream in ('stdout', 'stderr'):
690 kw = {stream: subprocess.PIPE}
691 with subprocess.Popen(args, **kw) as process:
692 signal.alarm(1)
693 # communicate() will be interrupted by SIGALRM
694 process.communicate()
695
Tim Peterse718f612004-10-12 21:51:32 +0000696
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000697# context manager
698class _SuppressCoreFiles(object):
699 """Try to prevent core files from being created."""
700 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000701
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000702 def __enter__(self):
703 """Try to save previous ulimit, then set it to (0, 0)."""
704 try:
705 import resource
706 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
707 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
708 except (ImportError, ValueError, resource.error):
709 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000710
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000711 if sys.platform == 'darwin':
712 # Check if the 'Crash Reporter' on OSX was configured
713 # in 'Developer' mode and warn that it will get triggered
714 # when it is.
715 #
716 # This assumes that this context manager is used in tests
717 # that might trigger the next manager.
718 value = subprocess.Popen(['/usr/bin/defaults', 'read',
719 'com.apple.CrashReporter', 'DialogType'],
720 stdout=subprocess.PIPE).communicate()[0]
721 if value.strip() == b'developer':
722 print("this tests triggers the Crash Reporter, "
723 "that is intentional", end='')
724 sys.stdout.flush()
725
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000726 def __exit__(self, *args):
727 """Return core file behavior to default."""
728 if self.old_limit is None:
729 return
730 try:
731 import resource
732 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
733 except (ImportError, ValueError, resource.error):
734 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000735
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000736
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000737@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000738class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000739
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000740 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000741 nonexistent_dir = "/_this/pa.th/does/not/exist"
742 try:
743 os.chdir(nonexistent_dir)
744 except OSError as e:
745 # This avoids hard coding the errno value or the OS perror()
746 # string and instead capture the exception that we want to see
747 # below for comparison.
748 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000749 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000750 else:
751 self.fail("chdir to nonexistant directory %s succeeded." %
752 nonexistent_dir)
753
754 # Error in the child re-raised in the parent.
755 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000756 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000757 cwd=nonexistent_dir)
758 except OSError as e:
759 # Test that the child process chdir failure actually makes
760 # it up to the parent process as the correct exception.
761 self.assertEqual(desired_exception.errno, e.errno)
762 self.assertEqual(desired_exception.strerror, e.strerror)
763 else:
764 self.fail("Expected OSError: %s" % desired_exception)
765
766 def test_restore_signals(self):
767 # Code coverage for both values of restore_signals to make sure it
768 # at least does not blow up.
769 # A test for behavior would be complex. Contributions welcome.
770 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
771 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
772
773 def test_start_new_session(self):
774 # For code coverage of calling setsid(). We don't care if we get an
775 # EPERM error from it depending on the test execution environment, that
776 # still indicates that it was called.
777 try:
778 output = subprocess.check_output(
779 [sys.executable, "-c",
780 "import os; print(os.getpgid(os.getpid()))"],
781 start_new_session=True)
782 except OSError as e:
783 if e.errno != errno.EPERM:
784 raise
785 else:
786 parent_pgid = os.getpgid(os.getpid())
787 child_pgid = int(output)
788 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000789
790 def test_run_abort(self):
791 # returncode handles signal termination
792 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000793 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000794 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000795 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000796 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000797
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000798 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000799 # DISCLAIMER: Setting environment variables is *not* a good use
800 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000801 p = subprocess.Popen([sys.executable, "-c",
802 'import sys,os;'
803 'sys.stdout.write(os.getenv("FRUIT"))'],
804 stdout=subprocess.PIPE,
805 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000806 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000807 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000808
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000809 def test_preexec_exception(self):
810 def raise_it():
811 raise ValueError("What if two swallows carried a coconut?")
812 try:
813 p = subprocess.Popen([sys.executable, "-c", ""],
814 preexec_fn=raise_it)
815 except RuntimeError as e:
816 self.assertTrue(
817 subprocess._posixsubprocess,
818 "Expected a ValueError from the preexec_fn")
819 except ValueError as e:
820 self.assertIn("coconut", e.args[0])
821 else:
822 self.fail("Exception raised by preexec_fn did not make it "
823 "to the parent process.")
824
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000825 @unittest.skipUnless(gc, "Requires a gc module.")
826 def test_preexec_gc_module_failure(self):
827 # This tests the code that disables garbage collection if the child
828 # process will execute any Python.
829 def raise_runtime_error():
830 raise RuntimeError("this shouldn't escape")
831 enabled = gc.isenabled()
832 orig_gc_disable = gc.disable
833 orig_gc_isenabled = gc.isenabled
834 try:
835 gc.disable()
836 self.assertFalse(gc.isenabled())
837 subprocess.call([sys.executable, '-c', ''],
838 preexec_fn=lambda: None)
839 self.assertFalse(gc.isenabled(),
840 "Popen enabled gc when it shouldn't.")
841
842 gc.enable()
843 self.assertTrue(gc.isenabled())
844 subprocess.call([sys.executable, '-c', ''],
845 preexec_fn=lambda: None)
846 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
847
848 gc.disable = raise_runtime_error
849 self.assertRaises(RuntimeError, subprocess.Popen,
850 [sys.executable, '-c', ''],
851 preexec_fn=lambda: None)
852
853 del gc.isenabled # force an AttributeError
854 self.assertRaises(AttributeError, subprocess.Popen,
855 [sys.executable, '-c', ''],
856 preexec_fn=lambda: None)
857 finally:
858 gc.disable = orig_gc_disable
859 gc.isenabled = orig_gc_isenabled
860 if not enabled:
861 gc.disable()
862
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000863 def test_args_string(self):
864 # args is a string
865 fd, fname = mkstemp()
866 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000867 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000868 fobj.write("#!/bin/sh\n")
869 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
870 sys.executable)
871 os.chmod(fname, 0o700)
872 p = subprocess.Popen(fname)
873 p.wait()
874 os.remove(fname)
875 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000876
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000877 def test_invalid_args(self):
878 # invalid arguments should raise ValueError
879 self.assertRaises(ValueError, subprocess.call,
880 [sys.executable, "-c",
881 "import sys; sys.exit(47)"],
882 startupinfo=47)
883 self.assertRaises(ValueError, subprocess.call,
884 [sys.executable, "-c",
885 "import sys; sys.exit(47)"],
886 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000887
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000888 def test_shell_sequence(self):
889 # Run command through the shell (sequence)
890 newenv = os.environ.copy()
891 newenv["FRUIT"] = "apple"
892 p = subprocess.Popen(["echo $FRUIT"], shell=1,
893 stdout=subprocess.PIPE,
894 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000895 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000896 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000897
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000898 def test_shell_string(self):
899 # Run command through the shell (string)
900 newenv = os.environ.copy()
901 newenv["FRUIT"] = "apple"
902 p = subprocess.Popen("echo $FRUIT", shell=1,
903 stdout=subprocess.PIPE,
904 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000905 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000906 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +0000907
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000908 def test_call_string(self):
909 # call() function with string argument on UNIX
910 fd, fname = mkstemp()
911 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000912 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000913 fobj.write("#!/bin/sh\n")
914 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
915 sys.executable)
916 os.chmod(fname, 0o700)
917 rc = subprocess.call(fname)
918 os.remove(fname)
919 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +0000920
Stefan Krah9542cc62010-07-19 14:20:53 +0000921 def test_specific_shell(self):
922 # Issue #9265: Incorrect name passed as arg[0].
923 shells = []
924 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
925 for name in ['bash', 'ksh']:
926 sh = os.path.join(prefix, name)
927 if os.path.isfile(sh):
928 shells.append(sh)
929 if not shells: # Will probably work for any shell but csh.
930 self.skipTest("bash or ksh required for this test")
931 sh = '/bin/sh'
932 if os.path.isfile(sh) and not os.path.islink(sh):
933 # Test will fail if /bin/sh is a symlink to csh.
934 shells.append(sh)
935 for sh in shells:
936 p = subprocess.Popen("echo $0", executable=sh, shell=True,
937 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000938 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +0000939 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
940
Florent Xicluna4886d242010-03-08 13:27:26 +0000941 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +0000942 # Do not inherit file handles from the parent.
943 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +0000944 p = subprocess.Popen([sys.executable, "-c", """if 1:
945 import sys, time
946 sys.stdout.write('x\\n')
947 sys.stdout.flush()
948 time.sleep(30)
949 """],
950 close_fds=True,
951 stdin=subprocess.PIPE,
952 stdout=subprocess.PIPE,
953 stderr=subprocess.PIPE)
954 # Wait for the interpreter to be completely initialized before
955 # sending any signal.
956 p.stdout.read(1)
957 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +0000958 return p
959
960 def test_send_signal(self):
961 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +0000962 _, stderr = p.communicate()
963 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000964 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +0000965
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000966 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000967 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +0000968 _, stderr = p.communicate()
969 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000970 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +0000971
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000972 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000973 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +0000974 _, stderr = p.communicate()
975 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000976 self.assertEqual(p.wait(), -signal.SIGTERM)
977
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000978 def check_close_std_fds(self, fds):
979 # Issue #9905: test that subprocess pipes still work properly with
980 # some standard fds closed
981 stdin = 0
982 newfds = []
983 for a in fds:
984 b = os.dup(a)
985 newfds.append(b)
986 if a == 0:
987 stdin = b
988 try:
989 for fd in fds:
990 os.close(fd)
991 out, err = subprocess.Popen([sys.executable, "-c",
992 'import sys;'
993 'sys.stdout.write("apple");'
994 'sys.stdout.flush();'
995 'sys.stderr.write("orange")'],
996 stdin=stdin,
997 stdout=subprocess.PIPE,
998 stderr=subprocess.PIPE).communicate()
999 err = support.strip_python_stderr(err)
1000 self.assertEqual((out, err), (b'apple', b'orange'))
1001 finally:
1002 for b, a in zip(newfds, fds):
1003 os.dup2(b, a)
1004 for b in newfds:
1005 os.close(b)
1006
1007 def test_close_fd_0(self):
1008 self.check_close_std_fds([0])
1009
1010 def test_close_fd_1(self):
1011 self.check_close_std_fds([1])
1012
1013 def test_close_fd_2(self):
1014 self.check_close_std_fds([2])
1015
1016 def test_close_fds_0_1(self):
1017 self.check_close_std_fds([0, 1])
1018
1019 def test_close_fds_0_2(self):
1020 self.check_close_std_fds([0, 2])
1021
1022 def test_close_fds_1_2(self):
1023 self.check_close_std_fds([1, 2])
1024
1025 def test_close_fds_0_1_2(self):
1026 # Issue #10806: test that subprocess pipes still work properly with
1027 # all standard fds closed.
1028 self.check_close_std_fds([0, 1, 2])
1029
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001030 def test_remapping_std_fds(self):
1031 # open up some temporary files
1032 temps = [mkstemp() for i in range(3)]
1033 try:
1034 temp_fds = [fd for fd, fname in temps]
1035
1036 # unlink the files -- we won't need to reopen them
1037 for fd, fname in temps:
1038 os.unlink(fname)
1039
1040 # write some data to what will become stdin, and rewind
1041 os.write(temp_fds[1], b"STDIN")
1042 os.lseek(temp_fds[1], 0, 0)
1043
1044 # move the standard file descriptors out of the way
1045 saved_fds = [os.dup(fd) for fd in range(3)]
1046 try:
1047 # duplicate the file objects over the standard fd's
1048 for fd, temp_fd in enumerate(temp_fds):
1049 os.dup2(temp_fd, fd)
1050
1051 # now use those files in the "wrong" order, so that subprocess
1052 # has to rearrange them in the child
1053 p = subprocess.Popen([sys.executable, "-c",
1054 'import sys; got = sys.stdin.read();'
1055 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1056 stdin=temp_fds[1],
1057 stdout=temp_fds[2],
1058 stderr=temp_fds[0])
1059 p.wait()
1060 finally:
1061 # restore the original fd's underneath sys.stdin, etc.
1062 for std, saved in enumerate(saved_fds):
1063 os.dup2(saved, std)
1064 os.close(saved)
1065
1066 for fd in temp_fds:
1067 os.lseek(fd, 0, 0)
1068
1069 out = os.read(temp_fds[2], 1024)
1070 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1071 self.assertEqual(out, b"got STDIN")
1072 self.assertEqual(err, b"err")
1073
1074 finally:
1075 for fd in temp_fds:
1076 os.close(fd)
1077
Victor Stinner13bb71c2010-04-23 21:41:56 +00001078 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001079 def prepare():
1080 raise ValueError("surrogate:\uDCff")
1081
1082 try:
1083 subprocess.call(
1084 [sys.executable, "-c", "pass"],
1085 preexec_fn=prepare)
1086 except ValueError as err:
1087 # Pure Python implementations keeps the message
1088 self.assertIsNone(subprocess._posixsubprocess)
1089 self.assertEqual(str(err), "surrogate:\uDCff")
1090 except RuntimeError as err:
1091 # _posixsubprocess uses a default message
1092 self.assertIsNotNone(subprocess._posixsubprocess)
1093 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1094 else:
1095 self.fail("Expected ValueError or RuntimeError")
1096
Victor Stinner13bb71c2010-04-23 21:41:56 +00001097 def test_undecodable_env(self):
1098 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001099 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001100 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001101 env = os.environ.copy()
1102 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001103 # Use C locale to get ascii for the locale encoding to force
1104 # surrogate-escaping of \xFF in the child process; otherwise it can
1105 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001106 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001107 stdout = subprocess.check_output(
1108 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001109 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001110 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001111 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001112
1113 # test bytes
1114 key = key.encode("ascii", "surrogateescape")
1115 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001116 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001117 env = os.environ.copy()
1118 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001119 stdout = subprocess.check_output(
1120 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001121 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001122 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001123 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001124
Victor Stinnerb745a742010-05-18 17:17:23 +00001125 def test_bytes_program(self):
1126 abs_program = os.fsencode(sys.executable)
1127 path, program = os.path.split(sys.executable)
1128 program = os.fsencode(program)
1129
1130 # absolute bytes path
1131 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001132 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001133
1134 # bytes program, unicode PATH
1135 env = os.environ.copy()
1136 env["PATH"] = path
1137 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001138 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001139
1140 # bytes program, bytes PATH
1141 envb = os.environb.copy()
1142 envb[b"PATH"] = os.fsencode(path)
1143 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001144 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001145
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001146 def test_pipe_cloexec(self):
1147 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1148 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1149
1150 p1 = subprocess.Popen([sys.executable, sleeper],
1151 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1152 stderr=subprocess.PIPE, close_fds=False)
1153
1154 self.addCleanup(p1.communicate, b'')
1155
1156 p2 = subprocess.Popen([sys.executable, fd_status],
1157 stdout=subprocess.PIPE, close_fds=False)
1158
1159 output, error = p2.communicate()
1160 result_fds = set(map(int, output.split(b',')))
1161 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1162 p1.stderr.fileno()])
1163
1164 self.assertFalse(result_fds & unwanted_fds,
1165 "Expected no fds from %r to be open in child, "
1166 "found %r" %
1167 (unwanted_fds, result_fds & unwanted_fds))
1168
1169 def test_pipe_cloexec_real_tools(self):
1170 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1171 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1172
1173 subdata = b'zxcvbn'
1174 data = subdata * 4 + b'\n'
1175
1176 p1 = subprocess.Popen([sys.executable, qcat],
1177 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1178 close_fds=False)
1179
1180 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1181 stdin=p1.stdout, stdout=subprocess.PIPE,
1182 close_fds=False)
1183
1184 self.addCleanup(p1.wait)
1185 self.addCleanup(p2.wait)
1186 self.addCleanup(p1.terminate)
1187 self.addCleanup(p2.terminate)
1188
1189 p1.stdin.write(data)
1190 p1.stdin.close()
1191
1192 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1193
1194 self.assertTrue(readfiles, "The child hung")
1195 self.assertEqual(p2.stdout.read(), data)
1196
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001197 p1.stdout.close()
1198 p2.stdout.close()
1199
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001200 def test_close_fds(self):
1201 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1202
1203 fds = os.pipe()
1204 self.addCleanup(os.close, fds[0])
1205 self.addCleanup(os.close, fds[1])
1206
1207 open_fds = set(fds)
1208
1209 p = subprocess.Popen([sys.executable, fd_status],
1210 stdout=subprocess.PIPE, close_fds=False)
1211 output, ignored = p.communicate()
1212 remaining_fds = set(map(int, output.split(b',')))
1213
1214 self.assertEqual(remaining_fds & open_fds, open_fds,
1215 "Some fds were closed")
1216
1217 p = subprocess.Popen([sys.executable, fd_status],
1218 stdout=subprocess.PIPE, close_fds=True)
1219 output, ignored = p.communicate()
1220 remaining_fds = set(map(int, output.split(b',')))
1221
1222 self.assertFalse(remaining_fds & open_fds,
1223 "Some fds were left open")
1224 self.assertIn(1, remaining_fds, "Subprocess failed")
1225
Victor Stinner88701e22011-06-01 13:13:04 +02001226 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1227 # descriptor of a pipe closed in the parent process is valid in the
1228 # child process according to fstat(), but the mode of the file
1229 # descriptor is invalid, and read or write raise an error.
1230 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001231 def test_pass_fds(self):
1232 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1233
1234 open_fds = set()
1235
1236 for x in range(5):
1237 fds = os.pipe()
1238 self.addCleanup(os.close, fds[0])
1239 self.addCleanup(os.close, fds[1])
1240 open_fds.update(fds)
1241
1242 for fd in open_fds:
1243 p = subprocess.Popen([sys.executable, fd_status],
1244 stdout=subprocess.PIPE, close_fds=True,
1245 pass_fds=(fd, ))
1246 output, ignored = p.communicate()
1247
1248 remaining_fds = set(map(int, output.split(b',')))
1249 to_be_closed = open_fds - {fd}
1250
1251 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1252 self.assertFalse(remaining_fds & to_be_closed,
1253 "fd to be closed passed")
1254
1255 # pass_fds overrides close_fds with a warning.
1256 with self.assertWarns(RuntimeWarning) as context:
1257 self.assertFalse(subprocess.call(
1258 [sys.executable, "-c", "import sys; sys.exit(0)"],
1259 close_fds=False, pass_fds=(fd, )))
1260 self.assertIn('overriding close_fds', str(context.warning))
1261
Gregory P. Smithe14e9c22011-03-15 14:55:17 -04001262 def test_stdout_stdin_are_single_inout_fd(self):
1263 with io.open(os.devnull, "r+") as inout:
1264 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1265 stdout=inout, stdin=inout)
1266 p.wait()
1267
1268 def test_stdout_stderr_are_single_inout_fd(self):
1269 with io.open(os.devnull, "r+") as inout:
1270 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1271 stdout=inout, stderr=inout)
1272 p.wait()
1273
1274 def test_stderr_stdin_are_single_inout_fd(self):
1275 with io.open(os.devnull, "r+") as inout:
1276 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1277 stderr=inout, stdin=inout)
1278 p.wait()
1279
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001280 def test_wait_when_sigchild_ignored(self):
1281 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1282 sigchild_ignore = support.findfile("sigchild_ignore.py",
1283 subdir="subprocessdata")
1284 p = subprocess.Popen([sys.executable, sigchild_ignore],
1285 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1286 stdout, stderr = p.communicate()
1287 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001288 " non-zero with this error:\n%s" %
1289 stderr.decode('utf8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001290
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001291 def test_select_unbuffered(self):
1292 # Issue #11459: bufsize=0 should really set the pipes as
1293 # unbuffered (and therefore let select() work properly).
1294 select = support.import_module("select")
1295 p = subprocess.Popen([sys.executable, "-c",
1296 'import sys;'
1297 'sys.stdout.write("apple")'],
1298 stdout=subprocess.PIPE,
1299 bufsize=0)
1300 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001301 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001302 try:
1303 self.assertEqual(f.read(4), b"appl")
1304 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1305 finally:
1306 p.wait()
1307
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001308
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001309@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001310class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001311
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001312 def test_startupinfo(self):
1313 # startupinfo argument
1314 # We uses hardcoded constants, because we do not want to
1315 # depend on win32all.
1316 STARTF_USESHOWWINDOW = 1
1317 SW_MAXIMIZE = 3
1318 startupinfo = subprocess.STARTUPINFO()
1319 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1320 startupinfo.wShowWindow = SW_MAXIMIZE
1321 # Since Python is a console process, it won't be affected
1322 # by wShowWindow, but the argument should be silently
1323 # ignored
1324 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001325 startupinfo=startupinfo)
1326
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001327 def test_creationflags(self):
1328 # creationflags argument
1329 CREATE_NEW_CONSOLE = 16
1330 sys.stderr.write(" a DOS box should flash briefly ...\n")
1331 subprocess.call(sys.executable +
1332 ' -c "import time; time.sleep(0.25)"',
1333 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001334
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001335 def test_invalid_args(self):
1336 # invalid arguments should raise ValueError
1337 self.assertRaises(ValueError, subprocess.call,
1338 [sys.executable, "-c",
1339 "import sys; sys.exit(47)"],
1340 preexec_fn=lambda: 1)
1341 self.assertRaises(ValueError, subprocess.call,
1342 [sys.executable, "-c",
1343 "import sys; sys.exit(47)"],
1344 stdout=subprocess.PIPE,
1345 close_fds=True)
1346
1347 def test_close_fds(self):
1348 # close file descriptors
1349 rc = subprocess.call([sys.executable, "-c",
1350 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001351 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001352 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001353
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001354 def test_shell_sequence(self):
1355 # Run command through the shell (sequence)
1356 newenv = os.environ.copy()
1357 newenv["FRUIT"] = "physalis"
1358 p = subprocess.Popen(["set"], shell=1,
1359 stdout=subprocess.PIPE,
1360 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001361 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001362 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001363
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001364 def test_shell_string(self):
1365 # Run command through the shell (string)
1366 newenv = os.environ.copy()
1367 newenv["FRUIT"] = "physalis"
1368 p = subprocess.Popen("set", shell=1,
1369 stdout=subprocess.PIPE,
1370 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001371 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001372 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001373
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001374 def test_call_string(self):
1375 # call() function with string argument on Windows
1376 rc = subprocess.call(sys.executable +
1377 ' -c "import sys; sys.exit(47)"')
1378 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001379
Florent Xicluna4886d242010-03-08 13:27:26 +00001380 def _kill_process(self, method, *args):
1381 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001382 p = subprocess.Popen([sys.executable, "-c", """if 1:
1383 import sys, time
1384 sys.stdout.write('x\\n')
1385 sys.stdout.flush()
1386 time.sleep(30)
1387 """],
1388 stdin=subprocess.PIPE,
1389 stdout=subprocess.PIPE,
1390 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001391 self.addCleanup(p.stdout.close)
1392 self.addCleanup(p.stderr.close)
1393 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001394 # Wait for the interpreter to be completely initialized before
1395 # sending any signal.
1396 p.stdout.read(1)
1397 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001398 _, stderr = p.communicate()
1399 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001400 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001401 self.assertNotEqual(returncode, 0)
1402
1403 def test_send_signal(self):
1404 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001405
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001406 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001407 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001408
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001409 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001410 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001411
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001412
Brett Cannona23810f2008-05-26 19:04:21 +00001413# The module says:
1414# "NB This only works (and is only relevant) for UNIX."
1415#
1416# Actually, getoutput should work on any platform with an os.popen, but
1417# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001418@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001419class CommandTests(unittest.TestCase):
1420 def test_getoutput(self):
1421 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1422 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1423 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001424
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001425 # we use mkdtemp in the next line to create an empty directory
1426 # under our exclusive control; from that, we can invent a pathname
1427 # that we _know_ won't exist. This is guaranteed to fail.
1428 dir = None
1429 try:
1430 dir = tempfile.mkdtemp()
1431 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001432
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001433 status, output = subprocess.getstatusoutput('cat ' + name)
1434 self.assertNotEqual(status, 0)
1435 finally:
1436 if dir is not None:
1437 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001438
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001439
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001440@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1441 "poll system call not supported")
1442class ProcessTestCaseNoPoll(ProcessTestCase):
1443 def setUp(self):
1444 subprocess._has_poll = False
1445 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001446
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001447 def tearDown(self):
1448 subprocess._has_poll = True
1449 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001450
1451
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001452@unittest.skipUnless(getattr(subprocess, '_posixsubprocess', False),
1453 "_posixsubprocess extension module not found.")
1454class ProcessTestCasePOSIXPurePython(ProcessTestCase, POSIXProcessTestCase):
Gregory P. Smith7439e7b2011-05-28 09:06:02 -07001455 @classmethod
1456 def setUpClass(cls):
1457 global subprocess
1458 assert subprocess._posixsubprocess
1459 # Reimport subprocess while forcing _posixsubprocess to not exist.
1460 with support.check_warnings(('.*_posixsubprocess .* not being used.*',
1461 RuntimeWarning)):
1462 subprocess = support.import_fresh_module(
1463 'subprocess', blocked=['_posixsubprocess'])
1464 assert not subprocess._posixsubprocess
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001465
Gregory P. Smith7439e7b2011-05-28 09:06:02 -07001466 @classmethod
1467 def tearDownClass(cls):
1468 global subprocess
1469 # Reimport subprocess as it should be, restoring order to the universe.
1470 subprocess = support.import_fresh_module('subprocess')
1471 assert subprocess._posixsubprocess
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001472
1473
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001474class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001475 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001476 def test_eintr_retry_call(self):
1477 record_calls = []
1478 def fake_os_func(*args):
1479 record_calls.append(args)
1480 if len(record_calls) == 2:
1481 raise OSError(errno.EINTR, "fake interrupted system call")
1482 return tuple(reversed(args))
1483
1484 self.assertEqual((999, 256),
1485 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1486 self.assertEqual([(256, 999)], record_calls)
1487 # This time there will be an EINTR so it will loop once.
1488 self.assertEqual((666,),
1489 subprocess._eintr_retry_call(fake_os_func, 666))
1490 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1491
1492
Tim Golden126c2962010-08-11 14:20:40 +00001493@unittest.skipUnless(mswindows, "Windows-specific tests")
1494class CommandsWithSpaces (BaseTestCase):
1495
1496 def setUp(self):
1497 super().setUp()
1498 f, fname = mkstemp(".py", "te st")
1499 self.fname = fname.lower ()
1500 os.write(f, b"import sys;"
1501 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1502 )
1503 os.close(f)
1504
1505 def tearDown(self):
1506 os.remove(self.fname)
1507 super().tearDown()
1508
1509 def with_spaces(self, *args, **kwargs):
1510 kwargs['stdout'] = subprocess.PIPE
1511 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001512 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001513 self.assertEqual(
1514 p.stdout.read ().decode("mbcs"),
1515 "2 [%r, 'ab cd']" % self.fname
1516 )
1517
1518 def test_shell_string_with_spaces(self):
1519 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001520 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1521 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001522
1523 def test_shell_sequence_with_spaces(self):
1524 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001525 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001526
1527 def test_noshell_string_with_spaces(self):
1528 # call() function with string argument with spaces on Windows
1529 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1530 "ab cd"))
1531
1532 def test_noshell_sequence_with_spaces(self):
1533 # call() function with sequence argument with spaces on Windows
1534 self.with_spaces([sys.executable, self.fname, "ab cd"])
1535
Brian Curtin79cdb662010-12-03 02:46:02 +00001536
1537class ContextManagerTests(ProcessTestCase):
1538
1539 def test_pipe(self):
1540 with subprocess.Popen([sys.executable, "-c",
1541 "import sys;"
1542 "sys.stdout.write('stdout');"
1543 "sys.stderr.write('stderr');"],
1544 stdout=subprocess.PIPE,
1545 stderr=subprocess.PIPE) as proc:
1546 self.assertEqual(proc.stdout.read(), b"stdout")
1547 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1548
1549 self.assertTrue(proc.stdout.closed)
1550 self.assertTrue(proc.stderr.closed)
1551
1552 def test_returncode(self):
1553 with subprocess.Popen([sys.executable, "-c",
1554 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smithc9557af2011-05-11 22:18:23 -07001555 pass
1556 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00001557 self.assertEqual(proc.returncode, 100)
1558
1559 def test_communicate_stdin(self):
1560 with subprocess.Popen([sys.executable, "-c",
1561 "import sys;"
1562 "sys.exit(sys.stdin.read() == 'context')"],
1563 stdin=subprocess.PIPE) as proc:
1564 proc.communicate(b"context")
1565 self.assertEqual(proc.returncode, 1)
1566
1567 def test_invalid_args(self):
1568 with self.assertRaises(EnvironmentError) as c:
1569 with subprocess.Popen(['nonexisting_i_hope'],
1570 stdout=subprocess.PIPE,
1571 stderr=subprocess.PIPE) as proc:
1572 pass
1573
1574 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1575 raise c.exception
1576
1577
Gregory P. Smith961e0e82011-03-15 15:43:39 -04001578def test_main():
1579 unit_tests = (ProcessTestCase,
1580 POSIXProcessTestCase,
1581 Win32ProcessTestCase,
1582 ProcessTestCasePOSIXPurePython,
1583 CommandTests,
1584 ProcessTestCaseNoPoll,
1585 HelperFunctionTests,
1586 CommandsWithSpaces,
1587 ContextManagerTests)
1588
1589 support.run_unittest(*unit_tests)
1590 support.reap_children()
1591
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001592if __name__ == "__main__":
Gregory P. Smithe14e9c22011-03-15 14:55:17 -04001593 unittest.main()