blob: 8444d6a5170f53a6cbeb7a2cf8fd6a1cf3a82e85 [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 Stinner372309a2011-06-21 21:59:06 +0200342 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
343 'the python library cannot be loaded '
344 'with an empty environment')
Victor Stinnerf1512a22011-06-21 17:18:38 +0200345 def test_empty_env(self):
346 with subprocess.Popen([sys.executable, "-c",
347 'import os; '
Victor Stinner372309a2011-06-21 21:59:06 +0200348 'print(list(os.environ.keys()))'],
Victor Stinnerf1512a22011-06-21 17:18:38 +0200349 stdout=subprocess.PIPE,
350 env={}) as p:
351 stdout, stderr = p.communicate()
Victor Stinner372309a2011-06-21 21:59:06 +0200352 self.assertEqual(stdout.strip(), b"[]")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000353
Peter Astrandcbac93c2005-03-03 20:24:28 +0000354 def test_communicate_stdin(self):
355 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000356 'import sys;'
357 'sys.exit(sys.stdin.read() == "pear")'],
Peter Astrandcbac93c2005-03-03 20:24:28 +0000358 stdin=subprocess.PIPE)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000359 p.communicate(b"pear")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000360 self.assertEqual(p.returncode, 1)
361
362 def test_communicate_stdout(self):
363 p = subprocess.Popen([sys.executable, "-c",
364 'import sys; sys.stdout.write("pineapple")'],
365 stdout=subprocess.PIPE)
366 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000367 self.assertEqual(stdout, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000368 self.assertEqual(stderr, None)
369
370 def test_communicate_stderr(self):
371 p = subprocess.Popen([sys.executable, "-c",
372 'import sys; sys.stderr.write("pineapple")'],
373 stderr=subprocess.PIPE)
374 (stdout, stderr) = p.communicate()
375 self.assertEqual(stdout, None)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000376 self.assertStderrEqual(stderr, b"pineapple")
Peter Astrandcbac93c2005-03-03 20:24:28 +0000377
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000378 def test_communicate(self):
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.stderr.write("pineapple");'
382 'sys.stdout.write(sys.stdin.read())'],
383 stdin=subprocess.PIPE,
384 stdout=subprocess.PIPE,
385 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000386 self.addCleanup(p.stdout.close)
387 self.addCleanup(p.stderr.close)
388 self.addCleanup(p.stdin.close)
Georg Brandl1abcbf82008-07-01 19:28:43 +0000389 (stdout, stderr) = p.communicate(b"banana")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000390 self.assertEqual(stdout, b"banana")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000391 self.assertStderrEqual(stderr, b"pineapple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000392
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000393 # Test for the fd leak reported in http://bugs.python.org/issue2791.
394 def test_communicate_pipe_fd_leak(self):
Victor Stinner667d4b52010-12-25 22:40:32 +0000395 for stdin_pipe in (False, True):
396 for stdout_pipe in (False, True):
397 for stderr_pipe in (False, True):
398 options = {}
399 if stdin_pipe:
400 options['stdin'] = subprocess.PIPE
401 if stdout_pipe:
402 options['stdout'] = subprocess.PIPE
403 if stderr_pipe:
404 options['stderr'] = subprocess.PIPE
405 if not options:
406 continue
407 p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
408 p.communicate()
409 if p.stdin is not None:
410 self.assertTrue(p.stdin.closed)
411 if p.stdout is not None:
412 self.assertTrue(p.stdout.closed)
413 if p.stderr is not None:
414 self.assertTrue(p.stderr.closed)
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000415
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000416 def test_communicate_returns(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000417 # communicate() should return None if no redirection is active
Tim Peters3b01a702004-10-12 22:19:32 +0000418 p = subprocess.Popen([sys.executable, "-c",
419 "import sys; sys.exit(47)"])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000420 (stdout, stderr) = p.communicate()
421 self.assertEqual(stdout, None)
422 self.assertEqual(stderr, None)
423
424 def test_communicate_pipe_buf(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000425 # communicate() with writes larger than pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000426 # This test will probably deadlock rather than fail, if
Tim Peterse718f612004-10-12 21:51:32 +0000427 # communicate() does not work properly.
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000428 x, y = os.pipe()
429 if mswindows:
430 pipe_buf = 512
431 else:
432 pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
433 os.close(x)
434 os.close(y)
435 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000436 'import sys,os;'
437 'sys.stdout.write(sys.stdin.read(47));'
438 'sys.stderr.write("xyz"*%d);'
439 'sys.stdout.write(sys.stdin.read())' % pipe_buf],
440 stdin=subprocess.PIPE,
441 stdout=subprocess.PIPE,
442 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000443 self.addCleanup(p.stdout.close)
444 self.addCleanup(p.stderr.close)
445 self.addCleanup(p.stdin.close)
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000446 string_to_write = b"abc"*pipe_buf
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000447 (stdout, stderr) = p.communicate(string_to_write)
448 self.assertEqual(stdout, string_to_write)
449
450 def test_writes_before_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000451 # stdin.write before communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000452 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000453 'import sys,os;'
454 'sys.stdout.write(sys.stdin.read())'],
455 stdin=subprocess.PIPE,
456 stdout=subprocess.PIPE,
457 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +0000458 self.addCleanup(p.stdout.close)
459 self.addCleanup(p.stderr.close)
460 self.addCleanup(p.stdin.close)
Guido van Rossumbb839ef2007-08-27 23:58:21 +0000461 p.stdin.write(b"banana")
462 (stdout, stderr) = p.communicate(b"split")
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000463 self.assertEqual(stdout, b"bananasplit")
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000464 self.assertStderrEqual(stderr, b"")
Tim Peterse718f612004-10-12 21:51:32 +0000465
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000466 def test_universal_newlines(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000467 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000468 'import sys,os;' + SETBINARY +
469 'sys.stdout.write("line1\\n");'
470 'sys.stdout.flush();'
471 'sys.stdout.write("line2\\n");'
472 'sys.stdout.flush();'
473 'sys.stdout.write("line3\\r\\n");'
474 'sys.stdout.flush();'
475 'sys.stdout.write("line4\\r");'
476 'sys.stdout.flush();'
477 'sys.stdout.write("\\nline5");'
478 'sys.stdout.flush();'
479 'sys.stdout.write("\\nline6");'],
480 stdout=subprocess.PIPE,
481 universal_newlines=1)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000482 self.addCleanup(p.stdout.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000483 stdout = p.stdout.read()
Guido van Rossumc9e363c2007-05-15 23:18:55 +0000484 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000485
486 def test_universal_newlines_communicate(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000487 # universal newlines through communicate()
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000488 p = subprocess.Popen([sys.executable, "-c",
Guido van Rossum98297ee2007-11-06 21:34:58 +0000489 'import sys,os;' + SETBINARY +
490 'sys.stdout.write("line1\\n");'
491 'sys.stdout.flush();'
492 'sys.stdout.write("line2\\n");'
493 'sys.stdout.flush();'
494 'sys.stdout.write("line3\\r\\n");'
495 'sys.stdout.flush();'
496 'sys.stdout.write("line4\\r");'
497 'sys.stdout.flush();'
498 'sys.stdout.write("\\nline5");'
499 'sys.stdout.flush();'
500 'sys.stdout.write("\\nline6");'],
501 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
502 universal_newlines=1)
Brian Curtin19a53792010-11-05 17:09:05 +0000503 self.addCleanup(p.stdout.close)
504 self.addCleanup(p.stderr.close)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000505 (stdout, stderr) = p.communicate()
Guido van Rossumfa0054a2007-05-24 04:05:35 +0000506 self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000507
508 def test_no_leaking(self):
Tim Peters7b759da2004-10-12 22:29:54 +0000509 # Make sure we leak no resources
Antoine Pitrou8db30272010-09-18 22:38:48 +0000510 if not mswindows:
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000511 max_handles = 1026 # too much for most UNIX systems
512 else:
Antoine Pitrou8db30272010-09-18 22:38:48 +0000513 max_handles = 2050 # too much for (at least some) Windows setups
514 handles = []
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400515 tmpdir = tempfile.mkdtemp()
Antoine Pitrou8db30272010-09-18 22:38:48 +0000516 try:
517 for i in range(max_handles):
518 try:
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400519 tmpfile = os.path.join(tmpdir, support.TESTFN)
520 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
Antoine Pitrou8db30272010-09-18 22:38:48 +0000521 except OSError as e:
522 if e.errno != errno.EMFILE:
523 raise
524 break
525 else:
526 self.skipTest("failed to reach the file descriptor limit "
527 "(tried %d)" % max_handles)
528 # Close a couple of them (should be enough for a subprocess)
529 for i in range(10):
530 os.close(handles.pop())
531 # Loop creating some subprocesses. If one of them leaks some fds,
532 # the next loop iteration will fail by reaching the max fd limit.
533 for i in range(15):
534 p = subprocess.Popen([sys.executable, "-c",
535 "import sys;"
536 "sys.stdout.write(sys.stdin.read())"],
537 stdin=subprocess.PIPE,
538 stdout=subprocess.PIPE,
539 stderr=subprocess.PIPE)
540 data = p.communicate(b"lime")[0]
541 self.assertEqual(data, b"lime")
542 finally:
543 for h in handles:
544 os.close(h)
Gregory P. Smith81ce6852011-03-15 02:04:11 -0400545 shutil.rmtree(tmpdir)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000546
547 def test_list2cmdline(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000548 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
549 '"a b c" d e')
550 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
551 'ab\\"c \\ d')
Christian Heimesfdab48e2008-01-20 09:06:41 +0000552 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
553 'ab\\"c " \\\\" d')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000554 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
555 'a\\\\\\b "de fg" h')
556 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
557 'a\\\\\\"b c d')
558 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
559 '"a\\\\b c" d e')
560 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
561 '"a\\\\b\\ c" d e')
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000562 self.assertEqual(subprocess.list2cmdline(['ab', '']),
563 'ab ""')
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000564
565
566 def test_poll(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000567 p = subprocess.Popen([sys.executable,
Tim Peters29b6b4f2004-10-13 03:43:40 +0000568 "-c", "import time; time.sleep(1)"])
569 count = 0
570 while p.poll() is None:
571 time.sleep(0.1)
572 count += 1
573 # We expect that the poll loop probably went around about 10 times,
574 # but, based on system scheduling we can't control, it's possible
575 # poll() never returned None. It "should be" very rare that it
576 # didn't go around at least twice.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000577 self.assertGreaterEqual(count, 2)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000578 # Subsequent invocations should just return the returncode
579 self.assertEqual(p.poll(), 0)
580
581
582 def test_wait(self):
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000583 p = subprocess.Popen([sys.executable,
584 "-c", "import time; time.sleep(2)"])
585 self.assertEqual(p.wait(), 0)
586 # Subsequent invocations should just return the returncode
587 self.assertEqual(p.wait(), 0)
Tim Peterse718f612004-10-12 21:51:32 +0000588
Peter Astrand738131d2004-11-30 21:04:45 +0000589
590 def test_invalid_bufsize(self):
591 # an invalid type of the bufsize argument should raise
592 # TypeError.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000593 with self.assertRaises(TypeError):
Peter Astrand738131d2004-11-30 21:04:45 +0000594 subprocess.Popen([sys.executable, "-c", "pass"], "orange")
Peter Astrand738131d2004-11-30 21:04:45 +0000595
Guido van Rossum46a05a72007-06-07 21:56:45 +0000596 def test_bufsize_is_none(self):
597 # bufsize=None should be the same as bufsize=0.
598 p = subprocess.Popen([sys.executable, "-c", "pass"], None)
599 self.assertEqual(p.wait(), 0)
600 # Again with keyword arg
601 p = subprocess.Popen([sys.executable, "-c", "pass"], bufsize=None)
602 self.assertEqual(p.wait(), 0)
603
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000604 def test_leaking_fds_on_error(self):
605 # see bug #5179: Popen leaks file descriptors to PIPEs if
606 # the child fails to execute; this will eventually exhaust
607 # the maximum number of open fds. 1024 seems a very common
608 # value for that limit, but Windows has 2048, so we loop
609 # 1024 times (each call leaked two fds).
610 for i in range(1024):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000611 # Windows raises IOError. Others raise OSError.
612 with self.assertRaises(EnvironmentError) as c:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000613 subprocess.Popen(['nonexisting_i_hope'],
614 stdout=subprocess.PIPE,
615 stderr=subprocess.PIPE)
R David Murray384069c2011-03-13 22:26:53 -0400616 # ignore errors that indicate the command was not found
R David Murray6924bd72011-03-13 22:48:55 -0400617 if c.exception.errno not in (errno.ENOENT, errno.EACCES):
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000618 raise c.exception
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000619
Victor Stinnerb3693582010-05-21 20:13:12 +0000620 def test_issue8780(self):
621 # Ensure that stdout is inherited from the parent
622 # if stdout=PIPE is not used
623 code = ';'.join((
624 'import subprocess, sys',
625 'retcode = subprocess.call('
626 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
627 'assert retcode == 0'))
628 output = subprocess.check_output([sys.executable, '-c', code])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000629 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
Victor Stinnerb3693582010-05-21 20:13:12 +0000630
Tim Goldenaf5ac392010-08-06 13:03:56 +0000631 def test_handles_closed_on_exception(self):
632 # If CreateProcess exits with an error, ensure the
633 # duplicate output handles are released
634 ifhandle, ifname = mkstemp()
635 ofhandle, ofname = mkstemp()
636 efhandle, efname = mkstemp()
637 try:
638 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
639 stderr=efhandle)
640 except OSError:
641 os.close(ifhandle)
642 os.remove(ifname)
643 os.close(ofhandle)
644 os.remove(ofname)
645 os.close(efhandle)
646 os.remove(efname)
647 self.assertFalse(os.path.exists(ifname))
648 self.assertFalse(os.path.exists(ofname))
649 self.assertFalse(os.path.exists(efname))
650
Ross Lagerwall4f61b022011-04-05 15:34:00 +0200651 def test_communicate_epipe(self):
652 # Issue 10963: communicate() should hide EPIPE
653 p = subprocess.Popen([sys.executable, "-c", 'pass'],
654 stdin=subprocess.PIPE,
655 stdout=subprocess.PIPE,
656 stderr=subprocess.PIPE)
657 self.addCleanup(p.stdout.close)
658 self.addCleanup(p.stderr.close)
659 self.addCleanup(p.stdin.close)
660 p.communicate(b"x" * 2**20)
661
662 def test_communicate_epipe_only_stdin(self):
663 # Issue 10963: communicate() should hide EPIPE
664 p = subprocess.Popen([sys.executable, "-c", 'pass'],
665 stdin=subprocess.PIPE)
666 self.addCleanup(p.stdin.close)
667 time.sleep(2)
668 p.communicate(b"x" * 2**20)
669
Tim Peterse718f612004-10-12 21:51:32 +0000670
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000671# context manager
672class _SuppressCoreFiles(object):
673 """Try to prevent core files from being created."""
674 old_limit = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000675
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000676 def __enter__(self):
677 """Try to save previous ulimit, then set it to (0, 0)."""
678 try:
679 import resource
680 self.old_limit = resource.getrlimit(resource.RLIMIT_CORE)
681 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
682 except (ImportError, ValueError, resource.error):
683 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000684
Ronald Oussoren102d11a2010-07-23 09:50:05 +0000685 if sys.platform == 'darwin':
686 # Check if the 'Crash Reporter' on OSX was configured
687 # in 'Developer' mode and warn that it will get triggered
688 # when it is.
689 #
690 # This assumes that this context manager is used in tests
691 # that might trigger the next manager.
692 value = subprocess.Popen(['/usr/bin/defaults', 'read',
693 'com.apple.CrashReporter', 'DialogType'],
694 stdout=subprocess.PIPE).communicate()[0]
695 if value.strip() == b'developer':
696 print("this tests triggers the Crash Reporter, "
697 "that is intentional", end='')
698 sys.stdout.flush()
699
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000700 def __exit__(self, *args):
701 """Return core file behavior to default."""
702 if self.old_limit is None:
703 return
704 try:
705 import resource
706 resource.setrlimit(resource.RLIMIT_CORE, self.old_limit)
707 except (ImportError, ValueError, resource.error):
708 pass
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000709
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000710
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000711@unittest.skipIf(mswindows, "POSIX specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +0000712class POSIXProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000713
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000714 def test_exceptions(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000715 nonexistent_dir = "/_this/pa.th/does/not/exist"
716 try:
717 os.chdir(nonexistent_dir)
718 except OSError as e:
719 # This avoids hard coding the errno value or the OS perror()
720 # string and instead capture the exception that we want to see
721 # below for comparison.
722 desired_exception = e
Benjamin Peterson5f780402010-11-20 18:07:52 +0000723 desired_exception.strerror += ': ' + repr(sys.executable)
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000724 else:
725 self.fail("chdir to nonexistant directory %s succeeded." %
726 nonexistent_dir)
727
728 # Error in the child re-raised in the parent.
729 try:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000730 p = subprocess.Popen([sys.executable, "-c", ""],
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000731 cwd=nonexistent_dir)
732 except OSError as e:
733 # Test that the child process chdir failure actually makes
734 # it up to the parent process as the correct exception.
735 self.assertEqual(desired_exception.errno, e.errno)
736 self.assertEqual(desired_exception.strerror, e.strerror)
737 else:
738 self.fail("Expected OSError: %s" % desired_exception)
739
740 def test_restore_signals(self):
741 # Code coverage for both values of restore_signals to make sure it
742 # at least does not blow up.
743 # A test for behavior would be complex. Contributions welcome.
744 subprocess.call([sys.executable, "-c", ""], restore_signals=True)
745 subprocess.call([sys.executable, "-c", ""], restore_signals=False)
746
747 def test_start_new_session(self):
748 # For code coverage of calling setsid(). We don't care if we get an
749 # EPERM error from it depending on the test execution environment, that
750 # still indicates that it was called.
751 try:
752 output = subprocess.check_output(
753 [sys.executable, "-c",
754 "import os; print(os.getpgid(os.getpid()))"],
755 start_new_session=True)
756 except OSError as e:
757 if e.errno != errno.EPERM:
758 raise
759 else:
760 parent_pgid = os.getpgid(os.getpid())
761 child_pgid = int(output)
762 self.assertNotEqual(parent_pgid, child_pgid)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000763
764 def test_run_abort(self):
765 # returncode handles signal termination
766 with _SuppressCoreFiles():
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000767 p = subprocess.Popen([sys.executable, "-c",
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000768 'import os; os.abort()'])
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000769 p.wait()
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000770 self.assertEqual(-p.returncode, signal.SIGABRT)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000771
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000772 def test_preexec(self):
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000773 # DISCLAIMER: Setting environment variables is *not* a good use
774 # of a preexec_fn. This is merely a test.
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000775 p = subprocess.Popen([sys.executable, "-c",
776 'import sys,os;'
777 'sys.stdout.write(os.getenv("FRUIT"))'],
778 stdout=subprocess.PIPE,
779 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
Brian Curtin3c6a9512010-11-05 03:58:52 +0000780 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000781 self.assertEqual(p.stdout.read(), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000782
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000783 def test_preexec_exception(self):
784 def raise_it():
785 raise ValueError("What if two swallows carried a coconut?")
786 try:
787 p = subprocess.Popen([sys.executable, "-c", ""],
788 preexec_fn=raise_it)
789 except RuntimeError as e:
790 self.assertTrue(
791 subprocess._posixsubprocess,
792 "Expected a ValueError from the preexec_fn")
793 except ValueError as e:
794 self.assertIn("coconut", e.args[0])
795 else:
796 self.fail("Exception raised by preexec_fn did not make it "
797 "to the parent process.")
798
Gregory P. Smith32ec9da2010-03-19 16:53:08 +0000799 @unittest.skipUnless(gc, "Requires a gc module.")
800 def test_preexec_gc_module_failure(self):
801 # This tests the code that disables garbage collection if the child
802 # process will execute any Python.
803 def raise_runtime_error():
804 raise RuntimeError("this shouldn't escape")
805 enabled = gc.isenabled()
806 orig_gc_disable = gc.disable
807 orig_gc_isenabled = gc.isenabled
808 try:
809 gc.disable()
810 self.assertFalse(gc.isenabled())
811 subprocess.call([sys.executable, '-c', ''],
812 preexec_fn=lambda: None)
813 self.assertFalse(gc.isenabled(),
814 "Popen enabled gc when it shouldn't.")
815
816 gc.enable()
817 self.assertTrue(gc.isenabled())
818 subprocess.call([sys.executable, '-c', ''],
819 preexec_fn=lambda: None)
820 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
821
822 gc.disable = raise_runtime_error
823 self.assertRaises(RuntimeError, subprocess.Popen,
824 [sys.executable, '-c', ''],
825 preexec_fn=lambda: None)
826
827 del gc.isenabled # force an AttributeError
828 self.assertRaises(AttributeError, subprocess.Popen,
829 [sys.executable, '-c', ''],
830 preexec_fn=lambda: None)
831 finally:
832 gc.disable = orig_gc_disable
833 gc.isenabled = orig_gc_isenabled
834 if not enabled:
835 gc.disable()
836
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000837 def test_args_string(self):
838 # args is a string
839 fd, fname = mkstemp()
840 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000841 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000842 fobj.write("#!/bin/sh\n")
843 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
844 sys.executable)
845 os.chmod(fname, 0o700)
846 p = subprocess.Popen(fname)
847 p.wait()
848 os.remove(fname)
849 self.assertEqual(p.returncode, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000850
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000851 def test_invalid_args(self):
852 # invalid arguments should raise ValueError
853 self.assertRaises(ValueError, subprocess.call,
854 [sys.executable, "-c",
855 "import sys; sys.exit(47)"],
856 startupinfo=47)
857 self.assertRaises(ValueError, subprocess.call,
858 [sys.executable, "-c",
859 "import sys; sys.exit(47)"],
860 creationflags=47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000861
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000862 def test_shell_sequence(self):
863 # Run command through the shell (sequence)
864 newenv = os.environ.copy()
865 newenv["FRUIT"] = "apple"
866 p = subprocess.Popen(["echo $FRUIT"], shell=1,
867 stdout=subprocess.PIPE,
868 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000869 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000870 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Fredrik Lundh5b3687d2004-10-12 15:26:28 +0000871
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000872 def test_shell_string(self):
873 # Run command through the shell (string)
874 newenv = os.environ.copy()
875 newenv["FRUIT"] = "apple"
876 p = subprocess.Popen("echo $FRUIT", shell=1,
877 stdout=subprocess.PIPE,
878 env=newenv)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000879 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000880 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
Christian Heimesa342c012008-04-20 21:01:16 +0000881
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000882 def test_call_string(self):
883 # call() function with string argument on UNIX
884 fd, fname = mkstemp()
885 # reopen in text mode
Victor Stinnerf6782ac2010-10-16 23:46:43 +0000886 with open(fd, "w", errors="surrogateescape") as fobj:
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000887 fobj.write("#!/bin/sh\n")
888 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
889 sys.executable)
890 os.chmod(fname, 0o700)
891 rc = subprocess.call(fname)
892 os.remove(fname)
893 self.assertEqual(rc, 47)
Christian Heimesa342c012008-04-20 21:01:16 +0000894
Stefan Krah9542cc62010-07-19 14:20:53 +0000895 def test_specific_shell(self):
896 # Issue #9265: Incorrect name passed as arg[0].
897 shells = []
898 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
899 for name in ['bash', 'ksh']:
900 sh = os.path.join(prefix, name)
901 if os.path.isfile(sh):
902 shells.append(sh)
903 if not shells: # Will probably work for any shell but csh.
904 self.skipTest("bash or ksh required for this test")
905 sh = '/bin/sh'
906 if os.path.isfile(sh) and not os.path.islink(sh):
907 # Test will fail if /bin/sh is a symlink to csh.
908 shells.append(sh)
909 for sh in shells:
910 p = subprocess.Popen("echo $0", executable=sh, shell=True,
911 stdout=subprocess.PIPE)
Brian Curtin3c6a9512010-11-05 03:58:52 +0000912 self.addCleanup(p.stdout.close)
Stefan Krah9542cc62010-07-19 14:20:53 +0000913 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
914
Florent Xicluna4886d242010-03-08 13:27:26 +0000915 def _kill_process(self, method, *args):
Florent Xicluna1d8ee3a2010-03-05 20:26:54 +0000916 # Do not inherit file handles from the parent.
917 # It should fix failures on some platforms.
Antoine Pitrou3d8580f2010-09-20 01:33:21 +0000918 p = subprocess.Popen([sys.executable, "-c", """if 1:
919 import sys, time
920 sys.stdout.write('x\\n')
921 sys.stdout.flush()
922 time.sleep(30)
923 """],
924 close_fds=True,
925 stdin=subprocess.PIPE,
926 stdout=subprocess.PIPE,
927 stderr=subprocess.PIPE)
928 # Wait for the interpreter to be completely initialized before
929 # sending any signal.
930 p.stdout.read(1)
931 getattr(p, method)(*args)
Florent Xicluna4886d242010-03-08 13:27:26 +0000932 return p
933
934 def test_send_signal(self):
935 p = self._kill_process('send_signal', signal.SIGINT)
Florent Xiclunac049d872010-03-27 22:47:23 +0000936 _, stderr = p.communicate()
937 self.assertIn(b'KeyboardInterrupt', stderr)
Florent Xiclunaf0cbd822010-03-04 21:50:56 +0000938 self.assertNotEqual(p.wait(), 0)
Christian Heimesa342c012008-04-20 21:01:16 +0000939
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000940 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000941 p = self._kill_process('kill')
Florent Xiclunac049d872010-03-27 22:47:23 +0000942 _, stderr = p.communicate()
943 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000944 self.assertEqual(p.wait(), -signal.SIGKILL)
Tim Peterse718f612004-10-12 21:51:32 +0000945
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000946 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +0000947 p = self._kill_process('terminate')
Florent Xiclunac049d872010-03-27 22:47:23 +0000948 _, stderr = p.communicate()
949 self.assertStderrEqual(stderr, b'')
Florent Xiclunab1e94e82010-02-27 22:12:37 +0000950 self.assertEqual(p.wait(), -signal.SIGTERM)
951
Antoine Pitrouc9c83ba2011-01-03 18:23:55 +0000952 def check_close_std_fds(self, fds):
953 # Issue #9905: test that subprocess pipes still work properly with
954 # some standard fds closed
955 stdin = 0
956 newfds = []
957 for a in fds:
958 b = os.dup(a)
959 newfds.append(b)
960 if a == 0:
961 stdin = b
962 try:
963 for fd in fds:
964 os.close(fd)
965 out, err = subprocess.Popen([sys.executable, "-c",
966 'import sys;'
967 'sys.stdout.write("apple");'
968 'sys.stdout.flush();'
969 'sys.stderr.write("orange")'],
970 stdin=stdin,
971 stdout=subprocess.PIPE,
972 stderr=subprocess.PIPE).communicate()
973 err = support.strip_python_stderr(err)
974 self.assertEqual((out, err), (b'apple', b'orange'))
975 finally:
976 for b, a in zip(newfds, fds):
977 os.dup2(b, a)
978 for b in newfds:
979 os.close(b)
980
981 def test_close_fd_0(self):
982 self.check_close_std_fds([0])
983
984 def test_close_fd_1(self):
985 self.check_close_std_fds([1])
986
987 def test_close_fd_2(self):
988 self.check_close_std_fds([2])
989
990 def test_close_fds_0_1(self):
991 self.check_close_std_fds([0, 1])
992
993 def test_close_fds_0_2(self):
994 self.check_close_std_fds([0, 2])
995
996 def test_close_fds_1_2(self):
997 self.check_close_std_fds([1, 2])
998
999 def test_close_fds_0_1_2(self):
1000 # Issue #10806: test that subprocess pipes still work properly with
1001 # all standard fds closed.
1002 self.check_close_std_fds([0, 1, 2])
1003
Antoine Pitrou95aaeee2011-01-03 21:15:48 +00001004 def test_remapping_std_fds(self):
1005 # open up some temporary files
1006 temps = [mkstemp() for i in range(3)]
1007 try:
1008 temp_fds = [fd for fd, fname in temps]
1009
1010 # unlink the files -- we won't need to reopen them
1011 for fd, fname in temps:
1012 os.unlink(fname)
1013
1014 # write some data to what will become stdin, and rewind
1015 os.write(temp_fds[1], b"STDIN")
1016 os.lseek(temp_fds[1], 0, 0)
1017
1018 # move the standard file descriptors out of the way
1019 saved_fds = [os.dup(fd) for fd in range(3)]
1020 try:
1021 # duplicate the file objects over the standard fd's
1022 for fd, temp_fd in enumerate(temp_fds):
1023 os.dup2(temp_fd, fd)
1024
1025 # now use those files in the "wrong" order, so that subprocess
1026 # has to rearrange them in the child
1027 p = subprocess.Popen([sys.executable, "-c",
1028 'import sys; got = sys.stdin.read();'
1029 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
1030 stdin=temp_fds[1],
1031 stdout=temp_fds[2],
1032 stderr=temp_fds[0])
1033 p.wait()
1034 finally:
1035 # restore the original fd's underneath sys.stdin, etc.
1036 for std, saved in enumerate(saved_fds):
1037 os.dup2(saved, std)
1038 os.close(saved)
1039
1040 for fd in temp_fds:
1041 os.lseek(fd, 0, 0)
1042
1043 out = os.read(temp_fds[2], 1024)
1044 err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
1045 self.assertEqual(out, b"got STDIN")
1046 self.assertEqual(err, b"err")
1047
1048 finally:
1049 for fd in temp_fds:
1050 os.close(fd)
1051
Victor Stinner13bb71c2010-04-23 21:41:56 +00001052 def test_surrogates_error_message(self):
Victor Stinner4d078042010-04-23 19:28:32 +00001053 def prepare():
1054 raise ValueError("surrogate:\uDCff")
1055
1056 try:
1057 subprocess.call(
1058 [sys.executable, "-c", "pass"],
1059 preexec_fn=prepare)
1060 except ValueError as err:
1061 # Pure Python implementations keeps the message
1062 self.assertIsNone(subprocess._posixsubprocess)
1063 self.assertEqual(str(err), "surrogate:\uDCff")
1064 except RuntimeError as err:
1065 # _posixsubprocess uses a default message
1066 self.assertIsNotNone(subprocess._posixsubprocess)
1067 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
1068 else:
1069 self.fail("Expected ValueError or RuntimeError")
1070
Victor Stinner13bb71c2010-04-23 21:41:56 +00001071 def test_undecodable_env(self):
1072 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
Victor Stinner13bb71c2010-04-23 21:41:56 +00001073 # test str with surrogates
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001074 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001075 env = os.environ.copy()
1076 env[key] = value
Victor Stinner89f3ad12010-10-14 10:43:31 +00001077 # Use C locale to get ascii for the locale encoding to force
1078 # surrogate-escaping of \xFF in the child process; otherwise it can
1079 # be decoded as-is if the default locale is latin-1.
Victor Stinnerebc78d22010-10-14 10:38:17 +00001080 env['LC_ALL'] = 'C'
Victor Stinner13bb71c2010-04-23 21:41:56 +00001081 stdout = subprocess.check_output(
1082 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001083 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001084 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001085 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001086
1087 # test bytes
1088 key = key.encode("ascii", "surrogateescape")
1089 value = value.encode("ascii", "surrogateescape")
Antoine Pitroufb8db8f2010-09-19 22:46:05 +00001090 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001091 env = os.environ.copy()
1092 env[key] = value
Victor Stinner13bb71c2010-04-23 21:41:56 +00001093 stdout = subprocess.check_output(
1094 [sys.executable, "-c", script],
Victor Stinnerce2d24d2010-04-23 22:55:39 +00001095 env=env)
Victor Stinner13bb71c2010-04-23 21:41:56 +00001096 stdout = stdout.rstrip(b'\n\r')
Ezio Melottib3aedd42010-11-20 19:04:17 +00001097 self.assertEqual(stdout.decode('ascii'), ascii(value))
Victor Stinner13bb71c2010-04-23 21:41:56 +00001098
Victor Stinnerb745a742010-05-18 17:17:23 +00001099 def test_bytes_program(self):
1100 abs_program = os.fsencode(sys.executable)
1101 path, program = os.path.split(sys.executable)
1102 program = os.fsencode(program)
1103
1104 # absolute bytes path
1105 exitcode = subprocess.call([abs_program, "-c", "pass"])
Ezio Melottib3aedd42010-11-20 19:04:17 +00001106 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001107
1108 # bytes program, unicode PATH
1109 env = os.environ.copy()
1110 env["PATH"] = path
1111 exitcode = subprocess.call([program, "-c", "pass"], env=env)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001112 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001113
1114 # bytes program, bytes PATH
1115 envb = os.environb.copy()
1116 envb[b"PATH"] = os.fsencode(path)
1117 exitcode = subprocess.call([program, "-c", "pass"], env=envb)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001118 self.assertEqual(exitcode, 0)
Victor Stinnerb745a742010-05-18 17:17:23 +00001119
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001120 def test_pipe_cloexec(self):
1121 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
1122 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1123
1124 p1 = subprocess.Popen([sys.executable, sleeper],
1125 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1126 stderr=subprocess.PIPE, close_fds=False)
1127
1128 self.addCleanup(p1.communicate, b'')
1129
1130 p2 = subprocess.Popen([sys.executable, fd_status],
1131 stdout=subprocess.PIPE, close_fds=False)
1132
1133 output, error = p2.communicate()
1134 result_fds = set(map(int, output.split(b',')))
1135 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
1136 p1.stderr.fileno()])
1137
1138 self.assertFalse(result_fds & unwanted_fds,
1139 "Expected no fds from %r to be open in child, "
1140 "found %r" %
1141 (unwanted_fds, result_fds & unwanted_fds))
1142
1143 def test_pipe_cloexec_real_tools(self):
1144 qcat = support.findfile("qcat.py", subdir="subprocessdata")
1145 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
1146
1147 subdata = b'zxcvbn'
1148 data = subdata * 4 + b'\n'
1149
1150 p1 = subprocess.Popen([sys.executable, qcat],
1151 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1152 close_fds=False)
1153
1154 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
1155 stdin=p1.stdout, stdout=subprocess.PIPE,
1156 close_fds=False)
1157
1158 self.addCleanup(p1.wait)
1159 self.addCleanup(p2.wait)
1160 self.addCleanup(p1.terminate)
1161 self.addCleanup(p2.terminate)
1162
1163 p1.stdin.write(data)
1164 p1.stdin.close()
1165
1166 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
1167
1168 self.assertTrue(readfiles, "The child hung")
1169 self.assertEqual(p2.stdout.read(), data)
1170
Victor Stinnerfaa8c132011-01-03 16:36:00 +00001171 p1.stdout.close()
1172 p2.stdout.close()
1173
Gregory P. Smith51ee2702010-12-13 07:59:39 +00001174 def test_close_fds(self):
1175 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1176
1177 fds = os.pipe()
1178 self.addCleanup(os.close, fds[0])
1179 self.addCleanup(os.close, fds[1])
1180
1181 open_fds = set(fds)
1182
1183 p = subprocess.Popen([sys.executable, fd_status],
1184 stdout=subprocess.PIPE, close_fds=False)
1185 output, ignored = p.communicate()
1186 remaining_fds = set(map(int, output.split(b',')))
1187
1188 self.assertEqual(remaining_fds & open_fds, open_fds,
1189 "Some fds were closed")
1190
1191 p = subprocess.Popen([sys.executable, fd_status],
1192 stdout=subprocess.PIPE, close_fds=True)
1193 output, ignored = p.communicate()
1194 remaining_fds = set(map(int, output.split(b',')))
1195
1196 self.assertFalse(remaining_fds & open_fds,
1197 "Some fds were left open")
1198 self.assertIn(1, remaining_fds, "Subprocess failed")
1199
Victor Stinner88701e22011-06-01 13:13:04 +02001200 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
1201 # descriptor of a pipe closed in the parent process is valid in the
1202 # child process according to fstat(), but the mode of the file
1203 # descriptor is invalid, and read or write raise an error.
1204 @support.requires_mac_ver(10, 5)
Gregory P. Smith8edd99d2010-12-14 13:43:30 +00001205 def test_pass_fds(self):
1206 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
1207
1208 open_fds = set()
1209
1210 for x in range(5):
1211 fds = os.pipe()
1212 self.addCleanup(os.close, fds[0])
1213 self.addCleanup(os.close, fds[1])
1214 open_fds.update(fds)
1215
1216 for fd in open_fds:
1217 p = subprocess.Popen([sys.executable, fd_status],
1218 stdout=subprocess.PIPE, close_fds=True,
1219 pass_fds=(fd, ))
1220 output, ignored = p.communicate()
1221
1222 remaining_fds = set(map(int, output.split(b',')))
1223 to_be_closed = open_fds - {fd}
1224
1225 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
1226 self.assertFalse(remaining_fds & to_be_closed,
1227 "fd to be closed passed")
1228
1229 # pass_fds overrides close_fds with a warning.
1230 with self.assertWarns(RuntimeWarning) as context:
1231 self.assertFalse(subprocess.call(
1232 [sys.executable, "-c", "import sys; sys.exit(0)"],
1233 close_fds=False, pass_fds=(fd, )))
1234 self.assertIn('overriding close_fds', str(context.warning))
1235
Gregory P. Smithe14e9c22011-03-15 14:55:17 -04001236 def test_stdout_stdin_are_single_inout_fd(self):
1237 with io.open(os.devnull, "r+") as inout:
1238 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1239 stdout=inout, stdin=inout)
1240 p.wait()
1241
1242 def test_stdout_stderr_are_single_inout_fd(self):
1243 with io.open(os.devnull, "r+") as inout:
1244 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1245 stdout=inout, stderr=inout)
1246 p.wait()
1247
1248 def test_stderr_stdin_are_single_inout_fd(self):
1249 with io.open(os.devnull, "r+") as inout:
1250 p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"],
1251 stderr=inout, stdin=inout)
1252 p.wait()
1253
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001254 def test_wait_when_sigchild_ignored(self):
1255 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
1256 sigchild_ignore = support.findfile("sigchild_ignore.py",
1257 subdir="subprocessdata")
1258 p = subprocess.Popen([sys.executable, sigchild_ignore],
1259 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1260 stdout, stderr = p.communicate()
1261 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
Gregory P. Smitha80f4fb2010-12-14 15:23:02 +00001262 " non-zero with this error:\n%s" %
1263 stderr.decode('utf8'))
Gregory P. Smithe85db2b2010-12-14 14:38:00 +00001264
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001265 def test_select_unbuffered(self):
1266 # Issue #11459: bufsize=0 should really set the pipes as
1267 # unbuffered (and therefore let select() work properly).
1268 select = support.import_module("select")
1269 p = subprocess.Popen([sys.executable, "-c",
1270 'import sys;'
1271 'sys.stdout.write("apple")'],
1272 stdout=subprocess.PIPE,
1273 bufsize=0)
1274 f = p.stdout
Ross Lagerwall17ace7a2011-03-26 21:21:46 +02001275 self.addCleanup(f.close)
Antoine Pitrou7b98d022011-03-19 17:04:13 +01001276 try:
1277 self.assertEqual(f.read(4), b"appl")
1278 self.assertIn(f, select.select([f], [], [], 0.0)[0])
1279 finally:
1280 p.wait()
1281
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001282
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001283@unittest.skipUnless(mswindows, "Windows specific tests")
Florent Xiclunac049d872010-03-27 22:47:23 +00001284class Win32ProcessTestCase(BaseTestCase):
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001285
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001286 def test_startupinfo(self):
1287 # startupinfo argument
1288 # We uses hardcoded constants, because we do not want to
1289 # depend on win32all.
1290 STARTF_USESHOWWINDOW = 1
1291 SW_MAXIMIZE = 3
1292 startupinfo = subprocess.STARTUPINFO()
1293 startupinfo.dwFlags = STARTF_USESHOWWINDOW
1294 startupinfo.wShowWindow = SW_MAXIMIZE
1295 # Since Python is a console process, it won't be affected
1296 # by wShowWindow, but the argument should be silently
1297 # ignored
1298 subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001299 startupinfo=startupinfo)
1300
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001301 def test_creationflags(self):
1302 # creationflags argument
1303 CREATE_NEW_CONSOLE = 16
1304 sys.stderr.write(" a DOS box should flash briefly ...\n")
1305 subprocess.call(sys.executable +
1306 ' -c "import time; time.sleep(0.25)"',
1307 creationflags=CREATE_NEW_CONSOLE)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001308
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001309 def test_invalid_args(self):
1310 # invalid arguments should raise ValueError
1311 self.assertRaises(ValueError, subprocess.call,
1312 [sys.executable, "-c",
1313 "import sys; sys.exit(47)"],
1314 preexec_fn=lambda: 1)
1315 self.assertRaises(ValueError, subprocess.call,
1316 [sys.executable, "-c",
1317 "import sys; sys.exit(47)"],
1318 stdout=subprocess.PIPE,
1319 close_fds=True)
1320
1321 def test_close_fds(self):
1322 # close file descriptors
1323 rc = subprocess.call([sys.executable, "-c",
1324 "import sys; sys.exit(47)"],
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001325 close_fds=True)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001326 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001327
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001328 def test_shell_sequence(self):
1329 # Run command through the shell (sequence)
1330 newenv = os.environ.copy()
1331 newenv["FRUIT"] = "physalis"
1332 p = subprocess.Popen(["set"], shell=1,
1333 stdout=subprocess.PIPE,
1334 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001335 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001336 self.assertIn(b"physalis", p.stdout.read())
Guido van Rossume7ba4952007-06-06 23:52:48 +00001337
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001338 def test_shell_string(self):
1339 # Run command through the shell (string)
1340 newenv = os.environ.copy()
1341 newenv["FRUIT"] = "physalis"
1342 p = subprocess.Popen("set", shell=1,
1343 stdout=subprocess.PIPE,
1344 env=newenv)
Brian Curtin19a53792010-11-05 17:09:05 +00001345 self.addCleanup(p.stdout.close)
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001346 self.assertIn(b"physalis", p.stdout.read())
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001347
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001348 def test_call_string(self):
1349 # call() function with string argument on Windows
1350 rc = subprocess.call(sys.executable +
1351 ' -c "import sys; sys.exit(47)"')
1352 self.assertEqual(rc, 47)
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001353
Florent Xicluna4886d242010-03-08 13:27:26 +00001354 def _kill_process(self, method, *args):
1355 # Some win32 buildbot raises EOFError if stdin is inherited
Antoine Pitroua4024e22010-09-24 18:57:01 +00001356 p = subprocess.Popen([sys.executable, "-c", """if 1:
1357 import sys, time
1358 sys.stdout.write('x\\n')
1359 sys.stdout.flush()
1360 time.sleep(30)
1361 """],
1362 stdin=subprocess.PIPE,
1363 stdout=subprocess.PIPE,
1364 stderr=subprocess.PIPE)
Brian Curtin19a53792010-11-05 17:09:05 +00001365 self.addCleanup(p.stdout.close)
1366 self.addCleanup(p.stderr.close)
1367 self.addCleanup(p.stdin.close)
Antoine Pitroua4024e22010-09-24 18:57:01 +00001368 # Wait for the interpreter to be completely initialized before
1369 # sending any signal.
1370 p.stdout.read(1)
1371 getattr(p, method)(*args)
Florent Xiclunac049d872010-03-27 22:47:23 +00001372 _, stderr = p.communicate()
1373 self.assertStderrEqual(stderr, b'')
Antoine Pitroua4024e22010-09-24 18:57:01 +00001374 returncode = p.wait()
Florent Xicluna4886d242010-03-08 13:27:26 +00001375 self.assertNotEqual(returncode, 0)
1376
1377 def test_send_signal(self):
1378 self._kill_process('send_signal', signal.SIGTERM)
Christian Heimesa342c012008-04-20 21:01:16 +00001379
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001380 def test_kill(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001381 self._kill_process('kill')
Christian Heimesa342c012008-04-20 21:01:16 +00001382
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001383 def test_terminate(self):
Florent Xicluna4886d242010-03-08 13:27:26 +00001384 self._kill_process('terminate')
Christian Heimesa342c012008-04-20 21:01:16 +00001385
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001386
Brett Cannona23810f2008-05-26 19:04:21 +00001387# The module says:
1388# "NB This only works (and is only relevant) for UNIX."
1389#
1390# Actually, getoutput should work on any platform with an os.popen, but
1391# I'll take the comment as given, and skip this suite.
Florent Xiclunaf0cbd822010-03-04 21:50:56 +00001392@unittest.skipUnless(os.name == 'posix', "only relevant for UNIX")
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001393class CommandTests(unittest.TestCase):
1394 def test_getoutput(self):
1395 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
1396 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
1397 (0, 'xyzzy'))
Brett Cannona23810f2008-05-26 19:04:21 +00001398
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001399 # we use mkdtemp in the next line to create an empty directory
1400 # under our exclusive control; from that, we can invent a pathname
1401 # that we _know_ won't exist. This is guaranteed to fail.
1402 dir = None
1403 try:
1404 dir = tempfile.mkdtemp()
1405 name = os.path.join(dir, "foo")
Brett Cannona23810f2008-05-26 19:04:21 +00001406
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001407 status, output = subprocess.getstatusoutput('cat ' + name)
1408 self.assertNotEqual(status, 0)
1409 finally:
1410 if dir is not None:
1411 os.rmdir(dir)
Brett Cannona23810f2008-05-26 19:04:21 +00001412
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001413
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001414@unittest.skipUnless(getattr(subprocess, '_has_poll', False),
1415 "poll system call not supported")
1416class ProcessTestCaseNoPoll(ProcessTestCase):
1417 def setUp(self):
1418 subprocess._has_poll = False
1419 ProcessTestCase.setUp(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001420
Florent Xiclunab1e94e82010-02-27 22:12:37 +00001421 def tearDown(self):
1422 subprocess._has_poll = True
1423 ProcessTestCase.tearDown(self)
Gregory P. Smithd06fa472009-07-04 02:46:54 +00001424
1425
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001426@unittest.skipUnless(getattr(subprocess, '_posixsubprocess', False),
1427 "_posixsubprocess extension module not found.")
1428class ProcessTestCasePOSIXPurePython(ProcessTestCase, POSIXProcessTestCase):
Gregory P. Smith7439e7b2011-05-28 09:06:02 -07001429 @classmethod
1430 def setUpClass(cls):
1431 global subprocess
1432 assert subprocess._posixsubprocess
1433 # Reimport subprocess while forcing _posixsubprocess to not exist.
1434 with support.check_warnings(('.*_posixsubprocess .* not being used.*',
1435 RuntimeWarning)):
1436 subprocess = support.import_fresh_module(
1437 'subprocess', blocked=['_posixsubprocess'])
1438 assert not subprocess._posixsubprocess
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001439
Gregory P. Smith7439e7b2011-05-28 09:06:02 -07001440 @classmethod
1441 def tearDownClass(cls):
1442 global subprocess
1443 # Reimport subprocess as it should be, restoring order to the universe.
1444 subprocess = support.import_fresh_module('subprocess')
1445 assert subprocess._posixsubprocess
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00001446
1447
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001448class HelperFunctionTests(unittest.TestCase):
Gregory P. Smithaf6d3b82010-03-01 02:56:44 +00001449 @unittest.skipIf(mswindows, "errno and EINTR make no sense on windows")
Gregory P. Smitha59c59f2010-03-01 00:17:40 +00001450 def test_eintr_retry_call(self):
1451 record_calls = []
1452 def fake_os_func(*args):
1453 record_calls.append(args)
1454 if len(record_calls) == 2:
1455 raise OSError(errno.EINTR, "fake interrupted system call")
1456 return tuple(reversed(args))
1457
1458 self.assertEqual((999, 256),
1459 subprocess._eintr_retry_call(fake_os_func, 256, 999))
1460 self.assertEqual([(256, 999)], record_calls)
1461 # This time there will be an EINTR so it will loop once.
1462 self.assertEqual((666,),
1463 subprocess._eintr_retry_call(fake_os_func, 666))
1464 self.assertEqual([(256, 999), (666,), (666,)], record_calls)
1465
1466
Tim Golden126c2962010-08-11 14:20:40 +00001467@unittest.skipUnless(mswindows, "Windows-specific tests")
1468class CommandsWithSpaces (BaseTestCase):
1469
1470 def setUp(self):
1471 super().setUp()
1472 f, fname = mkstemp(".py", "te st")
1473 self.fname = fname.lower ()
1474 os.write(f, b"import sys;"
1475 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
1476 )
1477 os.close(f)
1478
1479 def tearDown(self):
1480 os.remove(self.fname)
1481 super().tearDown()
1482
1483 def with_spaces(self, *args, **kwargs):
1484 kwargs['stdout'] = subprocess.PIPE
1485 p = subprocess.Popen(*args, **kwargs)
Brian Curtin19a53792010-11-05 17:09:05 +00001486 self.addCleanup(p.stdout.close)
Tim Golden126c2962010-08-11 14:20:40 +00001487 self.assertEqual(
1488 p.stdout.read ().decode("mbcs"),
1489 "2 [%r, 'ab cd']" % self.fname
1490 )
1491
1492 def test_shell_string_with_spaces(self):
1493 # call() function with string argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001494 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1495 "ab cd"), shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001496
1497 def test_shell_sequence_with_spaces(self):
1498 # call() function with sequence argument with spaces on Windows
Brian Curtind835cf12010-08-13 20:42:57 +00001499 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
Tim Golden126c2962010-08-11 14:20:40 +00001500
1501 def test_noshell_string_with_spaces(self):
1502 # call() function with string argument with spaces on Windows
1503 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
1504 "ab cd"))
1505
1506 def test_noshell_sequence_with_spaces(self):
1507 # call() function with sequence argument with spaces on Windows
1508 self.with_spaces([sys.executable, self.fname, "ab cd"])
1509
Brian Curtin79cdb662010-12-03 02:46:02 +00001510
1511class ContextManagerTests(ProcessTestCase):
1512
1513 def test_pipe(self):
1514 with subprocess.Popen([sys.executable, "-c",
1515 "import sys;"
1516 "sys.stdout.write('stdout');"
1517 "sys.stderr.write('stderr');"],
1518 stdout=subprocess.PIPE,
1519 stderr=subprocess.PIPE) as proc:
1520 self.assertEqual(proc.stdout.read(), b"stdout")
1521 self.assertStderrEqual(proc.stderr.read(), b"stderr")
1522
1523 self.assertTrue(proc.stdout.closed)
1524 self.assertTrue(proc.stderr.closed)
1525
1526 def test_returncode(self):
1527 with subprocess.Popen([sys.executable, "-c",
1528 "import sys; sys.exit(100)"]) as proc:
Gregory P. Smithc9557af2011-05-11 22:18:23 -07001529 pass
1530 # __exit__ calls wait(), so the returncode should be set
Brian Curtin79cdb662010-12-03 02:46:02 +00001531 self.assertEqual(proc.returncode, 100)
1532
1533 def test_communicate_stdin(self):
1534 with subprocess.Popen([sys.executable, "-c",
1535 "import sys;"
1536 "sys.exit(sys.stdin.read() == 'context')"],
1537 stdin=subprocess.PIPE) as proc:
1538 proc.communicate(b"context")
1539 self.assertEqual(proc.returncode, 1)
1540
1541 def test_invalid_args(self):
1542 with self.assertRaises(EnvironmentError) as c:
1543 with subprocess.Popen(['nonexisting_i_hope'],
1544 stdout=subprocess.PIPE,
1545 stderr=subprocess.PIPE) as proc:
1546 pass
1547
1548 if c.exception.errno != errno.ENOENT: # ignore "no such file"
1549 raise c.exception
1550
1551
Gregory P. Smith961e0e82011-03-15 15:43:39 -04001552def test_main():
1553 unit_tests = (ProcessTestCase,
1554 POSIXProcessTestCase,
1555 Win32ProcessTestCase,
1556 ProcessTestCasePOSIXPurePython,
1557 CommandTests,
1558 ProcessTestCaseNoPoll,
1559 HelperFunctionTests,
1560 CommandsWithSpaces,
1561 ContextManagerTests)
1562
1563 support.run_unittest(*unit_tests)
1564 support.reap_children()
1565
Fredrik Lundh5b3687d2004-10-12 15:26:28 +00001566if __name__ == "__main__":
Gregory P. Smithe14e9c22011-03-15 14:55:17 -04001567 unittest.main()