Debian Codegraph @

Lib/test/test_subprocess.py

raw
1 import unittest
2 from unittest import mock
3 from test import support
4 from test.support import check_sanitizer
5 from test.support import import_helper
6 from test.support import os_helper
7 from test.support import warnings_helper
8 from test.support.script_helper import assert_python_ok
9 import subprocess
10 import sys
11 import signal
12 import io
13 import itertools
14 import os
15 import errno
16 import tempfile
17 import time
18 import traceback
19 import types
20 import selectors
21 import sysconfig
22 import select
23 import shutil
24 import threading
25 import gc
26 import textwrap
27 import json
28 from test.support.os_helper import FakePath
29
30 try:
31 import _testcapi
32 except ImportError:
33 _testcapi = None
34
35 try:
36 import pwd
37 except ImportError:
38 pwd = None
39 try:
40 import grp
41 except ImportError:
42 grp = None
43 try:
44 import resource
45 except ImportError:
46 resource = None
47
48 try:
49 import fcntl
50 except:
51 fcntl = None
52
53 if support.PGO:
54 raise unittest.SkipTest("test is not helpful for PGO")
55
56 if not support.has_subprocess_support:
57 raise unittest.SkipTest("test module requires subprocess")
58
59 mswindows = (sys.platform == "win32")
60
61 #
62 # Depends on the following external programs: Python
63 #
64
65 if mswindows:
66 SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
67 'os.O_BINARY);')
68 else:
69 SETBINARY = ''
70
71 NONEXISTING_CMD = ('nonexisting_i_hope',)
72 # Ignore errors that indicate the command was not found
73 NONEXISTING_ERRORS = (FileNotFoundError, NotADirectoryError, PermissionError)
74
75 ZERO_RETURN_CMD = (sys.executable, '-c', 'pass')
76
77
78 def setUpModule():
79 shell_true = shutil.which('true')
80 if shell_true is None:
81 return
82 if (os.access(shell_true, os.X_OK) and
83 subprocess.run([shell_true]).returncode == 0):
84 global ZERO_RETURN_CMD
85 ZERO_RETURN_CMD = (shell_true,) # Faster than Python startup.
86
87
88 class BaseTestCase(unittest.TestCase):
89 def setUp(self):
90 # Try to minimize the number of children we have so this test
91 # doesn't crash on some buildbots (Alphas in particular).
92 support.reap_children()
93
94 def tearDown(self):
95 if not mswindows:
96 # subprocess._active is not used on Windows and is set to None.
97 for inst in subprocess._active:
98 inst.wait()
99 subprocess._cleanup()
100 self.assertFalse(
101 subprocess._active, "subprocess._active not empty"
102 )
103 self.doCleanups()
104 support.reap_children()
105
106
107 class PopenTestException(Exception):
108 pass
109
110
111 class PopenExecuteChildRaises(subprocess.Popen):
112 """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
113 _execute_child fails.
114 """
115 def _execute_child(self, *args, **kwargs):
116 raise PopenTestException("Forced Exception for Test")
117
118
119 class ProcessTestCase(BaseTestCase):
120
121 def test_io_buffered_by_default(self):
122 p = subprocess.Popen(ZERO_RETURN_CMD,
123 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
124 stderr=subprocess.PIPE)
125 try:
126 self.assertIsInstance(p.stdin, io.BufferedIOBase)
127 self.assertIsInstance(p.stdout, io.BufferedIOBase)
128 self.assertIsInstance(p.stderr, io.BufferedIOBase)
129 finally:
130 p.stdin.close()
131 p.stdout.close()
132 p.stderr.close()
133 p.wait()
134
135 def test_io_unbuffered_works(self):
136 p = subprocess.Popen(ZERO_RETURN_CMD,
137 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
138 stderr=subprocess.PIPE, bufsize=0)
139 try:
140 self.assertIsInstance(p.stdin, io.RawIOBase)
141 self.assertIsInstance(p.stdout, io.RawIOBase)
142 self.assertIsInstance(p.stderr, io.RawIOBase)
143 finally:
144 p.stdin.close()
145 p.stdout.close()
146 p.stderr.close()
147 p.wait()
148
149 def test_call_seq(self):
150 # call() function with sequence argument
151 rc = subprocess.call([sys.executable, "-c",
152 "import sys; sys.exit(47)"])
153 self.assertEqual(rc, 47)
154
155 def test_call_timeout(self):
156 # call() function with timeout argument; we want to test that the child
157 # process gets killed when the timeout expires. If the child isn't
158 # killed, this call will deadlock since subprocess.call waits for the
159 # child.
160 self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
161 [sys.executable, "-c", "while True: pass"],
162 timeout=0.1)
163
164 def test_timeout_exception(self):
165 try:
166 subprocess.run([sys.executable, '-c', 'import time;time.sleep(9)'], timeout = -1)
167 except subprocess.TimeoutExpired as e:
168 self.assertIn("-1 seconds", str(e))
169 else:
170 self.fail("Expected TimeoutExpired exception not raised")
171 try:
172 subprocess.run([sys.executable, '-c', 'import time;time.sleep(9)'], timeout = 0)
173 except subprocess.TimeoutExpired as e:
174 self.assertIn("0 seconds", str(e))
175 else:
176 self.fail("Expected TimeoutExpired exception not raised")
177
178 def test_check_call_zero(self):
179 # check_call() function with zero return code
180 rc = subprocess.check_call(ZERO_RETURN_CMD)
181 self.assertEqual(rc, 0)
182
183 def test_check_call_nonzero(self):
184 # check_call() function with non-zero return code
185 with self.assertRaises(subprocess.CalledProcessError) as c:
186 subprocess.check_call([sys.executable, "-c",
187 "import sys; sys.exit(47)"])
188 self.assertEqual(c.exception.returncode, 47)
189
190 def test_check_output(self):
191 # check_output() function with zero return code
192 output = subprocess.check_output(
193 [sys.executable, "-c", "print('BDFL')"])
194 self.assertIn(b'BDFL', output)
195
196 with self.assertRaisesRegex(ValueError,
197 "stdout argument not allowed, it will be overridden"):
198 subprocess.check_output([], stdout=None)
199
200 with self.assertRaisesRegex(ValueError,
201 "check argument not allowed, it will be overridden"):
202 subprocess.check_output([], check=False)
203
204 def test_check_output_nonzero(self):
205 # check_call() function with non-zero return code
206 with self.assertRaises(subprocess.CalledProcessError) as c:
207 subprocess.check_output(
208 [sys.executable, "-c", "import sys; sys.exit(5)"])
209 self.assertEqual(c.exception.returncode, 5)
210
211 def test_check_output_stderr(self):
212 # check_output() function stderr redirected to stdout
213 output = subprocess.check_output(
214 [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
215 stderr=subprocess.STDOUT)
216 self.assertIn(b'BDFL', output)
217
218 def test_check_output_stdin_arg(self):
219 # check_output() can be called with stdin set to a file
220 tf = tempfile.TemporaryFile()
221 self.addCleanup(tf.close)
222 tf.write(b'pear')
223 tf.seek(0)
224 output = subprocess.check_output(
225 [sys.executable, "-c",
226 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
227 stdin=tf)
228 self.assertIn(b'PEAR', output)
229
230 def test_check_output_input_arg(self):
231 # check_output() can be called with input set to a string
232 output = subprocess.check_output(
233 [sys.executable, "-c",
234 "import sys; sys.stdout.write(sys.stdin.read().upper())"],
235 input=b'pear')
236 self.assertIn(b'PEAR', output)
237
238 def test_check_output_input_none(self):
239 """input=None has a legacy meaning of input='' on check_output."""
240 output = subprocess.check_output(
241 [sys.executable, "-c",
242 "import sys; print('XX' if sys.stdin.read() else '')"],
243 input=None)
244 self.assertNotIn(b'XX', output)
245
246 def test_check_output_input_none_text(self):
247 output = subprocess.check_output(
248 [sys.executable, "-c",
249 "import sys; print('XX' if sys.stdin.read() else '')"],
250 input=None, text=True)
251 self.assertNotIn('XX', output)
252
253 def test_check_output_input_none_universal_newlines(self):
254 output = subprocess.check_output(
255 [sys.executable, "-c",
256 "import sys; print('XX' if sys.stdin.read() else '')"],
257 input=None, universal_newlines=True)
258 self.assertNotIn('XX', output)
259
260 def test_check_output_input_none_encoding_errors(self):
261 output = subprocess.check_output(
262 [sys.executable, "-c", "print('foo')"],
263 input=None, encoding='utf-8', errors='ignore')
264 self.assertIn('foo', output)
265
266 def test_check_output_stdout_arg(self):
267 # check_output() refuses to accept 'stdout' argument
268 with self.assertRaises(ValueError) as c:
269 output = subprocess.check_output(
270 [sys.executable, "-c", "print('will not be run')"],
271 stdout=sys.stdout)
272 self.fail("Expected ValueError when stdout arg supplied.")
273 self.assertIn('stdout', c.exception.args[0])
274
275 def test_check_output_stdin_with_input_arg(self):
276 # check_output() refuses to accept 'stdin' with 'input'
277 tf = tempfile.TemporaryFile()
278 self.addCleanup(tf.close)
279 tf.write(b'pear')
280 tf.seek(0)
281 with self.assertRaises(ValueError) as c:
282 output = subprocess.check_output(
283 [sys.executable, "-c", "print('will not be run')"],
284 stdin=tf, input=b'hare')
285 self.fail("Expected ValueError when stdin and input args supplied.")
286 self.assertIn('stdin', c.exception.args[0])
287 self.assertIn('input', c.exception.args[0])
288
289 def test_check_output_timeout(self):
290 # check_output() function with timeout arg
291 with self.assertRaises(subprocess.TimeoutExpired) as c:
292 output = subprocess.check_output(
293 [sys.executable, "-c",
294 "import time; time.sleep(3600)"],
295 timeout=0.1)
296
297 def test_call_kwargs(self):
298 # call() function with keyword args
299 newenv = os.environ.copy()
300 newenv["FRUIT"] = "banana"
301 rc = subprocess.call([sys.executable, "-c",
302 'import sys, os;'
303 'sys.exit(os.getenv("FRUIT")=="banana")'],
304 env=newenv)
305 self.assertEqual(rc, 1)
306
307 def test_invalid_args(self):
308 # Popen() called with invalid arguments should raise TypeError
309 # but Popen.__del__ should not complain (issue #12085)
310 with support.captured_stderr() as s:
311 self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
312 argcount = subprocess.Popen.__init__.__code__.co_argcount
313 too_many_args = [0] * (argcount + 1)
314 self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
315 self.assertEqual(s.getvalue(), '')
316
317 def test_stdin_none(self):
318 # .stdin is None when not redirected
319 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
320 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
321 self.addCleanup(p.stdout.close)
322 self.addCleanup(p.stderr.close)
323 p.wait()
324 self.assertEqual(p.stdin, None)
325
326 def test_stdout_none(self):
327 # .stdout is None when not redirected, and the child's stdout will
328 # be inherited from the parent. In order to test this we run a
329 # subprocess in a subprocess:
330 # this_test
331 # \-- subprocess created by this test (parent)
332 # \-- subprocess created by the parent subprocess (child)
333 # The parent doesn't specify stdout, so the child will use the
334 # parent's stdout. This test checks that the message printed by the
335 # child goes to the parent stdout. The parent also checks that the
336 # child's stdout is None. See #11963.
337 code = ('import sys; from subprocess import Popen, PIPE;'
338 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
339 ' stdin=PIPE, stderr=PIPE);'
340 'p.wait(); assert p.stdout is None;')
341 p = subprocess.Popen([sys.executable, "-c", code],
342 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
343 self.addCleanup(p.stdout.close)
344 self.addCleanup(p.stderr.close)
345 out, err = p.communicate()
346 self.assertEqual(p.returncode, 0, err)
347 self.assertEqual(out.rstrip(), b'test_stdout_none')
348
349 def test_stderr_none(self):
350 # .stderr is None when not redirected
351 p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
352 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
353 self.addCleanup(p.stdout.close)
354 self.addCleanup(p.stdin.close)
355 p.wait()
356 self.assertEqual(p.stderr, None)
357
358 def _assert_python(self, pre_args, **kwargs):
359 # We include sys.exit() to prevent the test runner from hanging
360 # whenever python is found.
361 args = pre_args + ["import sys; sys.exit(47)"]
362 p = subprocess.Popen(args, **kwargs)
363 p.wait()
364 self.assertEqual(47, p.returncode)
365
366 def test_executable(self):
367 # Check that the executable argument works.
368 #
369 # On Unix (non-Mac and non-Windows), Python looks at args[0] to
370 # determine where its standard library is, so we need the directory
371 # of args[0] to be valid for the Popen() call to Python to succeed.
372 # See also issue #16170 and issue #7774.
373 doesnotexist = os.path.join(os.path.dirname(sys.executable),
374 "doesnotexist")
375 self._assert_python([doesnotexist, "-c"], executable=sys.executable)
376
377 def test_bytes_executable(self):
378 doesnotexist = os.path.join(os.path.dirname(sys.executable),
379 "doesnotexist")
380 self._assert_python([doesnotexist, "-c"],
381 executable=os.fsencode(sys.executable))
382
383 def test_pathlike_executable(self):
384 doesnotexist = os.path.join(os.path.dirname(sys.executable),
385 "doesnotexist")
386 self._assert_python([doesnotexist, "-c"],
387 executable=FakePath(sys.executable))
388
389 def test_executable_takes_precedence(self):
390 # Check that the executable argument takes precedence over args[0].
391 #
392 # Verify first that the call succeeds without the executable arg.
393 pre_args = [sys.executable, "-c"]
394 self._assert_python(pre_args)
395 self.assertRaises(NONEXISTING_ERRORS,
396 self._assert_python, pre_args,
397 executable=NONEXISTING_CMD[0])
398
399 @unittest.skipIf(mswindows, "executable argument replaces shell")
400 def test_executable_replaces_shell(self):
401 # Check that the executable argument replaces the default shell
402 # when shell=True.
403 self._assert_python([], executable=sys.executable, shell=True)
404
405 @unittest.skipIf(mswindows, "executable argument replaces shell")
406 def test_bytes_executable_replaces_shell(self):
407 self._assert_python([], executable=os.fsencode(sys.executable),
408 shell=True)
409
410 @unittest.skipIf(mswindows, "executable argument replaces shell")
411 def test_pathlike_executable_replaces_shell(self):
412 self._assert_python([], executable=FakePath(sys.executable),
413 shell=True)
414
415 # For use in the test_cwd* tests below.
416 def _normalize_cwd(self, cwd):
417 # Normalize an expected cwd (for Tru64 support).
418 # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
419 # strings. See bug #1063571.
420 with os_helper.change_cwd(cwd):
421 return os.getcwd()
422
423 # For use in the test_cwd* tests below.
424 def _split_python_path(self):
425 # Return normalized (python_dir, python_base).
426 python_path = os.path.realpath(sys.executable)
427 return os.path.split(python_path)
428
429 # For use in the test_cwd* tests below.
430 def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
431 # Invoke Python via Popen, and assert that (1) the call succeeds,
432 # and that (2) the current working directory of the child process
433 # matches *expected_cwd*.
434 p = subprocess.Popen([python_arg, "-c",
435 "import os, sys; "
436 "buf = sys.stdout.buffer; "
437 "buf.write(os.getcwd().encode()); "
438 "buf.flush(); "
439 "sys.exit(47)"],
440 stdout=subprocess.PIPE,
441 **kwargs)
442 self.addCleanup(p.stdout.close)
443 p.wait()
444 self.assertEqual(47, p.returncode)
445 normcase = os.path.normcase
446 self.assertEqual(normcase(expected_cwd),
447 normcase(p.stdout.read().decode()))
448
449 def test_cwd(self):
450 # Check that cwd changes the cwd for the child process.
451 temp_dir = tempfile.gettempdir()
452 temp_dir = self._normalize_cwd(temp_dir)
453 self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
454
455 def test_cwd_with_bytes(self):
456 temp_dir = tempfile.gettempdir()
457 temp_dir = self._normalize_cwd(temp_dir)
458 self._assert_cwd(temp_dir, sys.executable, cwd=os.fsencode(temp_dir))
459
460 def test_cwd_with_pathlike(self):
461 temp_dir = tempfile.gettempdir()
462 temp_dir = self._normalize_cwd(temp_dir)
463 self._assert_cwd(temp_dir, sys.executable, cwd=FakePath(temp_dir))
464
465 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
466 def test_cwd_with_relative_arg(self):
467 # Check that Popen looks for args[0] relative to cwd if args[0]
468 # is relative.
469 python_dir, python_base = self._split_python_path()
470 rel_python = os.path.join(os.curdir, python_base)
471 with os_helper.temp_cwd() as wrong_dir:
472 # Before calling with the correct cwd, confirm that the call fails
473 # without cwd and with the wrong cwd.
474 self.assertRaises(FileNotFoundError, subprocess.Popen,
475 [rel_python])
476 self.assertRaises(FileNotFoundError, subprocess.Popen,
477 [rel_python], cwd=wrong_dir)
478 python_dir = self._normalize_cwd(python_dir)
479 self._assert_cwd(python_dir, rel_python, cwd=python_dir)
480
481 @unittest.skipIf(mswindows, "pending resolution of issue #15533")
482 def test_cwd_with_relative_executable(self):
483 # Check that Popen looks for executable relative to cwd if executable
484 # is relative (and that executable takes precedence over args[0]).
485 python_dir, python_base = self._split_python_path()
486 rel_python = os.path.join(os.curdir, python_base)
487 doesntexist = "somethingyoudonthave"
488 with os_helper.temp_cwd() as wrong_dir:
489 # Before calling with the correct cwd, confirm that the call fails
490 # without cwd and with the wrong cwd.
491 self.assertRaises(FileNotFoundError, subprocess.Popen,
492 [doesntexist], executable=rel_python)
493 self.assertRaises(FileNotFoundError, subprocess.Popen,
494 [doesntexist], executable=rel_python,
495 cwd=wrong_dir)
496 python_dir = self._normalize_cwd(python_dir)
497 self._assert_cwd(python_dir, doesntexist, executable=rel_python,
498 cwd=python_dir)
499
500 def test_cwd_with_absolute_arg(self):
501 # Check that Popen can find the executable when the cwd is wrong
502 # if args[0] is an absolute path.
503 python_dir, python_base = self._split_python_path()
504 abs_python = os.path.join(python_dir, python_base)
505 rel_python = os.path.join(os.curdir, python_base)
506 with os_helper.temp_dir() as wrong_dir:
507 # Before calling with an absolute path, confirm that using a
508 # relative path fails.
509 self.assertRaises(FileNotFoundError, subprocess.Popen,
510 [rel_python], cwd=wrong_dir)
511 wrong_dir = self._normalize_cwd(wrong_dir)
512 self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
513
514 @unittest.skipIf(sys.base_prefix != sys.prefix,
515 'Test is not venv-compatible')
516 def test_executable_with_cwd(self):
517 python_dir, python_base = self._split_python_path()
518 python_dir = self._normalize_cwd(python_dir)
519 self._assert_cwd(python_dir, "somethingyoudonthave",
520 executable=sys.executable, cwd=python_dir)
521
522 @unittest.skipIf(sys.base_prefix != sys.prefix,
523 'Test is not venv-compatible')
524 @unittest.skipIf(sysconfig.is_python_build(),
525 "need an installed Python. See #7774")
526 def test_executable_without_cwd(self):
527 # For a normal installation, it should work without 'cwd'
528 # argument. For test runs in the build directory, see #7774.
529 self._assert_cwd(os.getcwd(), "somethingyoudonthave",
530 executable=sys.executable)
531
532 def test_stdin_pipe(self):
533 # stdin redirection
534 p = subprocess.Popen([sys.executable, "-c",
535 'import sys; sys.exit(sys.stdin.read() == "pear")'],
536 stdin=subprocess.PIPE)
537 p.stdin.write(b"pear")
538 p.stdin.close()
539 p.wait()
540 self.assertEqual(p.returncode, 1)
541
542 def test_stdin_filedes(self):
543 # stdin is set to open file descriptor
544 tf = tempfile.TemporaryFile()
545 self.addCleanup(tf.close)
546 d = tf.fileno()
547 os.write(d, b"pear")
548 os.lseek(d, 0, 0)
549 p = subprocess.Popen([sys.executable, "-c",
550 'import sys; sys.exit(sys.stdin.read() == "pear")'],
551 stdin=d)
552 p.wait()
553 self.assertEqual(p.returncode, 1)
554
555 def test_stdin_fileobj(self):
556 # stdin is set to open file object
557 tf = tempfile.TemporaryFile()
558 self.addCleanup(tf.close)
559 tf.write(b"pear")
560 tf.seek(0)
561 p = subprocess.Popen([sys.executable, "-c",
562 'import sys; sys.exit(sys.stdin.read() == "pear")'],
563 stdin=tf)
564 p.wait()
565 self.assertEqual(p.returncode, 1)
566
567 def test_stdout_pipe(self):
568 # stdout redirection
569 p = subprocess.Popen([sys.executable, "-c",
570 'import sys; sys.stdout.write("orange")'],
571 stdout=subprocess.PIPE)
572 with p:
573 self.assertEqual(p.stdout.read(), b"orange")
574
575 def test_stdout_filedes(self):
576 # stdout is set to open file descriptor
577 tf = tempfile.TemporaryFile()
578 self.addCleanup(tf.close)
579 d = tf.fileno()
580 p = subprocess.Popen([sys.executable, "-c",
581 'import sys; sys.stdout.write("orange")'],
582 stdout=d)
583 p.wait()
584 os.lseek(d, 0, 0)
585 self.assertEqual(os.read(d, 1024), b"orange")
586
587 def test_stdout_fileobj(self):
588 # stdout is set to open file object
589 tf = tempfile.TemporaryFile()
590 self.addCleanup(tf.close)
591 p = subprocess.Popen([sys.executable, "-c",
592 'import sys; sys.stdout.write("orange")'],
593 stdout=tf)
594 p.wait()
595 tf.seek(0)
596 self.assertEqual(tf.read(), b"orange")
597
598 def test_stderr_pipe(self):
599 # stderr redirection
600 p = subprocess.Popen([sys.executable, "-c",
601 'import sys; sys.stderr.write("strawberry")'],
602 stderr=subprocess.PIPE)
603 with p:
604 self.assertEqual(p.stderr.read(), b"strawberry")
605
606 def test_stderr_filedes(self):
607 # stderr is set to open file descriptor
608 tf = tempfile.TemporaryFile()
609 self.addCleanup(tf.close)
610 d = tf.fileno()
611 p = subprocess.Popen([sys.executable, "-c",
612 'import sys; sys.stderr.write("strawberry")'],
613 stderr=d)
614 p.wait()
615 os.lseek(d, 0, 0)
616 self.assertEqual(os.read(d, 1024), b"strawberry")
617
618 def test_stderr_fileobj(self):
619 # stderr is set to open file object
620 tf = tempfile.TemporaryFile()
621 self.addCleanup(tf.close)
622 p = subprocess.Popen([sys.executable, "-c",
623 'import sys; sys.stderr.write("strawberry")'],
624 stderr=tf)
625 p.wait()
626 tf.seek(0)
627 self.assertEqual(tf.read(), b"strawberry")
628
629 def test_stderr_redirect_with_no_stdout_redirect(self):
630 # test stderr=STDOUT while stdout=None (not set)
631
632 # - grandchild prints to stderr
633 # - child redirects grandchild's stderr to its stdout
634 # - the parent should get grandchild's stderr in child's stdout
635 p = subprocess.Popen([sys.executable, "-c",
636 'import sys, subprocess;'
637 'rc = subprocess.call([sys.executable, "-c",'
638 ' "import sys;"'
639 ' "sys.stderr.write(\'42\')"],'
640 ' stderr=subprocess.STDOUT);'
641 'sys.exit(rc)'],
642 stdout=subprocess.PIPE,
643 stderr=subprocess.PIPE)
644 stdout, stderr = p.communicate()
645 #NOTE: stdout should get stderr from grandchild
646 self.assertEqual(stdout, b'42')
647 self.assertEqual(stderr, b'') # should be empty
648 self.assertEqual(p.returncode, 0)
649
650 def test_stdout_stderr_pipe(self):
651 # capture stdout and stderr to the same pipe
652 p = subprocess.Popen([sys.executable, "-c",
653 'import sys;'
654 'sys.stdout.write("apple");'
655 'sys.stdout.flush();'
656 'sys.stderr.write("orange")'],
657 stdout=subprocess.PIPE,
658 stderr=subprocess.STDOUT)
659 with p:
660 self.assertEqual(p.stdout.read(), b"appleorange")
661
662 def test_stdout_stderr_file(self):
663 # capture stdout and stderr to the same open file
664 tf = tempfile.TemporaryFile()
665 self.addCleanup(tf.close)
666 p = subprocess.Popen([sys.executable, "-c",
667 'import sys;'
668 'sys.stdout.write("apple");'
669 'sys.stdout.flush();'
670 'sys.stderr.write("orange")'],
671 stdout=tf,
672 stderr=tf)
673 p.wait()
674 tf.seek(0)
675 self.assertEqual(tf.read(), b"appleorange")
676
677 def test_stdout_filedes_of_stdout(self):
678 # stdout is set to 1 (#1531862).
679 # To avoid printing the text on stdout, we do something similar to
680 # test_stdout_none (see above). The parent subprocess calls the child
681 # subprocess passing stdout=1, and this test uses stdout=PIPE in
682 # order to capture and check the output of the parent. See #11963.
683 code = ('import sys, subprocess; '
684 'rc = subprocess.call([sys.executable, "-c", '
685 ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
686 'b\'test with stdout=1\'))"], stdout=1); '
687 'assert rc == 18')
688 p = subprocess.Popen([sys.executable, "-c", code],
689 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
690 self.addCleanup(p.stdout.close)
691 self.addCleanup(p.stderr.close)
692 out, err = p.communicate()
693 self.assertEqual(p.returncode, 0, err)
694 self.assertEqual(out.rstrip(), b'test with stdout=1')
695
696 def test_stdout_devnull(self):
697 p = subprocess.Popen([sys.executable, "-c",
698 'for i in range(10240):'
699 'print("x" * 1024)'],
700 stdout=subprocess.DEVNULL)
701 p.wait()
702 self.assertEqual(p.stdout, None)
703
704 def test_stderr_devnull(self):
705 p = subprocess.Popen([sys.executable, "-c",
706 'import sys\n'
707 'for i in range(10240):'
708 'sys.stderr.write("x" * 1024)'],
709 stderr=subprocess.DEVNULL)
710 p.wait()
711 self.assertEqual(p.stderr, None)
712
713 def test_stdin_devnull(self):
714 p = subprocess.Popen([sys.executable, "-c",
715 'import sys;'
716 'sys.stdin.read(1)'],
717 stdin=subprocess.DEVNULL)
718 p.wait()
719 self.assertEqual(p.stdin, None)
720
721 @unittest.skipUnless(fcntl and hasattr(fcntl, 'F_GETPIPE_SZ'),
722 'fcntl.F_GETPIPE_SZ required for test.')
723 def test_pipesizes(self):
724 test_pipe_r, test_pipe_w = os.pipe()
725 try:
726 # Get the default pipesize with F_GETPIPE_SZ
727 pipesize_default = fcntl.fcntl(test_pipe_w, fcntl.F_GETPIPE_SZ)
728 finally:
729 os.close(test_pipe_r)
730 os.close(test_pipe_w)
731 pipesize = pipesize_default // 2
732 pagesize_default = support.get_pagesize()
733 if pipesize < pagesize_default: # the POSIX minimum
734 raise unittest.SkipTest(
735 'default pipesize too small to perform test.')
736 p = subprocess.Popen(
737 [sys.executable, "-c",
738 'import sys; sys.stdin.read(); sys.stdout.write("out"); '
739 'sys.stderr.write("error!")'],
740 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
741 stderr=subprocess.PIPE, pipesize=pipesize)
742 try:
743 for fifo in [p.stdin, p.stdout, p.stderr]:
744 self.assertEqual(
745 fcntl.fcntl(fifo.fileno(), fcntl.F_GETPIPE_SZ),
746 pipesize)
747 # Windows pipe size can be acquired via GetNamedPipeInfoFunction
748 # https://docs.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-getnamedpipeinfo
749 # However, this function is not yet in _winapi.
750 p.stdin.write(b"pear")
751 p.stdin.close()
752 p.stdout.close()
753 p.stderr.close()
754 finally:
755 p.kill()
756 p.wait()
757
758 @unittest.skipUnless(fcntl and hasattr(fcntl, 'F_GETPIPE_SZ'),
759 'fcntl.F_GETPIPE_SZ required for test.')
760 def test_pipesize_default(self):
761 proc = subprocess.Popen(
762 [sys.executable, "-c",
763 'import sys; sys.stdin.read(); sys.stdout.write("out"); '
764 'sys.stderr.write("error!")'],
765 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
766 stderr=subprocess.PIPE, pipesize=-1)
767
768 with proc:
769 try:
770 fp_r, fp_w = os.pipe()
771 try:
772 default_read_pipesize = fcntl.fcntl(fp_r, fcntl.F_GETPIPE_SZ)
773 default_write_pipesize = fcntl.fcntl(fp_w, fcntl.F_GETPIPE_SZ)
774 finally:
775 os.close(fp_r)
776 os.close(fp_w)
777
778 self.assertEqual(
779 fcntl.fcntl(proc.stdin.fileno(), fcntl.F_GETPIPE_SZ),
780 default_read_pipesize)
781 self.assertEqual(
782 fcntl.fcntl(proc.stdout.fileno(), fcntl.F_GETPIPE_SZ),
783 default_write_pipesize)
784 self.assertEqual(
785 fcntl.fcntl(proc.stderr.fileno(), fcntl.F_GETPIPE_SZ),
786 default_write_pipesize)
787 # On other platforms we cannot test the pipe size (yet). But above
788 # code using pipesize=-1 should not crash.
789 finally:
790 proc.kill()
791
792 def test_env(self):
793 newenv = os.environ.copy()
794 newenv["FRUIT"] = "orange"
795 with subprocess.Popen([sys.executable, "-c",
796 'import sys,os;'
797 'sys.stdout.write(os.getenv("FRUIT"))'],
798 stdout=subprocess.PIPE,
799 env=newenv) as p:
800 stdout, stderr = p.communicate()
801 self.assertEqual(stdout, b"orange")
802
803 @unittest.skipUnless(sys.platform == "win32", "Windows only issue")
804 def test_win32_duplicate_envs(self):
805 newenv = os.environ.copy()
806 newenv["fRUit"] = "cherry"
807 newenv["fruit"] = "lemon"
808 newenv["FRUIT"] = "orange"
809 newenv["frUit"] = "banana"
810 with subprocess.Popen(["CMD", "/c", "SET", "fruit"],
811 stdout=subprocess.PIPE,
812 env=newenv) as p:
813 stdout, _ = p.communicate()
814 self.assertEqual(stdout.strip(), b"frUit=banana")
815
816 # Windows requires at least the SYSTEMROOT environment variable to start
817 # Python
818 @unittest.skipIf(sys.platform == 'win32',
819 'cannot test an empty env on Windows')
820 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
821 'The Python shared library cannot be loaded '
822 'with an empty environment.')
823 @unittest.skipIf(check_sanitizer(address=True),
824 'AddressSanitizer adds to the environment.')
825 def test_empty_env(self):
826 """Verify that env={} is as empty as possible."""
827
828 def is_env_var_to_ignore(n):
829 """Determine if an environment variable is under our control."""
830 # This excludes some __CF_* and VERSIONER_* keys MacOS insists
831 # on adding even when the environment in exec is empty.
832 # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist.
833 return ('VERSIONER' in n or '__CF' in n or # MacOS
834 n == 'LD_PRELOAD' or n.startswith('SANDBOX') or # Gentoo
835 n == 'LC_CTYPE') # Locale coercion triggered
836
837 with subprocess.Popen([sys.executable, "-c",
838 'import os; print(list(os.environ.keys()))'],
839 stdout=subprocess.PIPE, env={}) as p:
840 stdout, stderr = p.communicate()
841 child_env_names = eval(stdout.strip())
842 self.assertIsInstance(child_env_names, list)
843 child_env_names = [k for k in child_env_names
844 if not is_env_var_to_ignore(k)]
845 self.assertEqual(child_env_names, [])
846
847 @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
848 'The Python shared library cannot be loaded '
849 'without some system environments.')
850 @unittest.skipIf(check_sanitizer(address=True),
851 'AddressSanitizer adds to the environment.')
852 def test_one_environment_variable(self):
853 newenv = {'fruit': 'orange'}
854 cmd = [sys.executable, '-c',
855 'import sys,os;'
856 'sys.stdout.write("fruit="+os.getenv("fruit"))']
857 if sys.platform == "win32":
858 cmd = ["CMD", "/c", "SET", "fruit"]
859 with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=newenv) as p:
860 stdout, stderr = p.communicate()
861 if p.returncode and support.verbose:
862 print("STDOUT:", stdout.decode("ascii", "replace"))
863 print("STDERR:", stderr.decode("ascii", "replace"))
864 self.assertEqual(p.returncode, 0)
865 self.assertEqual(stdout.strip(), b"fruit=orange")
866
867 def test_invalid_cmd(self):
868 # null character in the command name
869 cmd = sys.executable + '\0'
870 with self.assertRaises(ValueError):
871 subprocess.Popen([cmd, "-c", "pass"])
872
873 # null character in the command argument
874 with self.assertRaises(ValueError):
875 subprocess.Popen([sys.executable, "-c", "pass#\0"])
876
877 def test_invalid_env(self):
878 # null character in the environment variable name
879 newenv = os.environ.copy()
880 newenv["FRUIT\0VEGETABLE"] = "cabbage"
881 with self.assertRaises(ValueError):
882 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
883
884 # null character in the environment variable value
885 newenv = os.environ.copy()
886 newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
887 with self.assertRaises(ValueError):
888 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
889
890 # equal character in the environment variable name
891 newenv = os.environ.copy()
892 newenv["FRUIT=ORANGE"] = "lemon"
893 with self.assertRaises(ValueError):
894 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
895
896 # equal character in the environment variable value
897 newenv = os.environ.copy()
898 newenv["FRUIT"] = "orange=lemon"
899 with subprocess.Popen([sys.executable, "-c",
900 'import sys, os;'
901 'sys.stdout.write(os.getenv("FRUIT"))'],
902 stdout=subprocess.PIPE,
903 env=newenv) as p:
904 stdout, stderr = p.communicate()
905 self.assertEqual(stdout, b"orange=lemon")
906
907 @unittest.skipUnless(sys.platform == "win32", "Windows only issue")
908 def test_win32_invalid_env(self):
909 # '=' in the environment variable name
910 newenv = os.environ.copy()
911 newenv["FRUIT=VEGETABLE"] = "cabbage"
912 with self.assertRaises(ValueError):
913 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
914
915 newenv = os.environ.copy()
916 newenv["==FRUIT"] = "cabbage"
917 with self.assertRaises(ValueError):
918 subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
919
920 def test_communicate_stdin(self):
921 p = subprocess.Popen([sys.executable, "-c",
922 'import sys;'
923 'sys.exit(sys.stdin.read() == "pear")'],
924 stdin=subprocess.PIPE)
925 p.communicate(b"pear")
926 self.assertEqual(p.returncode, 1)
927
928 def test_communicate_stdout(self):
929 p = subprocess.Popen([sys.executable, "-c",
930 'import sys; sys.stdout.write("pineapple")'],
931 stdout=subprocess.PIPE)
932 (stdout, stderr) = p.communicate()
933 self.assertEqual(stdout, b"pineapple")
934 self.assertEqual(stderr, None)
935
936 def test_communicate_stderr(self):
937 p = subprocess.Popen([sys.executable, "-c",
938 'import sys; sys.stderr.write("pineapple")'],
939 stderr=subprocess.PIPE)
940 (stdout, stderr) = p.communicate()
941 self.assertEqual(stdout, None)
942 self.assertEqual(stderr, b"pineapple")
943
944 def test_communicate(self):
945 p = subprocess.Popen([sys.executable, "-c",
946 'import sys,os;'
947 'sys.stderr.write("pineapple");'
948 'sys.stdout.write(sys.stdin.read())'],
949 stdin=subprocess.PIPE,
950 stdout=subprocess.PIPE,
951 stderr=subprocess.PIPE)
952 self.addCleanup(p.stdout.close)
953 self.addCleanup(p.stderr.close)
954 self.addCleanup(p.stdin.close)
955 (stdout, stderr) = p.communicate(b"banana")
956 self.assertEqual(stdout, b"banana")
957 self.assertEqual(stderr, b"pineapple")
958
959 def test_communicate_memoryview_input(self):
960 # Test memoryview input with byte elements
961 test_data = b"Hello, memoryview!"
962 mv = memoryview(test_data)
963 p = subprocess.Popen([sys.executable, "-c",
964 'import sys; sys.stdout.write(sys.stdin.read())'],
965 stdin=subprocess.PIPE,
966 stdout=subprocess.PIPE)
967 self.addCleanup(p.stdout.close)
968 self.addCleanup(p.stdin.close)
969 (stdout, stderr) = p.communicate(mv)
970 self.assertEqual(stdout, test_data)
971 self.assertIsNone(stderr)
972
973 def test_communicate_memoryview_input_nonbyte(self):
974 # Test memoryview input with non-byte elements (e.g., int32)
975 # This tests the fix for gh-134453 where non-byte memoryviews
976 # had incorrect length tracking on POSIX
977 import array
978 # Create an array of 32-bit integers that's large enough to trigger
979 # the chunked writing behavior (> PIPE_BUF)
980 pipe_buf = getattr(select, 'PIPE_BUF', 512)
981 # Each 'i' element is 4 bytes, so we need more than pipe_buf/4 elements
982 # Add some extra to ensure we exceed the buffer size
983 num_elements = pipe_buf + 1
984 test_array = array.array('i', [0x64306f66 for _ in range(num_elements)])
985 expected_bytes = test_array.tobytes()
986 mv = memoryview(test_array)
987
988 p = subprocess.Popen([sys.executable, "-c",
989 'import sys; '
990 'data = sys.stdin.buffer.read(); '
991 'sys.stdout.buffer.write(data)'],
992 stdin=subprocess.PIPE,
993 stdout=subprocess.PIPE)
994 self.addCleanup(p.stdout.close)
995 self.addCleanup(p.stdin.close)
996 (stdout, stderr) = p.communicate(mv)
997 self.assertEqual(stdout, expected_bytes,
998 msg=f"{len(stdout)=} =? {len(expected_bytes)=}")
999 self.assertIsNone(stderr)
1000
1001 def test_communicate_timeout(self):
1002 p = subprocess.Popen([sys.executable, "-c",
1003 'import sys,os,time;'
1004 'sys.stderr.write("pineapple\\n");'
1005 'time.sleep(1);'
1006 'sys.stderr.write("pear\\n");'
1007 'sys.stdout.write(sys.stdin.read())'],
1008 universal_newlines=True,
1009 stdin=subprocess.PIPE,
1010 stdout=subprocess.PIPE,
1011 stderr=subprocess.PIPE)
1012 self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
1013 timeout=0.3)
1014 # Make sure we can keep waiting for it, and that we get the whole output
1015 # after it completes.
1016 (stdout, stderr) = p.communicate()
1017 self.assertEqual(stdout, "banana")
1018 self.assertEqual(stderr.encode(), b"pineapple\npear\n")
1019
1020 def test_communicate_timeout_large_output(self):
1021 # Test an expiring timeout while the child is outputting lots of data.
1022 p = subprocess.Popen([sys.executable, "-c",
1023 'import sys,os,time;'
1024 'sys.stdout.write("a" * (64 * 1024));'
1025 'time.sleep(0.2);'
1026 'sys.stdout.write("a" * (64 * 1024));'
1027 'time.sleep(0.2);'
1028 'sys.stdout.write("a" * (64 * 1024));'
1029 'time.sleep(0.2);'
1030 'sys.stdout.write("a" * (64 * 1024));'],
1031 stdout=subprocess.PIPE)
1032 self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
1033 (stdout, _) = p.communicate()
1034 self.assertEqual(len(stdout), 4 * 64 * 1024)
1035
1036 def test_communicate_timeout_large_input(self):
1037 # Test that timeout is enforced when writing large input to a
1038 # slow-to-read subprocess, and that partial input is preserved
1039 # for continuation after timeout (gh-141473).
1040 #
1041 # This is a regression test for Windows matching POSIX behavior.
1042 # On POSIX, select() is used to multiplex I/O with timeout checking.
1043 # On Windows, stdin writing must also honor the timeout rather than
1044 # blocking indefinitely when the pipe buffer fills.
1045
1046 # Input larger than typical pipe buffer (4-64KB on Windows)
1047 input_data = b"x" * (128 * 1024)
1048
1049 p = subprocess.Popen(
1050 [sys.executable, "-c",
1051 "import sys, time; "
1052 "time.sleep(30); " # Don't read stdin for a long time
1053 "sys.stdout.buffer.write(sys.stdin.buffer.read())"],
1054 stdin=subprocess.PIPE,
1055 stdout=subprocess.PIPE,
1056 stderr=subprocess.PIPE)
1057
1058 try:
1059 timeout = 0.2
1060 start = time.monotonic()
1061 try:
1062 p.communicate(input_data, timeout=timeout)
1063 # If we get here without TimeoutExpired, the timeout was ignored
1064 elapsed = time.monotonic() - start
1065 self.fail(
1066 f"TimeoutExpired not raised. communicate() completed in "
1067 f"{elapsed:.2f}s, but subprocess sleeps for 30s. "
1068 "Stdin writing blocked without enforcing timeout.")
1069 except subprocess.TimeoutExpired:
1070 elapsed = time.monotonic() - start
1071
1072 # Timeout should occur close to the specified timeout value,
1073 # not after waiting for the subprocess to finish sleeping.
1074 # Allow generous margin for slow CI, but must be well under
1075 # the subprocess sleep time.
1076 self.assertLess(elapsed, 5.0,
1077 f"TimeoutExpired raised after {elapsed:.2f}s; expected ~{timeout}s. "
1078 "Stdin writing blocked without checking timeout.")
1079
1080 # After timeout, continue communication. The remaining input
1081 # should be sent and we should receive all data back.
1082 stdout, stderr = p.communicate()
1083
1084 # Verify all input was eventually received by the subprocess
1085 self.assertEqual(len(stdout), len(input_data),
1086 f"Expected {len(input_data)} bytes output but got {len(stdout)}")
1087 self.assertEqual(stdout, input_data)
1088 finally:
1089 p.kill()
1090 p.wait()
1091
1092 # Test for the fd leak reported in http://bugs.python.org/issue2791.
1093 def test_communicate_pipe_fd_leak(self):
1094 for stdin_pipe in (False, True):
1095 for stdout_pipe in (False, True):
1096 for stderr_pipe in (False, True):
1097 options = {}
1098 if stdin_pipe:
1099 options['stdin'] = subprocess.PIPE
1100 if stdout_pipe:
1101 options['stdout'] = subprocess.PIPE
1102 if stderr_pipe:
1103 options['stderr'] = subprocess.PIPE
1104 if not options:
1105 continue
1106 p = subprocess.Popen(ZERO_RETURN_CMD, **options)
1107 p.communicate()
1108 if p.stdin is not None:
1109 self.assertTrue(p.stdin.closed)
1110 if p.stdout is not None:
1111 self.assertTrue(p.stdout.closed)
1112 if p.stderr is not None:
1113 self.assertTrue(p.stderr.closed)
1114
1115 def test_communicate_returns(self):
1116 # communicate() should return None if no redirection is active
1117 p = subprocess.Popen([sys.executable, "-c",
1118 "import sys; sys.exit(47)"])
1119 (stdout, stderr) = p.communicate()
1120 self.assertEqual(stdout, None)
1121 self.assertEqual(stderr, None)
1122
1123 def test_communicate_pipe_buf(self):
1124 # communicate() with writes larger than pipe_buf
1125 # This test will probably deadlock rather than fail, if
1126 # communicate() does not work properly.
1127 x, y = os.pipe()
1128 os.close(x)
1129 os.close(y)
1130 p = subprocess.Popen([sys.executable, "-c",
1131 'import sys,os;'
1132 'sys.stdout.write(sys.stdin.read(47));'
1133 'sys.stderr.write("x" * %d);'
1134 'sys.stdout.write(sys.stdin.read())' %
1135 support.PIPE_MAX_SIZE],
1136 stdin=subprocess.PIPE,
1137 stdout=subprocess.PIPE,
1138 stderr=subprocess.PIPE)
1139 self.addCleanup(p.stdout.close)
1140 self.addCleanup(p.stderr.close)
1141 self.addCleanup(p.stdin.close)
1142 string_to_write = b"a" * support.PIPE_MAX_SIZE
1143 (stdout, stderr) = p.communicate(string_to_write)
1144 self.assertEqual(stdout, string_to_write)
1145
1146 def test_writes_before_communicate(self):
1147 # stdin.write before communicate()
1148 p = subprocess.Popen([sys.executable, "-c",
1149 'import sys,os;'
1150 'sys.stdout.write(sys.stdin.read())'],
1151 stdin=subprocess.PIPE,
1152 stdout=subprocess.PIPE,
1153 stderr=subprocess.PIPE)
1154 self.addCleanup(p.stdout.close)
1155 self.addCleanup(p.stderr.close)
1156 self.addCleanup(p.stdin.close)
1157 p.stdin.write(b"banana")
1158 (stdout, stderr) = p.communicate(b"split")
1159 self.assertEqual(stdout, b"bananasplit")
1160 self.assertEqual(stderr, b"")
1161
1162 def test_communicate_stdin_closed_before_call(self):
1163 # gh-70560, gh-74389: stdin.close() before communicate()
1164 # should not raise ValueError from stdin.flush()
1165 with subprocess.Popen([sys.executable, "-c",
1166 'import sys; sys.exit(0)'],
1167 stdin=subprocess.PIPE,
1168 stdout=subprocess.PIPE,
1169 stderr=subprocess.PIPE) as p:
1170 p.stdin.close() # Close stdin before communicate
1171 # This should not raise ValueError
1172 (stdout, stderr) = p.communicate()
1173 self.assertEqual(p.returncode, 0)
1174
1175 def test_universal_newlines_and_text(self):
1176 args = [
1177 sys.executable, "-c",
1178 'import sys,os;' + SETBINARY +
1179 'buf = sys.stdout.buffer;'
1180 'buf.write(sys.stdin.readline().encode());'
1181 'buf.flush();'
1182 'buf.write(b"line2\\n");'
1183 'buf.flush();'
1184 'buf.write(sys.stdin.read().encode());'
1185 'buf.flush();'
1186 'buf.write(b"line4\\n");'
1187 'buf.flush();'
1188 'buf.write(b"line5\\r\\n");'
1189 'buf.flush();'
1190 'buf.write(b"line6\\r");'
1191 'buf.flush();'
1192 'buf.write(b"\\nline7");'
1193 'buf.flush();'
1194 'buf.write(b"\\nline8");']
1195
1196 for extra_kwarg in ('universal_newlines', 'text'):
1197 p = subprocess.Popen(args, **{'stdin': subprocess.PIPE,
1198 'stdout': subprocess.PIPE,
1199 extra_kwarg: True})
1200 with p:
1201 p.stdin.write("line1\n")
1202 p.stdin.flush()
1203 self.assertEqual(p.stdout.readline(), "line1\n")
1204 p.stdin.write("line3\n")
1205 p.stdin.close()
1206 self.addCleanup(p.stdout.close)
1207 self.assertEqual(p.stdout.readline(),
1208 "line2\n")
1209 self.assertEqual(p.stdout.read(6),
1210 "line3\n")
1211 self.assertEqual(p.stdout.read(),
1212 "line4\nline5\nline6\nline7\nline8")
1213
1214 def test_universal_newlines_communicate(self):
1215 # universal newlines through communicate()
1216 p = subprocess.Popen([sys.executable, "-c",
1217 'import sys,os;' + SETBINARY +
1218 'buf = sys.stdout.buffer;'
1219 'buf.write(b"line2\\n");'
1220 'buf.flush();'
1221 'buf.write(b"line4\\n");'
1222 'buf.flush();'
1223 'buf.write(b"line5\\r\\n");'
1224 'buf.flush();'
1225 'buf.write(b"line6\\r");'
1226 'buf.flush();'
1227 'buf.write(b"\\nline7");'
1228 'buf.flush();'
1229 'buf.write(b"\\nline8");'],
1230 stderr=subprocess.PIPE,
1231 stdout=subprocess.PIPE,
1232 universal_newlines=1)
1233 self.addCleanup(p.stdout.close)
1234 self.addCleanup(p.stderr.close)
1235 (stdout, stderr) = p.communicate()
1236 self.assertEqual(stdout,
1237 "line2\nline4\nline5\nline6\nline7\nline8")
1238
1239 def test_universal_newlines_communicate_stdin(self):
1240 # universal newlines through communicate(), with only stdin
1241 p = subprocess.Popen([sys.executable, "-c",
1242 'import sys,os;' + SETBINARY + textwrap.dedent('''
1243 s = sys.stdin.readline()
1244 assert s == "line1\\n", repr(s)
1245 s = sys.stdin.read()
1246 assert s == "line3\\n", repr(s)
1247 ''')],
1248 stdin=subprocess.PIPE,
1249 universal_newlines=1)
1250 (stdout, stderr) = p.communicate("line1\nline3\n")
1251 self.assertEqual(p.returncode, 0)
1252
1253 def test_universal_newlines_communicate_input_none(self):
1254 # Test communicate(input=None) with universal newlines.
1255 #
1256 # We set stdout to PIPE because, as of this writing, a different
1257 # code path is tested when the number of pipes is zero or one.
1258 p = subprocess.Popen(ZERO_RETURN_CMD,
1259 stdin=subprocess.PIPE,
1260 stdout=subprocess.PIPE,
1261 universal_newlines=True)
1262 p.communicate()
1263 self.assertEqual(p.returncode, 0)
1264
1265 def test_universal_newlines_communicate_stdin_stdout_stderr(self):
1266 # universal newlines through communicate(), with stdin, stdout, stderr
1267 p = subprocess.Popen([sys.executable, "-c",
1268 'import sys,os;' + SETBINARY + textwrap.dedent('''
1269 s = sys.stdin.buffer.readline()
1270 sys.stdout.buffer.write(s)
1271 sys.stdout.buffer.write(b"line2\\r")
1272 sys.stderr.buffer.write(b"eline2\\n")
1273 s = sys.stdin.buffer.read()
1274 sys.stdout.buffer.write(s)
1275 sys.stdout.buffer.write(b"line4\\n")
1276 sys.stdout.buffer.write(b"line5\\r\\n")
1277 sys.stderr.buffer.write(b"eline6\\r")
1278 sys.stderr.buffer.write(b"eline7\\r\\nz")
1279 ''')],
1280 stdin=subprocess.PIPE,
1281 stderr=subprocess.PIPE,
1282 stdout=subprocess.PIPE,
1283 universal_newlines=True)
1284 self.addCleanup(p.stdout.close)
1285 self.addCleanup(p.stderr.close)
1286 (stdout, stderr) = p.communicate("line1\nline3\n")
1287 self.assertEqual(p.returncode, 0)
1288 self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
1289 # Python debug build push something like "[42442 refs]\n"
1290 # to stderr at exit of subprocess.
1291 self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
1292
1293 def test_universal_newlines_communicate_encodings(self):
1294 # Check that universal newlines mode works for various encodings,
1295 # in particular for encodings in the UTF-16 and UTF-32 families.
1296 # See issue #15595.
1297 #
1298 # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
1299 # without, and UTF-16 and UTF-32.
1300 for encoding in ['utf-16', 'utf-32-be']:
1301 code = ("import sys; "
1302 r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
1303 encoding)
1304 args = [sys.executable, '-c', code]
1305 # We set stdin to be non-None because, as of this writing,
1306 # a different code path is used when the number of pipes is
1307 # zero or one.
1308 popen = subprocess.Popen(args,
1309 stdin=subprocess.PIPE,
1310 stdout=subprocess.PIPE,
1311 encoding=encoding)
1312 stdout, stderr = popen.communicate(input='')
1313 self.assertEqual(stdout, '1\n2\n3\n4')
1314
1315 def test_communicate_errors(self):
1316 for errors, expected in [
1317 ('ignore', ''),
1318 ('replace', '\ufffd\ufffd'),
1319 ('surrogateescape', '\udc80\udc80'),
1320 ('backslashreplace', '\\x80\\x80'),
1321 ]:
1322 code = ("import sys; "
1323 r"sys.stdout.buffer.write(b'[\x80\x80]')")
1324 args = [sys.executable, '-c', code]
1325 # We set stdin to be non-None because, as of this writing,
1326 # a different code path is used when the number of pipes is
1327 # zero or one.
1328 popen = subprocess.Popen(args,
1329 stdin=subprocess.PIPE,
1330 stdout=subprocess.PIPE,
1331 encoding='utf-8',
1332 errors=errors)
1333 stdout, stderr = popen.communicate(input='')
1334 self.assertEqual(stdout, '[{}]'.format(expected))
1335
1336 def test_no_leaking(self):
1337 # Make sure we leak no resources
1338 if not mswindows:
1339 max_handles = 1026 # too much for most UNIX systems
1340 else:
1341 max_handles = 2050 # too much for (at least some) Windows setups
1342 if resource:
1343 # And if it is not too much, try to make it too much.
1344 try:
1345 soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
1346 if soft > 1024:
1347 resource.setrlimit(resource.RLIMIT_NOFILE, (1024, hard))
1348 self.addCleanup(resource.setrlimit, resource.RLIMIT_NOFILE,
1349 (soft, hard))
1350 except (OSError, ValueError):
1351 pass
1352 handles = []
1353 tmpdir = tempfile.mkdtemp()
1354 try:
1355 for i in range(max_handles):
1356 try:
1357 tmpfile = os.path.join(tmpdir, os_helper.TESTFN)
1358 handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
1359 except OSError as e:
1360 if e.errno != errno.EMFILE:
1361 raise
1362 break
1363 else:
1364 self.skipTest("failed to reach the file descriptor limit "
1365 "(tried %d)" % max_handles)
1366 # Close a couple of them (should be enough for a subprocess).
1367 # Close lower file descriptors, so select() will work.
1368 handles.reverse()
1369 for i in range(10):
1370 os.close(handles.pop())
1371 # Loop creating some subprocesses. If one of them leaks some fds,
1372 # the next loop iteration will fail by reaching the max fd limit.
1373 for i in range(15):
1374 p = subprocess.Popen([sys.executable, "-c",
1375 "import sys;"
1376 "sys.stdout.write(sys.stdin.read())"],
1377 stdin=subprocess.PIPE,
1378 stdout=subprocess.PIPE,
1379 stderr=subprocess.PIPE)
1380 data = p.communicate(b"lime")[0]
1381 self.assertEqual(data, b"lime")
1382 finally:
1383 for h in handles:
1384 os.close(h)
1385 shutil.rmtree(tmpdir)
1386
1387 def test_list2cmdline(self):
1388 self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
1389 '"a b c" d e')
1390 self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
1391 'ab\\"c \\ d')
1392 self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
1393 'ab\\"c " \\\\" d')
1394 self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
1395 'a\\\\\\b "de fg" h')
1396 self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
1397 'a\\\\\\"b c d')
1398 self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
1399 '"a\\\\b c" d e')
1400 self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
1401 '"a\\\\b\\ c" d e')
1402 self.assertEqual(subprocess.list2cmdline(['ab', '']),
1403 'ab ""')
1404
1405 def test_poll(self):
1406 p = subprocess.Popen([sys.executable, "-c",
1407 "import os; os.read(0, 1)"],
1408 stdin=subprocess.PIPE)
1409 self.addCleanup(p.stdin.close)
1410 self.assertIsNone(p.poll())
1411 os.write(p.stdin.fileno(), b'A')
1412 p.wait()
1413 # Subsequent invocations should just return the returncode
1414 self.assertEqual(p.poll(), 0)
1415
1416 def test_wait(self):
1417 p = subprocess.Popen(ZERO_RETURN_CMD)
1418 self.assertEqual(p.wait(), 0)
1419 # Subsequent invocations should just return the returncode
1420 self.assertEqual(p.wait(), 0)
1421
1422 def test_wait_timeout(self):
1423 p = subprocess.Popen([sys.executable,
1424 "-c", "import time; time.sleep(0.3)"])
1425 with self.assertRaises(subprocess.TimeoutExpired) as c:
1426 p.wait(timeout=0.0001)
1427 self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
1428 self.assertEqual(p.wait(timeout=support.SHORT_TIMEOUT), 0)
1429
1430 def test_invalid_bufsize(self):
1431 # an invalid type of the bufsize argument should raise
1432 # TypeError.
1433 with self.assertRaises(TypeError):
1434 subprocess.Popen(ZERO_RETURN_CMD, "orange")
1435
1436 def test_bufsize_is_none(self):
1437 # bufsize=None should be the same as bufsize=0.
1438 p = subprocess.Popen(ZERO_RETURN_CMD, None)
1439 self.assertEqual(p.wait(), 0)
1440 # Again with keyword arg
1441 p = subprocess.Popen(ZERO_RETURN_CMD, bufsize=None)
1442 self.assertEqual(p.wait(), 0)
1443
1444 def _test_bufsize_equal_one(self, line, expected, universal_newlines):
1445 # subprocess may deadlock with bufsize=1, see issue #21332
1446 with subprocess.Popen([sys.executable, "-c", "import sys;"
1447 "sys.stdout.write(sys.stdin.readline());"
1448 "sys.stdout.flush()"],
1449 stdin=subprocess.PIPE,
1450 stdout=subprocess.PIPE,
1451 stderr=subprocess.DEVNULL,
1452 bufsize=1,
1453 universal_newlines=universal_newlines) as p:
1454 p.stdin.write(line) # expect that it flushes the line in text mode
1455 os.close(p.stdin.fileno()) # close it without flushing the buffer
1456 read_line = p.stdout.readline()
1457 with support.SuppressCrashReport():
1458 try:
1459 p.stdin.close()
1460 except OSError:
1461 pass
1462 p.stdin = None
1463 self.assertEqual(p.returncode, 0)
1464 self.assertEqual(read_line, expected)
1465
1466 def test_bufsize_equal_one_text_mode(self):
1467 # line is flushed in text mode with bufsize=1.
1468 # we should get the full line in return
1469 line = "line\n"
1470 self._test_bufsize_equal_one(line, line, universal_newlines=True)
1471
1472 def test_bufsize_equal_one_binary_mode(self):
1473 # line is not flushed in binary mode with bufsize=1.
1474 # we should get empty response
1475 line = b'line' + os.linesep.encode() # assume ascii-based locale
1476 with self.assertWarnsRegex(RuntimeWarning, 'line buffering'):
1477 self._test_bufsize_equal_one(line, b'', universal_newlines=False)
1478
1479 @support.requires_resource('cpu')
1480 def test_leaking_fds_on_error(self):
1481 # see bug #5179: Popen leaks file descriptors to PIPEs if
1482 # the child fails to execute; this will eventually exhaust
1483 # the maximum number of open fds. 1024 seems a very common
1484 # value for that limit, but Windows has 2048, so we loop
1485 # 1024 times (each call leaked two fds).
1486 for i in range(1024):
1487 with self.assertRaises(NONEXISTING_ERRORS):
1488 subprocess.Popen(NONEXISTING_CMD,
1489 stdout=subprocess.PIPE,
1490 stderr=subprocess.PIPE)
1491
1492 def test_nonexisting_with_pipes(self):
1493 # bpo-30121: Popen with pipes must close properly pipes on error.
1494 # Previously, os.close() was called with a Windows handle which is not
1495 # a valid file descriptor.
1496 #
1497 # Run the test in a subprocess to control how the CRT reports errors
1498 # and to get stderr content.
1499 try:
1500 import msvcrt
1501 msvcrt.CrtSetReportMode
1502 except (AttributeError, ImportError):
1503 self.skipTest("need msvcrt.CrtSetReportMode")
1504
1505 code = textwrap.dedent(f"""
1506 import msvcrt
1507 import subprocess
1508
1509 cmd = {NONEXISTING_CMD!r}
1510
1511 for report_type in [msvcrt.CRT_WARN,
1512 msvcrt.CRT_ERROR,
1513 msvcrt.CRT_ASSERT]:
1514 msvcrt.CrtSetReportMode(report_type, msvcrt.CRTDBG_MODE_FILE)
1515 msvcrt.CrtSetReportFile(report_type, msvcrt.CRTDBG_FILE_STDERR)
1516
1517 try:
1518 subprocess.Popen(cmd,
1519 stdout=subprocess.PIPE,
1520 stderr=subprocess.PIPE)
1521 except OSError:
1522 pass
1523 """)
1524 cmd = [sys.executable, "-c", code]
1525 proc = subprocess.Popen(cmd,
1526 stderr=subprocess.PIPE,
1527 universal_newlines=True)
1528 with proc:
1529 stderr = proc.communicate()[1]
1530 self.assertEqual(stderr, "")
1531 self.assertEqual(proc.returncode, 0)
1532
1533 def test_double_close_on_error(self):
1534 # Issue #18851
1535 fds = []
1536 def open_fds():
1537 for i in range(20):
1538 fds.extend(os.pipe())
1539 time.sleep(0.001)
1540 t = threading.Thread(target=open_fds)
1541 t.start()
1542 try:
1543 with self.assertRaises(OSError):
1544 subprocess.Popen(NONEXISTING_CMD,
1545 stdin=subprocess.PIPE,
1546 stdout=subprocess.PIPE,
1547 stderr=subprocess.PIPE)
1548 finally:
1549 t.join()
1550 exc = None
1551 for fd in fds:
1552 # If a double close occurred, some of those fds will
1553 # already have been closed by mistake, and os.close()
1554 # here will raise.
1555 try:
1556 os.close(fd)
1557 except OSError as e:
1558 exc = e
1559 if exc is not None:
1560 raise exc
1561
1562 def test_threadsafe_wait(self):
1563 """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
1564 proc = subprocess.Popen([sys.executable, '-c',
1565 'import time; time.sleep(12)'])
1566 self.assertEqual(proc.returncode, None)
1567 results = []
1568
1569 def kill_proc_timer_thread():
1570 results.append(('thread-start-poll-result', proc.poll()))
1571 # terminate it from the thread and wait for the result.
1572 proc.kill()
1573 proc.wait()
1574 results.append(('thread-after-kill-and-wait', proc.returncode))
1575 # this wait should be a no-op given the above.
1576 proc.wait()
1577 results.append(('thread-after-second-wait', proc.returncode))
1578
1579 # This is a timing sensitive test, the failure mode is
1580 # triggered when both the main thread and this thread are in
1581 # the wait() call at once. The delay here is to allow the
1582 # main thread to most likely be blocked in its wait() call.
1583 t = threading.Timer(0.2, kill_proc_timer_thread)
1584 t.start()
1585
1586 if mswindows:
1587 expected_errorcode = 1
1588 else:
1589 # Should be -9 because of the proc.kill() from the thread.
1590 expected_errorcode = -9
1591
1592 # Wait for the process to finish; the thread should kill it
1593 # long before it finishes on its own. Supplying a timeout
1594 # triggers a different code path for better coverage.
1595 proc.wait(timeout=support.SHORT_TIMEOUT)
1596 self.assertEqual(proc.returncode, expected_errorcode,
1597 msg="unexpected result in wait from main thread")
1598
1599 # This should be a no-op with no change in returncode.
1600 proc.wait()
1601 self.assertEqual(proc.returncode, expected_errorcode,
1602 msg="unexpected result in second main wait.")
1603
1604 t.join()
1605 # Ensure that all of the thread results are as expected.
1606 # When a race condition occurs in wait(), the returncode could
1607 # be set by the wrong thread that doesn't actually have it
1608 # leading to an incorrect value.
1609 self.assertEqual([('thread-start-poll-result', None),
1610 ('thread-after-kill-and-wait', expected_errorcode),
1611 ('thread-after-second-wait', expected_errorcode)],
1612 results)
1613
1614 def test_issue8780(self):
1615 # Ensure that stdout is inherited from the parent
1616 # if stdout=PIPE is not used
1617 code = ';'.join((
1618 'import subprocess, sys',
1619 'retcode = subprocess.call('
1620 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
1621 'assert retcode == 0'))
1622 output = subprocess.check_output([sys.executable, '-c', code])
1623 self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
1624
1625 def test_handles_closed_on_exception(self):
1626 # If CreateProcess exits with an error, ensure the
1627 # duplicate output handles are released
1628 ifhandle, ifname = tempfile.mkstemp()
1629 ofhandle, ofname = tempfile.mkstemp()
1630 efhandle, efname = tempfile.mkstemp()
1631 try:
1632 subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
1633 stderr=efhandle)
1634 except OSError:
1635 os.close(ifhandle)
1636 os.remove(ifname)
1637 os.close(ofhandle)
1638 os.remove(ofname)
1639 os.close(efhandle)
1640 os.remove(efname)
1641 self.assertFalse(os.path.exists(ifname))
1642 self.assertFalse(os.path.exists(ofname))
1643 self.assertFalse(os.path.exists(efname))
1644
1645 def test_communicate_epipe(self):
1646 # Issue 10963: communicate() should hide EPIPE
1647 p = subprocess.Popen(ZERO_RETURN_CMD,
1648 stdin=subprocess.PIPE,
1649 stdout=subprocess.PIPE,
1650 stderr=subprocess.PIPE)
1651 self.addCleanup(p.stdout.close)
1652 self.addCleanup(p.stderr.close)
1653 self.addCleanup(p.stdin.close)
1654 p.communicate(b"x" * 2**20)
1655
1656 def test_repr(self):
1657 cases = [
1658 ("ls", True, 123, "<Popen: returncode: 123 args: 'ls'>"),
1659 ('a' * 100, True, 0,
1660 "<Popen: returncode: 0 args: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...>"),
1661 (["ls"], False, None, "<Popen: returncode: None args: ['ls']>"),
1662 (["ls", '--my-opts', 'a' * 100], False, None,
1663 "<Popen: returncode: None args: ['ls', '--my-opts', 'aaaaaaaaaaaaaaaaaaaaaaaa...>"),
1664 (os_helper.FakePath("my-tool.py"), False, 7,
1665 "<Popen: returncode: 7 args: <FakePath 'my-tool.py'>>")
1666 ]
1667 with unittest.mock.patch.object(subprocess.Popen, '_execute_child'):
1668 for cmd, shell, code, sx in cases:
1669 p = subprocess.Popen(cmd, shell=shell)
1670 p.returncode = code
1671 self.assertEqual(repr(p), sx)
1672
1673 def test_communicate_epipe_only_stdin(self):
1674 # Issue 10963: communicate() should hide EPIPE
1675 p = subprocess.Popen(ZERO_RETURN_CMD,
1676 stdin=subprocess.PIPE)
1677 self.addCleanup(p.stdin.close)
1678 p.wait()
1679 p.communicate(b"x" * 2**20)
1680
1681 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
1682 "Requires signal.SIGUSR1")
1683 @unittest.skipUnless(hasattr(os, 'kill'),
1684 "Requires os.kill")
1685 @unittest.skipUnless(hasattr(os, 'getppid'),
1686 "Requires os.getppid")
1687 def test_communicate_eintr(self):
1688 # Issue #12493: communicate() should handle EINTR
1689 def handler(signum, frame):
1690 pass
1691 old_handler = signal.signal(signal.SIGUSR1, handler)
1692 self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
1693
1694 args = [sys.executable, "-c",
1695 'import os, signal;'
1696 'os.kill(os.getppid(), signal.SIGUSR1)']
1697 for stream in ('stdout', 'stderr'):
1698 kw = {stream: subprocess.PIPE}
1699 with subprocess.Popen(args, **kw) as process:
1700 # communicate() will be interrupted by SIGUSR1
1701 process.communicate()
1702
1703
1704 # This test is Linux-ish specific for simplicity to at least have
1705 # some coverage. It is not a platform specific bug.
1706 @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
1707 "Linux specific")
1708 def test_failed_child_execute_fd_leak(self):
1709 """Test for the fork() failure fd leak reported in issue16327."""
1710 fd_directory = '/proc/%d/fd' % os.getpid()
1711 fds_before_popen = os.listdir(fd_directory)
1712 with self.assertRaises(PopenTestException):
1713 PopenExecuteChildRaises(
1714 ZERO_RETURN_CMD, stdin=subprocess.PIPE,
1715 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1716
1717 # NOTE: This test doesn't verify that the real _execute_child
1718 # does not close the file descriptors itself on the way out
1719 # during an exception. Code inspection has confirmed that.
1720
1721 fds_after_exception = os.listdir(fd_directory)
1722 self.assertEqual(fds_before_popen, fds_after_exception)
1723
1724 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
1725 def test_file_not_found_includes_filename(self):
1726 with self.assertRaises(FileNotFoundError) as c:
1727 subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args'])
1728 self.assertEqual(c.exception.filename, '/opt/nonexistent_binary')
1729
1730 @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
1731 def test_file_not_found_with_bad_cwd(self):
1732 with self.assertRaises(FileNotFoundError) as c:
1733 subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory')
1734 self.assertEqual(c.exception.filename, '/some/nonexistent/directory')
1735
1736 def test_class_getitems(self):
1737 self.assertIsInstance(subprocess.Popen[bytes], types.GenericAlias)
1738 self.assertIsInstance(subprocess.CompletedProcess[str], types.GenericAlias)
1739
1740 @unittest.skipUnless(hasattr(subprocess, '_winapi'),
1741 'need subprocess._winapi')
1742 def test_wait_negative_timeout(self):
1743 proc = subprocess.Popen(ZERO_RETURN_CMD)
1744 with proc:
1745 patch = mock.patch.object(
1746 subprocess._winapi,
1747 'WaitForSingleObject',
1748 return_value=subprocess._winapi.WAIT_OBJECT_0)
1749 with patch as mock_wait:
1750 proc.wait(-1) # negative timeout
1751 mock_wait.assert_called_once_with(proc._handle, 0)
1752 proc.returncode = None
1753
1754 self.assertEqual(proc.wait(), 0)
1755
1756 def test_post_timeout_communicate_sends_input(self):
1757 """GH-141473 regression test; the stdin pipe must close"""
1758 with subprocess.Popen(
1759 [sys.executable, "-uc", """\
1760 import sys
1761 while c := sys.stdin.read(512):
1762 sys.stdout.write(c)
1763 print()
1764 """],
1765 stdin=subprocess.PIPE,
1766 stdout=subprocess.PIPE,
1767 stderr=subprocess.PIPE,
1768 text=True,
1769 ) as proc:
1770 try:
1771 data = f"spam{'#'*4096}beans"
1772 proc.communicate(
1773 input=data,
1774 timeout=0,
1775 )
1776 except subprocess.TimeoutExpired as exc:
1777 pass
1778 # Prior to the bugfix, this would hang as the stdin
1779 # pipe to the child had not been closed.
1780 try:
1781 stdout, stderr = proc.communicate(timeout=15)
1782 except subprocess.TimeoutExpired as exc:
1783 self.fail("communicate() hung waiting on child process that should have seen its stdin pipe close and exit")
1784 self.assertEqual(
1785 proc.returncode, 0,
1786 msg=f"STDERR:\n{stderr}\nSTDOUT:\n{stdout}")
1787 self.assertTrue(stdout.startswith("spam"), msg=stdout)
1788 self.assertIn("beans", stdout)
1789
1790
1791 class RunFuncTestCase(BaseTestCase):
1792 def run_python(self, code, **kwargs):
1793 """Run Python code in a subprocess using subprocess.run"""
1794 argv = [sys.executable, "-c", code]
1795 return subprocess.run(argv, **kwargs)
1796
1797 def test_returncode(self):
1798 # call() function with sequence argument
1799 cp = self.run_python("import sys; sys.exit(47)")
1800 self.assertEqual(cp.returncode, 47)
1801 with self.assertRaises(subprocess.CalledProcessError):
1802 cp.check_returncode()
1803
1804 def test_check(self):
1805 with self.assertRaises(subprocess.CalledProcessError) as c:
1806 self.run_python("import sys; sys.exit(47)", check=True)
1807 self.assertEqual(c.exception.returncode, 47)
1808
1809 def test_check_zero(self):
1810 # check_returncode shouldn't raise when returncode is zero
1811 cp = subprocess.run(ZERO_RETURN_CMD, check=True)
1812 self.assertEqual(cp.returncode, 0)
1813
1814 def test_timeout(self):
1815 # run() function with timeout argument; we want to test that the child
1816 # process gets killed when the timeout expires. If the child isn't
1817 # killed, this call will deadlock since subprocess.run waits for the
1818 # child.
1819 with self.assertRaises(subprocess.TimeoutExpired):
1820 self.run_python("while True: pass", timeout=0.0001)
1821
1822 def test_capture_stdout(self):
1823 # capture stdout with zero return code
1824 cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
1825 self.assertIn(b'BDFL', cp.stdout)
1826
1827 def test_capture_stderr(self):
1828 cp = self.run_python("import sys; sys.stderr.write('BDFL')",
1829 stderr=subprocess.PIPE)
1830 self.assertIn(b'BDFL', cp.stderr)
1831
1832 def test_check_output_stdin_arg(self):
1833 # run() can be called with stdin set to a file
1834 tf = tempfile.TemporaryFile()
1835 self.addCleanup(tf.close)
1836 tf.write(b'pear')
1837 tf.seek(0)
1838 cp = self.run_python(
1839 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1840 stdin=tf, stdout=subprocess.PIPE)
1841 self.assertIn(b'PEAR', cp.stdout)
1842
1843 def test_check_output_input_arg(self):
1844 # check_output() can be called with input set to a string
1845 cp = self.run_python(
1846 "import sys; sys.stdout.write(sys.stdin.read().upper())",
1847 input=b'pear', stdout=subprocess.PIPE)
1848 self.assertIn(b'PEAR', cp.stdout)
1849
1850 def test_check_output_stdin_with_input_arg(self):
1851 # run() refuses to accept 'stdin' with 'input'
1852 tf = tempfile.TemporaryFile()
1853 self.addCleanup(tf.close)
1854 tf.write(b'pear')
1855 tf.seek(0)
1856 with self.assertRaises(ValueError,
1857 msg="Expected ValueError when stdin and input args supplied.") as c:
1858 output = self.run_python("print('will not be run')",
1859 stdin=tf, input=b'hare')
1860 self.assertIn('stdin', c.exception.args[0])
1861 self.assertIn('input', c.exception.args[0])
1862
1863 def test_check_output_timeout(self):
1864 with self.assertRaises(subprocess.TimeoutExpired) as c:
1865 cp = self.run_python(
1866 "import time; time.sleep(3600)",
1867 timeout=0.1, stdout=subprocess.PIPE)
1868
1869 def test_run_kwargs(self):
1870 newenv = os.environ.copy()
1871 newenv["FRUIT"] = "banana"
1872 cp = self.run_python(('import sys, os;'
1873 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
1874 env=newenv)
1875 self.assertEqual(cp.returncode, 33)
1876
1877 def test_run_with_pathlike_path(self):
1878 # bpo-31961: test run(pathlike_object)
1879 # the name of a command that can be run without
1880 # any arguments that exit fast
1881 prog = 'tree.com' if mswindows else 'ls'
1882 path = shutil.which(prog)
1883 if path is None:
1884 self.skipTest(f'{prog} required for this test')
1885 path = FakePath(path)
1886 res = subprocess.run(path, stdout=subprocess.DEVNULL)
1887 self.assertEqual(res.returncode, 0)
1888 with self.assertRaises(TypeError):
1889 subprocess.run(path, stdout=subprocess.DEVNULL, shell=True)
1890
1891 def test_run_with_bytes_path_and_arguments(self):
1892 # bpo-31961: test run([bytes_object, b'additional arguments'])
1893 path = os.fsencode(sys.executable)
1894 args = [path, '-c', b'import sys; sys.exit(57)']
1895 res = subprocess.run(args)
1896 self.assertEqual(res.returncode, 57)
1897
1898 def test_run_with_pathlike_path_and_arguments(self):
1899 # bpo-31961: test run([pathlike_object, 'additional arguments'])
1900 path = FakePath(sys.executable)
1901 args = [path, '-c', 'import sys; sys.exit(57)']
1902 res = subprocess.run(args)
1903 self.assertEqual(res.returncode, 57)
1904
1905 @unittest.skipUnless(mswindows, "Maybe test trigger a leak on Ubuntu")
1906 def test_run_with_an_empty_env(self):
1907 # gh-105436: fix subprocess.run(..., env={}) broken on Windows
1908 args = [sys.executable, "-c", 'pass']
1909 # Ignore subprocess errors - we only care that the API doesn't
1910 # raise an OSError
1911 subprocess.run(args, env={})
1912
1913 def test_capture_output(self):
1914 cp = self.run_python(("import sys;"
1915 "sys.stdout.write('BDFL'); "
1916 "sys.stderr.write('FLUFL')"),
1917 capture_output=True)
1918 self.assertIn(b'BDFL', cp.stdout)
1919 self.assertIn(b'FLUFL', cp.stderr)
1920
1921 def test_stdout_stdout(self):
1922 # run() refuses to accept stdout=STDOUT
1923 with self.assertRaises(ValueError,
1924 msg=("STDOUT can only be used for stderr")):
1925 self.run_python("print('will not be run')",
1926 stdout=subprocess.STDOUT)
1927
1928 def test_stdout_with_capture_output_arg(self):
1929 # run() refuses to accept 'stdout' with 'capture_output'
1930 tf = tempfile.TemporaryFile()
1931 self.addCleanup(tf.close)
1932 with self.assertRaises(ValueError,
1933 msg=("Expected ValueError when stdout and capture_output "
1934 "args supplied.")) as c:
1935 output = self.run_python("print('will not be run')",
1936 capture_output=True, stdout=tf)
1937 self.assertIn('stdout', c.exception.args[0])
1938 self.assertIn('capture_output', c.exception.args[0])
1939
1940 def test_stderr_with_capture_output_arg(self):
1941 # run() refuses to accept 'stderr' with 'capture_output'
1942 tf = tempfile.TemporaryFile()
1943 self.addCleanup(tf.close)
1944 with self.assertRaises(ValueError,
1945 msg=("Expected ValueError when stderr and capture_output "
1946 "args supplied.")) as c:
1947 output = self.run_python("print('will not be run')",
1948 capture_output=True, stderr=tf)
1949 self.assertIn('stderr', c.exception.args[0])
1950 self.assertIn('capture_output', c.exception.args[0])
1951
1952 # This test _might_ wind up a bit fragile on loaded build+test machines
1953 # as it depends on the timing with wide enough margins for normal situations
1954 # but does assert that it happened "soon enough" to believe the right thing
1955 # happened.
1956 @unittest.skipIf(mswindows, "requires posix like 'sleep' shell command")
1957 def test_run_with_shell_timeout_and_capture_output(self):
1958 """Output capturing after a timeout mustn't hang forever on open filehandles."""
1959 before_secs = time.monotonic()
1960 try:
1961 subprocess.run('sleep 3', shell=True, timeout=0.1,
1962 capture_output=True) # New session unspecified.
1963 except subprocess.TimeoutExpired as exc:
1964 after_secs = time.monotonic()
1965 stacks = traceback.format_exc() # assertRaises doesn't give this.
1966 else:
1967 self.fail("TimeoutExpired not raised.")
1968 self.assertLess(after_secs - before_secs, 1.5,
1969 msg="TimeoutExpired was delayed! Bad traceback:\n```\n"
1970 f"{stacks}```")
1971
1972 def test_encoding_warning(self):
1973 code = textwrap.dedent("""\
1974 from subprocess import *
1975 run("echo hello", shell=True, text=True)
1976 check_output("echo hello", shell=True, text=True)
1977 """)
1978 cp = subprocess.run([sys.executable, "-Xwarn_default_encoding", "-c", code],
1979 capture_output=True)
1980 lines = cp.stderr.splitlines()
1981 self.assertEqual(len(lines), 2, lines)
1982 self.assertTrue(lines[0].startswith(b"<string>:2: EncodingWarning: "))
1983 self.assertTrue(lines[1].startswith(b"<string>:3: EncodingWarning: "))
1984
1985
1986 def _get_test_grp_name():
1987 for name_group in ('staff', 'nogroup', 'grp', 'nobody', 'nfsnobody'):
1988 if grp:
1989 try:
1990 grp.getgrnam(name_group)
1991 except KeyError:
1992 continue
1993 return name_group
1994 else:
1995 raise unittest.SkipTest('No identified group name to use for this test on this platform.')
1996
1997
1998 @unittest.skipIf(mswindows, "POSIX specific tests")
1999 class POSIXProcessTestCase(BaseTestCase):
2000
2001 def setUp(self):
2002 super().setUp()
2003 self._nonexistent_dir = "/_this/pa.th/does/not/exist"
2004
2005 def _get_chdir_exception(self):
2006 try:
2007 os.chdir(self._nonexistent_dir)
2008 except OSError as e:
2009 # This avoids hard coding the errno value or the OS perror()
2010 # string and instead capture the exception that we want to see
2011 # below for comparison.
2012 desired_exception = e
2013 else:
2014 self.fail("chdir to nonexistent directory %s succeeded." %
2015 self._nonexistent_dir)
2016 return desired_exception
2017
2018 def test_exception_cwd(self):
2019 """Test error in the child raised in the parent for a bad cwd."""
2020 desired_exception = self._get_chdir_exception()
2021 try:
2022 p = subprocess.Popen([sys.executable, "-c", ""],
2023 cwd=self._nonexistent_dir)
2024 except OSError as e:
2025 # Test that the child process chdir failure actually makes
2026 # it up to the parent process as the correct exception.
2027 self.assertEqual(desired_exception.errno, e.errno)
2028 self.assertEqual(desired_exception.strerror, e.strerror)
2029 self.assertEqual(desired_exception.filename, e.filename)
2030 else:
2031 self.fail("Expected OSError: %s" % desired_exception)
2032
2033 def test_exception_bad_executable(self):
2034 """Test error in the child raised in the parent for a bad executable."""
2035 desired_exception = self._get_chdir_exception()
2036 try:
2037 p = subprocess.Popen([sys.executable, "-c", ""],
2038 executable=self._nonexistent_dir)
2039 except OSError as e:
2040 # Test that the child process exec failure actually makes
2041 # it up to the parent process as the correct exception.
2042 self.assertEqual(desired_exception.errno, e.errno)
2043 self.assertEqual(desired_exception.strerror, e.strerror)
2044 self.assertEqual(desired_exception.filename, e.filename)
2045 else:
2046 self.fail("Expected OSError: %s" % desired_exception)
2047
2048 def test_exception_bad_args_0(self):
2049 """Test error in the child raised in the parent for a bad args[0]."""
2050 desired_exception = self._get_chdir_exception()
2051 try:
2052 p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
2053 except OSError as e:
2054 # Test that the child process exec failure actually makes
2055 # it up to the parent process as the correct exception.
2056 self.assertEqual(desired_exception.errno, e.errno)
2057 self.assertEqual(desired_exception.strerror, e.strerror)
2058 self.assertEqual(desired_exception.filename, e.filename)
2059 else:
2060 self.fail("Expected OSError: %s" % desired_exception)
2061
2062 # We mock the __del__ method for Popen in the next two tests
2063 # because it does cleanup based on the pid returned by fork_exec
2064 # along with issuing a resource warning if it still exists. Since
2065 # we don't actually spawn a process in these tests we can forego
2066 # the destructor. An alternative would be to set _child_created to
2067 # False before the destructor is called but there is no easy way
2068 # to do that
2069 class PopenNoDestructor(subprocess.Popen):
2070 def __del__(self):
2071 pass
2072
2073 @mock.patch("subprocess._fork_exec")
2074 def test_exception_errpipe_normal(self, fork_exec):
2075 """Test error passing done through errpipe_write in the good case"""
2076 def proper_error(*args):
2077 errpipe_write = args[13]
2078 # Write the hex for the error code EISDIR: 'is a directory'
2079 err_code = '{:x}'.format(errno.EISDIR).encode()
2080 os.write(errpipe_write, b"OSError:" + err_code + b":")
2081 return 0
2082
2083 fork_exec.side_effect = proper_error
2084
2085 with mock.patch("subprocess.os.waitpid",
2086 side_effect=ChildProcessError):
2087 with self.assertRaises(IsADirectoryError):
2088 self.PopenNoDestructor(["non_existent_command"])
2089
2090 @mock.patch("subprocess._fork_exec")
2091 def test_exception_errpipe_bad_data(self, fork_exec):
2092 """Test error passing done through errpipe_write where its not
2093 in the expected format"""
2094 error_data = b"\xFF\x00\xDE\xAD"
2095 def bad_error(*args):
2096 errpipe_write = args[13]
2097 # Anything can be in the pipe, no assumptions should
2098 # be made about its encoding, so we'll write some
2099 # arbitrary hex bytes to test it out
2100 os.write(errpipe_write, error_data)
2101 return 0
2102
2103 fork_exec.side_effect = bad_error
2104
2105 with mock.patch("subprocess.os.waitpid",
2106 side_effect=ChildProcessError):
2107 with self.assertRaises(subprocess.SubprocessError) as e:
2108 self.PopenNoDestructor(["non_existent_command"])
2109
2110 self.assertIn(repr(error_data), str(e.exception))
2111
2112 @unittest.skipIf(not os.path.exists('/proc/self/status'),
2113 "need /proc/self/status")
2114 def test_restore_signals(self):
2115 # Blindly assume that cat exists on systems with /proc/self/status...
2116 default_proc_status = subprocess.check_output(
2117 ['cat', '/proc/self/status'],
2118 restore_signals=False)
2119 for line in default_proc_status.splitlines():
2120 if line.startswith(b'SigIgn'):
2121 default_sig_ign_mask = line
2122 break
2123 else:
2124 self.skipTest("SigIgn not found in /proc/self/status.")
2125 restored_proc_status = subprocess.check_output(
2126 ['cat', '/proc/self/status'],
2127 restore_signals=True)
2128 for line in restored_proc_status.splitlines():
2129 if line.startswith(b'SigIgn'):
2130 restored_sig_ign_mask = line
2131 break
2132 self.assertNotEqual(default_sig_ign_mask, restored_sig_ign_mask,
2133 msg="restore_signals=True should've unblocked "
2134 "SIGPIPE and friends.")
2135
2136 def test_start_new_session(self):
2137 # For code coverage of calling setsid(). We don't care if we get an
2138 # EPERM error from it depending on the test execution environment, that
2139 # still indicates that it was called.
2140 try:
2141 output = subprocess.check_output(
2142 [sys.executable, "-c", "import os; print(os.getsid(0))"],
2143 start_new_session=True)
2144 except PermissionError as e:
2145 if e.errno != errno.EPERM:
2146 raise # EACCES?
2147 else:
2148 parent_sid = os.getsid(0)
2149 child_sid = int(output)
2150 self.assertNotEqual(parent_sid, child_sid)
2151
2152 @unittest.skipUnless(hasattr(os, 'setpgid') and hasattr(os, 'getpgid'),
2153 'no setpgid or getpgid on platform')
2154 def test_process_group_0(self):
2155 # For code coverage of calling setpgid(). We don't care if we get an
2156 # EPERM error from it depending on the test execution environment, that
2157 # still indicates that it was called.
2158 try:
2159 output = subprocess.check_output(
2160 [sys.executable, "-c", "import os; print(os.getpgid(0))"],
2161 process_group=0)
2162 except PermissionError as e:
2163 if e.errno != errno.EPERM:
2164 raise # EACCES?
2165 else:
2166 parent_pgid = os.getpgid(0)
2167 child_pgid = int(output)
2168 self.assertNotEqual(parent_pgid, child_pgid)
2169
2170 @unittest.skipUnless(hasattr(os, 'setreuid'), 'no setreuid on platform')
2171 def test_user(self):
2172 # For code coverage of the user parameter. We don't care if we get a
2173 # permission error from it depending on the test execution environment,
2174 # that still indicates that it was called.
2175
2176 uid = os.geteuid()
2177 test_users = [65534 if uid != 65534 else 65533, uid]
2178 name_uid = "nobody" if sys.platform != 'darwin' else "unknown"
2179
2180 if pwd is not None:
2181 try:
2182 pwd.getpwnam(name_uid)
2183 test_users.append(name_uid)
2184 except KeyError:
2185 # unknown user name
2186 name_uid = None
2187
2188 for user in test_users:
2189 # posix_spawn() may be used with close_fds=False
2190 for close_fds in (False, True):
2191 with self.subTest(user=user, close_fds=close_fds):
2192 try:
2193 output = subprocess.check_output(
2194 [sys.executable, "-c",
2195 "import os; print(os.getuid())"],
2196 user=user,
2197 close_fds=close_fds)
2198 except PermissionError as e: # (EACCES, EPERM)
2199 if e.errno == errno.EACCES:
2200 self.assertEqual(e.filename, sys.executable)
2201 else:
2202 self.assertIsNone(e.filename)
2203 else:
2204 if isinstance(user, str):
2205 user_uid = pwd.getpwnam(user).pw_uid
2206 else:
2207 user_uid = user
2208 child_user = int(output)
2209 self.assertEqual(child_user, user_uid)
2210
2211 with self.assertRaises(ValueError):
2212 subprocess.check_call(ZERO_RETURN_CMD, user=-1)
2213
2214 with self.assertRaises(OverflowError):
2215 subprocess.check_call(ZERO_RETURN_CMD,
2216 cwd=os.curdir, env=os.environ, user=2**64)
2217
2218 if pwd is None and name_uid is not None:
2219 with self.assertRaises(ValueError):
2220 subprocess.check_call(ZERO_RETURN_CMD, user=name_uid)
2221
2222 @unittest.skipIf(hasattr(os, 'setreuid'), 'setreuid() available on platform')
2223 def test_user_error(self):
2224 with self.assertRaises(ValueError):
2225 subprocess.check_call(ZERO_RETURN_CMD, user=65535)
2226
2227 @unittest.skipUnless(hasattr(os, 'setregid'), 'no setregid() on platform')
2228 def test_group(self):
2229 gid = os.getegid()
2230 group_list = [65534 if gid != 65534 else 65533]
2231 name_group = _get_test_grp_name()
2232
2233 if grp is not None:
2234 group_list.append(name_group)
2235
2236 for group in group_list + [gid]:
2237 # posix_spawn() may be used with close_fds=False
2238 for close_fds in (False, True):
2239 with self.subTest(group=group, close_fds=close_fds):
2240 try:
2241 output = subprocess.check_output(
2242 [sys.executable, "-c",
2243 "import os; print(os.getgid())"],
2244 group=group,
2245 close_fds=close_fds)
2246 except PermissionError as e: # (EACCES, EPERM)
2247 self.assertIsNone(e.filename)
2248 else:
2249 if isinstance(group, str):
2250 group_gid = grp.getgrnam(group).gr_gid
2251 else:
2252 group_gid = group
2253
2254 child_group = int(output)
2255 self.assertEqual(child_group, group_gid)
2256
2257 # make sure we bomb on negative values
2258 with self.assertRaises(ValueError):
2259 subprocess.check_call(ZERO_RETURN_CMD, group=-1)
2260
2261 with self.assertRaises(OverflowError):
2262 subprocess.check_call(ZERO_RETURN_CMD,
2263 cwd=os.curdir, env=os.environ, group=2**64)
2264
2265 if grp is None:
2266 with self.assertRaises(ValueError):
2267 subprocess.check_call(ZERO_RETURN_CMD, group=name_group)
2268
2269 @unittest.skipIf(hasattr(os, 'setregid'), 'setregid() available on platform')
2270 def test_group_error(self):
2271 with self.assertRaises(ValueError):
2272 subprocess.check_call(ZERO_RETURN_CMD, group=65535)
2273
2274 @unittest.skipUnless(hasattr(os, 'setgroups'), 'no setgroups() on platform')
2275 def test_extra_groups(self):
2276 gid = os.getegid()
2277 group_list = [65534 if gid != 65534 else 65533]
2278 self._test_extra_groups_impl(gid=gid, group_list=group_list)
2279
2280 @unittest.skipUnless(hasattr(os, 'setgroups'), 'no setgroups() on platform')
2281 def test_extra_groups_empty_list(self):
2282 self._test_extra_groups_impl(gid=os.getegid(), group_list=[])
2283
2284 def _test_extra_groups_impl(self, *, gid, group_list):
2285 name_group = _get_test_grp_name()
2286
2287 if grp is not None:
2288 group_list.append(name_group)
2289
2290 try:
2291 output = subprocess.check_output(
2292 [sys.executable, "-c",
2293 "import os, sys, json; json.dump(os.getgroups(), sys.stdout)"],
2294 extra_groups=group_list)
2295 except PermissionError as e:
2296 self.assertIsNone(e.filename)
2297 self.skipTest("setgroup() EPERM; this test may require root.")
2298 else:
2299 parent_groups = os.getgroups()
2300 child_groups = json.loads(output)
2301
2302 if grp is not None:
2303 desired_gids = [grp.getgrnam(g).gr_gid if isinstance(g, str) else g
2304 for g in group_list]
2305 else:
2306 desired_gids = group_list
2307
2308 self.assertEqual(set(desired_gids), set(child_groups))
2309
2310 if grp is None:
2311 with self.assertRaises(ValueError):
2312 subprocess.check_call(ZERO_RETURN_CMD,
2313 extra_groups=[name_group])
2314
2315 # No skip necessary, this test won't make it to a setgroup() call.
2316 def test_extra_groups_invalid_gid_t_values(self):
2317 with self.assertRaises(ValueError):
2318 subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[-1])
2319
2320 with self.assertRaises(ValueError):
2321 subprocess.check_call(ZERO_RETURN_CMD,
2322 cwd=os.curdir, env=os.environ,
2323 extra_groups=[2**64])
2324
2325 @unittest.skipIf(mswindows or not hasattr(os, 'umask'),
2326 'POSIX umask() is not available.')
2327 def test_umask(self):
2328 tmpdir = None
2329 try:
2330 tmpdir = tempfile.mkdtemp()
2331 name = os.path.join(tmpdir, "beans")
2332 # We set an unusual umask in the child so as a unique mode
2333 # for us to test the child's touched file for.
2334 subprocess.check_call(
2335 [sys.executable, "-c", f"open({name!r}, 'w').close()"],
2336 umask=0o053)
2337 # Ignore execute permissions entirely in our test,
2338 # filesystems could be mounted to ignore or force that.
2339 st_mode = os.stat(name).st_mode & 0o666
2340 expected_mode = 0o624
2341 self.assertEqual(expected_mode, st_mode,
2342 msg=f'{oct(expected_mode)} != {oct(st_mode)}')
2343 finally:
2344 if tmpdir is not None:
2345 shutil.rmtree(tmpdir)
2346
2347 def test_run_abort(self):
2348 # returncode handles signal termination
2349 with support.SuppressCrashReport():
2350 p = subprocess.Popen([sys.executable, "-c",
2351 'import os; os.abort()'])
2352 p.wait()
2353 self.assertEqual(-p.returncode, signal.SIGABRT)
2354
2355 def test_CalledProcessError_str_signal(self):
2356 err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
2357 error_string = str(err)
2358 # We're relying on the repr() of the signal.Signals intenum to provide
2359 # the word signal, the signal name and the numeric value.
2360 self.assertIn("signal", error_string.lower())
2361 # We're not being specific about the signal name as some signals have
2362 # multiple names and which name is revealed can vary.
2363 self.assertIn("SIG", error_string)
2364 self.assertIn(str(signal.SIGABRT), error_string)
2365
2366 def test_CalledProcessError_str_unknown_signal(self):
2367 err = subprocess.CalledProcessError(-9876543, "fake cmd")
2368 error_string = str(err)
2369 self.assertIn("unknown signal 9876543.", error_string)
2370
2371 def test_CalledProcessError_str_non_zero(self):
2372 err = subprocess.CalledProcessError(2, "fake cmd")
2373 error_string = str(err)
2374 self.assertIn("non-zero exit status 2.", error_string)
2375
2376 def test_preexec(self):
2377 # DISCLAIMER: Setting environment variables is *not* a good use
2378 # of a preexec_fn. This is merely a test.
2379 p = subprocess.Popen([sys.executable, "-c",
2380 'import sys,os;'
2381 'sys.stdout.write(os.getenv("FRUIT"))'],
2382 stdout=subprocess.PIPE,
2383 preexec_fn=lambda: os.putenv("FRUIT", "apple"))
2384 with p:
2385 self.assertEqual(p.stdout.read(), b"apple")
2386
2387 def test_preexec_exception(self):
2388 def raise_it():
2389 raise ValueError("What if two swallows carried a coconut?")
2390 try:
2391 p = subprocess.Popen([sys.executable, "-c", ""],
2392 preexec_fn=raise_it)
2393 except subprocess.SubprocessError as e:
2394 self.assertTrue(
2395 subprocess._fork_exec,
2396 "Expected a ValueError from the preexec_fn")
2397 except ValueError as e:
2398 self.assertIn("coconut", e.args[0])
2399 else:
2400 self.fail("Exception raised by preexec_fn did not make it "
2401 "to the parent process.")
2402
2403 class _TestExecuteChildPopen(subprocess.Popen):
2404 """Used to test behavior at the end of _execute_child."""
2405 def __init__(self, testcase, *args, **kwargs):
2406 self._testcase = testcase
2407 subprocess.Popen.__init__(self, *args, **kwargs)
2408
2409 def _execute_child(self, *args, **kwargs):
2410 try:
2411 subprocess.Popen._execute_child(self, *args, **kwargs)
2412 finally:
2413 # Open a bunch of file descriptors and verify that
2414 # none of them are the same as the ones the Popen
2415 # instance is using for stdin/stdout/stderr.
2416 devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
2417 for _ in range(8)]
2418 try:
2419 for fd in devzero_fds:
2420 self._testcase.assertNotIn(
2421 fd, (self.stdin.fileno(), self.stdout.fileno(),
2422 self.stderr.fileno()),
2423 msg="At least one fd was closed early.")
2424 finally:
2425 for fd in devzero_fds:
2426 os.close(fd)
2427
2428 @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
2429 def test_preexec_errpipe_does_not_double_close_pipes(self):
2430 """Issue16140: Don't double close pipes on preexec error."""
2431
2432 def raise_it():
2433 raise subprocess.SubprocessError(
2434 "force the _execute_child() errpipe_data path.")
2435
2436 with self.assertRaises(subprocess.SubprocessError):
2437 self._TestExecuteChildPopen(
2438 self, ZERO_RETURN_CMD,
2439 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2440 stderr=subprocess.PIPE, preexec_fn=raise_it)
2441
2442 def test_preexec_gc_module_failure(self):
2443 # This tests the code that disables garbage collection if the child
2444 # process will execute any Python.
2445 enabled = gc.isenabled()
2446 try:
2447 gc.disable()
2448 self.assertFalse(gc.isenabled())
2449 subprocess.call([sys.executable, '-c', ''],
2450 preexec_fn=lambda: None)
2451 self.assertFalse(gc.isenabled(),
2452 "Popen enabled gc when it shouldn't.")
2453
2454 gc.enable()
2455 self.assertTrue(gc.isenabled())
2456 subprocess.call([sys.executable, '-c', ''],
2457 preexec_fn=lambda: None)
2458 self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
2459 finally:
2460 if not enabled:
2461 gc.disable()
2462
2463 @unittest.skipIf(
2464 sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
2465 def test_preexec_fork_failure(self):
2466 # The internal code did not preserve the previous exception when
2467 # re-enabling garbage collection
2468 try:
2469 from resource import getrlimit, setrlimit, RLIMIT_NPROC
2470 except ImportError as err:
2471 self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
2472 limits = getrlimit(RLIMIT_NPROC)
2473 [_, hard] = limits
2474 setrlimit(RLIMIT_NPROC, (0, hard))
2475 self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
2476 try:
2477 subprocess.call([sys.executable, '-c', ''],
2478 preexec_fn=lambda: None)
2479 except BlockingIOError:
2480 # Forking should raise EAGAIN, translated to BlockingIOError
2481 pass
2482 else:
2483 self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
2484
2485 def test_args_string(self):
2486 # args is a string
2487 fd, fname = tempfile.mkstemp()
2488 # reopen in text mode
2489 with open(fd, "w", errors="surrogateescape") as fobj:
2490 fobj.write("#!%s\n" % support.unix_shell)
2491 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2492 sys.executable)
2493 os.chmod(fname, 0o700)
2494 p = subprocess.Popen(fname)
2495 p.wait()
2496 os.remove(fname)
2497 self.assertEqual(p.returncode, 47)
2498
2499 def test_invalid_args(self):
2500 # invalid arguments should raise ValueError
2501 self.assertRaises(ValueError, subprocess.call,
2502 [sys.executable, "-c",
2503 "import sys; sys.exit(47)"],
2504 startupinfo=47)
2505 self.assertRaises(ValueError, subprocess.call,
2506 [sys.executable, "-c",
2507 "import sys; sys.exit(47)"],
2508 creationflags=47)
2509
2510 def test_shell_sequence(self):
2511 # Run command through the shell (sequence)
2512 newenv = os.environ.copy()
2513 newenv["FRUIT"] = "apple"
2514 p = subprocess.Popen(["echo $FRUIT"], shell=1,
2515 stdout=subprocess.PIPE,
2516 env=newenv)
2517 with p:
2518 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
2519
2520 def test_shell_string(self):
2521 # Run command through the shell (string)
2522 newenv = os.environ.copy()
2523 newenv["FRUIT"] = "apple"
2524 p = subprocess.Popen("echo $FRUIT", shell=1,
2525 stdout=subprocess.PIPE,
2526 env=newenv)
2527 with p:
2528 self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
2529
2530 def test_call_string(self):
2531 # call() function with string argument on UNIX
2532 fd, fname = tempfile.mkstemp()
2533 # reopen in text mode
2534 with open(fd, "w", errors="surrogateescape") as fobj:
2535 fobj.write("#!%s\n" % support.unix_shell)
2536 fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
2537 sys.executable)
2538 os.chmod(fname, 0o700)
2539 rc = subprocess.call(fname)
2540 os.remove(fname)
2541 self.assertEqual(rc, 47)
2542
2543 def test_specific_shell(self):
2544 # Issue #9265: Incorrect name passed as arg[0].
2545 shells = []
2546 for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
2547 for name in ['bash', 'ksh']:
2548 sh = os.path.join(prefix, name)
2549 if os.path.isfile(sh):
2550 shells.append(sh)
2551 if not shells: # Will probably work for any shell but csh.
2552 self.skipTest("bash or ksh required for this test")
2553 sh = '/bin/sh'
2554 if os.path.isfile(sh) and not os.path.islink(sh):
2555 # Test will fail if /bin/sh is a symlink to csh.
2556 shells.append(sh)
2557 for sh in shells:
2558 p = subprocess.Popen("echo $0", executable=sh, shell=True,
2559 stdout=subprocess.PIPE)
2560 with p:
2561 self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
2562
2563 def _kill_process(self, method, *args):
2564 # Do not inherit file handles from the parent.
2565 # It should fix failures on some platforms.
2566 # Also set the SIGINT handler to the default to make sure it's not
2567 # being ignored (some tests rely on that.)
2568 old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
2569 try:
2570 p = subprocess.Popen([sys.executable, "-c", """if 1:
2571 import sys, time
2572 sys.stdout.write('x\\n')
2573 sys.stdout.flush()
2574 time.sleep(30)
2575 """],
2576 close_fds=True,
2577 stdin=subprocess.PIPE,
2578 stdout=subprocess.PIPE,
2579 stderr=subprocess.PIPE)
2580 finally:
2581 signal.signal(signal.SIGINT, old_handler)
2582 # Wait for the interpreter to be completely initialized before
2583 # sending any signal.
2584 p.stdout.read(1)
2585 getattr(p, method)(*args)
2586 return p
2587
2588 @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
2589 "Due to known OS bug (issue #16762)")
2590 def _kill_dead_process(self, method, *args):
2591 # Do not inherit file handles from the parent.
2592 # It should fix failures on some platforms.
2593 p = subprocess.Popen([sys.executable, "-c", """if 1:
2594 import sys, time
2595 sys.stdout.write('x\\n')
2596 sys.stdout.flush()
2597 """],
2598 close_fds=True,
2599 stdin=subprocess.PIPE,
2600 stdout=subprocess.PIPE,
2601 stderr=subprocess.PIPE)
2602 # Wait for the interpreter to be completely initialized before
2603 # sending any signal.
2604 p.stdout.read(1)
2605 # The process should end after this
2606 time.sleep(1)
2607 # This shouldn't raise even though the child is now dead
2608 getattr(p, method)(*args)
2609 p.communicate()
2610
2611 def test_send_signal(self):
2612 p = self._kill_process('send_signal', signal.SIGINT)
2613 _, stderr = p.communicate()
2614 self.assertIn(b'KeyboardInterrupt', stderr)
2615 self.assertNotEqual(p.wait(), 0)
2616
2617 def test_kill(self):
2618 p = self._kill_process('kill')
2619 _, stderr = p.communicate()
2620 self.assertEqual(stderr, b'')
2621 self.assertEqual(p.wait(), -signal.SIGKILL)
2622
2623 def test_terminate(self):
2624 p = self._kill_process('terminate')
2625 _, stderr = p.communicate()
2626 self.assertEqual(stderr, b'')
2627 self.assertEqual(p.wait(), -signal.SIGTERM)
2628
2629 def test_send_signal_dead(self):
2630 # Sending a signal to a dead process
2631 self._kill_dead_process('send_signal', signal.SIGINT)
2632
2633 def test_kill_dead(self):
2634 # Killing a dead process
2635 self._kill_dead_process('kill')
2636
2637 def test_terminate_dead(self):
2638 # Terminating a dead process
2639 self._kill_dead_process('terminate')
2640
2641 def _save_fds(self, save_fds):
2642 fds = []
2643 for fd in save_fds:
2644 inheritable = os.get_inheritable(fd)
2645 saved = os.dup(fd)
2646 fds.append((fd, saved, inheritable))
2647 return fds
2648
2649 def _restore_fds(self, fds):
2650 for fd, saved, inheritable in fds:
2651 os.dup2(saved, fd, inheritable=inheritable)
2652 os.close(saved)
2653
2654 def check_close_std_fds(self, fds):
2655 # Issue #9905: test that subprocess pipes still work properly with
2656 # some standard fds closed
2657 stdin = 0
2658 saved_fds = self._save_fds(fds)
2659 for fd, saved, inheritable in saved_fds:
2660 if fd == 0:
2661 stdin = saved
2662 break
2663 try:
2664 for fd in fds:
2665 os.close(fd)
2666 out, err = subprocess.Popen([sys.executable, "-c",
2667 'import sys;'
2668 'sys.stdout.write("apple");'
2669 'sys.stdout.flush();'
2670 'sys.stderr.write("orange")'],
2671 stdin=stdin,
2672 stdout=subprocess.PIPE,
2673 stderr=subprocess.PIPE).communicate()
2674 self.assertEqual(out, b'apple')
2675 self.assertEqual(err, b'orange')
2676 finally:
2677 self._restore_fds(saved_fds)
2678
2679 def test_close_fd_0(self):
2680 self.check_close_std_fds([0])
2681
2682 def test_close_fd_1(self):
2683 self.check_close_std_fds([1])
2684
2685 def test_close_fd_2(self):
2686 self.check_close_std_fds([2])
2687
2688 def test_close_fds_0_1(self):
2689 self.check_close_std_fds([0, 1])
2690
2691 def test_close_fds_0_2(self):
2692 self.check_close_std_fds([0, 2])
2693
2694 def test_close_fds_1_2(self):
2695 self.check_close_std_fds([1, 2])
2696
2697 def test_close_fds_0_1_2(self):
2698 # Issue #10806: test that subprocess pipes still work properly with
2699 # all standard fds closed.
2700 self.check_close_std_fds([0, 1, 2])
2701
2702 def test_small_errpipe_write_fd(self):
2703 """Issue #15798: Popen should work when stdio fds are available."""
2704 new_stdin = os.dup(0)
2705 new_stdout = os.dup(1)
2706 try:
2707 os.close(0)
2708 os.close(1)
2709
2710 # Side test: if errpipe_write fails to have its CLOEXEC
2711 # flag set this should cause the parent to think the exec
2712 # failed. Extremely unlikely: everyone supports CLOEXEC.
2713 subprocess.Popen([
2714 sys.executable, "-c",
2715 "print('AssertionError:0:CLOEXEC failure.')"]).wait()
2716 finally:
2717 # Restore original stdin and stdout
2718 os.dup2(new_stdin, 0)
2719 os.dup2(new_stdout, 1)
2720 os.close(new_stdin)
2721 os.close(new_stdout)
2722
2723 def test_remapping_std_fds(self):
2724 # open up some temporary files
2725 temps = [tempfile.mkstemp() for i in range(3)]
2726 try:
2727 temp_fds = [fd for fd, fname in temps]
2728
2729 # unlink the files -- we won't need to reopen them
2730 for fd, fname in temps:
2731 os.unlink(fname)
2732
2733 # write some data to what will become stdin, and rewind
2734 os.write(temp_fds[1], b"STDIN")
2735 os.lseek(temp_fds[1], 0, 0)
2736
2737 # move the standard file descriptors out of the way
2738 saved_fds = self._save_fds(range(3))
2739 try:
2740 # duplicate the file objects over the standard fd's
2741 for fd, temp_fd in enumerate(temp_fds):
2742 os.dup2(temp_fd, fd)
2743
2744 # now use those files in the "wrong" order, so that subprocess
2745 # has to rearrange them in the child
2746 p = subprocess.Popen([sys.executable, "-c",
2747 'import sys; got = sys.stdin.read();'
2748 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2749 stdin=temp_fds[1],
2750 stdout=temp_fds[2],
2751 stderr=temp_fds[0])
2752 p.wait()
2753 finally:
2754 self._restore_fds(saved_fds)
2755
2756 for fd in temp_fds:
2757 os.lseek(fd, 0, 0)
2758
2759 out = os.read(temp_fds[2], 1024)
2760 err = os.read(temp_fds[0], 1024).strip()
2761 self.assertEqual(out, b"got STDIN")
2762 self.assertEqual(err, b"err")
2763
2764 finally:
2765 for fd in temp_fds:
2766 os.close(fd)
2767
2768 def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
2769 # open up some temporary files
2770 temps = [tempfile.mkstemp() for i in range(3)]
2771 temp_fds = [fd for fd, fname in temps]
2772 try:
2773 # unlink the files -- we won't need to reopen them
2774 for fd, fname in temps:
2775 os.unlink(fname)
2776
2777 # save a copy of the standard file descriptors
2778 saved_fds = self._save_fds(range(3))
2779 try:
2780 # duplicate the temp files over the standard fd's 0, 1, 2
2781 for fd, temp_fd in enumerate(temp_fds):
2782 os.dup2(temp_fd, fd)
2783
2784 # write some data to what will become stdin, and rewind
2785 os.write(stdin_no, b"STDIN")
2786 os.lseek(stdin_no, 0, 0)
2787
2788 # now use those files in the given order, so that subprocess
2789 # has to rearrange them in the child
2790 p = subprocess.Popen([sys.executable, "-c",
2791 'import sys; got = sys.stdin.read();'
2792 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
2793 stdin=stdin_no,
2794 stdout=stdout_no,
2795 stderr=stderr_no)
2796 p.wait()
2797
2798 for fd in temp_fds:
2799 os.lseek(fd, 0, 0)
2800
2801 out = os.read(stdout_no, 1024)
2802 err = os.read(stderr_no, 1024).strip()
2803 finally:
2804 self._restore_fds(saved_fds)
2805
2806 self.assertEqual(out, b"got STDIN")
2807 self.assertEqual(err, b"err")
2808
2809 finally:
2810 for fd in temp_fds:
2811 os.close(fd)
2812
2813 # When duping fds, if there arises a situation where one of the fds is
2814 # either 0, 1 or 2, it is possible that it is overwritten (#12607).
2815 # This tests all combinations of this.
2816 def test_swap_fds(self):
2817 self.check_swap_fds(0, 1, 2)
2818 self.check_swap_fds(0, 2, 1)
2819 self.check_swap_fds(1, 0, 2)
2820 self.check_swap_fds(1, 2, 0)
2821 self.check_swap_fds(2, 0, 1)
2822 self.check_swap_fds(2, 1, 0)
2823
2824 def _check_swap_std_fds_with_one_closed(self, from_fds, to_fds):
2825 saved_fds = self._save_fds(range(3))
2826 try:
2827 for from_fd in from_fds:
2828 with tempfile.TemporaryFile() as f:
2829 os.dup2(f.fileno(), from_fd)
2830
2831 fd_to_close = (set(range(3)) - set(from_fds)).pop()
2832 os.close(fd_to_close)
2833
2834 arg_names = ['stdin', 'stdout', 'stderr']
2835 kwargs = {}
2836 for from_fd, to_fd in zip(from_fds, to_fds):
2837 kwargs[arg_names[to_fd]] = from_fd
2838
2839 code = textwrap.dedent(r'''
2840 import os, sys
2841 skipped_fd = int(sys.argv[1])
2842 for fd in range(3):
2843 if fd != skipped_fd:
2844 os.write(fd, str(fd).encode('ascii'))
2845 ''')
2846
2847 skipped_fd = (set(range(3)) - set(to_fds)).pop()
2848
2849 rc = subprocess.call([sys.executable, '-c', code, str(skipped_fd)],
2850 **kwargs)
2851 self.assertEqual(rc, 0)
2852
2853 for from_fd, to_fd in zip(from_fds, to_fds):
2854 os.lseek(from_fd, 0, os.SEEK_SET)
2855 read_bytes = os.read(from_fd, 1024)
2856 read_fds = list(map(int, read_bytes.decode('ascii')))
2857 msg = textwrap.dedent(f"""
2858 When testing {from_fds} to {to_fds} redirection,
2859 parent descriptor {from_fd} got redirected
2860 to descriptor(s) {read_fds} instead of descriptor {to_fd}.
2861 """)
2862 self.assertEqual([to_fd], read_fds, msg)
2863 finally:
2864 self._restore_fds(saved_fds)
2865
2866 # Check that subprocess can remap std fds correctly even
2867 # if one of them is closed (#32844).
2868 def test_swap_std_fds_with_one_closed(self):
2869 for from_fds in itertools.combinations(range(3), 2):
2870 for to_fds in itertools.permutations(range(3), 2):
2871 self._check_swap_std_fds_with_one_closed(from_fds, to_fds)
2872
2873 def test_surrogates_error_message(self):
2874 def prepare():
2875 raise ValueError("surrogate:\uDCff")
2876
2877 try:
2878 subprocess.call(
2879 ZERO_RETURN_CMD,
2880 preexec_fn=prepare)
2881 except ValueError as err:
2882 # Pure Python implementations keeps the message
2883 self.assertIsNone(subprocess._fork_exec)
2884 self.assertEqual(str(err), "surrogate:\uDCff")
2885 except subprocess.SubprocessError as err:
2886 # _posixsubprocess uses a default message
2887 self.assertIsNotNone(subprocess._fork_exec)
2888 self.assertEqual(str(err), "Exception occurred in preexec_fn.")
2889 else:
2890 self.fail("Expected ValueError or subprocess.SubprocessError")
2891
2892 def test_undecodable_env(self):
2893 for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
2894 encoded_value = value.encode("ascii", "surrogateescape")
2895
2896 # test str with surrogates
2897 script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
2898 env = os.environ.copy()
2899 env[key] = value
2900 # Use C locale to get ASCII for the locale encoding to force
2901 # surrogate-escaping of \xFF in the child process
2902 env['LC_ALL'] = 'C'
2903 decoded_value = value
2904 stdout = subprocess.check_output(
2905 [sys.executable, "-c", script],
2906 env=env)
2907 stdout = stdout.rstrip(b'\n\r')
2908 self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
2909
2910 # test bytes
2911 key = key.encode("ascii", "surrogateescape")
2912 script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
2913 env = os.environ.copy()
2914 env[key] = encoded_value
2915 stdout = subprocess.check_output(
2916 [sys.executable, "-c", script],
2917 env=env)
2918 stdout = stdout.rstrip(b'\n\r')
2919 self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
2920
2921 def test_bytes_program(self):
2922 abs_program = os.fsencode(ZERO_RETURN_CMD[0])
2923 args = list(ZERO_RETURN_CMD[1:])
2924 path, program = os.path.split(ZERO_RETURN_CMD[0])
2925 program = os.fsencode(program)
2926
2927 # absolute bytes path
2928 exitcode = subprocess.call([abs_program]+args)
2929 self.assertEqual(exitcode, 0)
2930
2931 # absolute bytes path as a string
2932 cmd = b"'%s' %s" % (abs_program, " ".join(args).encode("utf-8"))
2933 exitcode = subprocess.call(cmd, shell=True)
2934 self.assertEqual(exitcode, 0)
2935
2936 # bytes program, unicode PATH
2937 env = os.environ.copy()
2938 env["PATH"] = path
2939 exitcode = subprocess.call([program]+args, env=env)
2940 self.assertEqual(exitcode, 0)
2941
2942 # bytes program, bytes PATH
2943 envb = os.environb.copy()
2944 envb[b"PATH"] = os.fsencode(path)
2945 exitcode = subprocess.call([program]+args, env=envb)
2946 self.assertEqual(exitcode, 0)
2947
2948 def test_pipe_cloexec(self):
2949 sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
2950 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
2951
2952 p1 = subprocess.Popen([sys.executable, sleeper],
2953 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2954 stderr=subprocess.PIPE, close_fds=False)
2955
2956 self.addCleanup(p1.communicate, b'')
2957
2958 p2 = subprocess.Popen([sys.executable, fd_status],
2959 stdout=subprocess.PIPE, close_fds=False)
2960
2961 output, error = p2.communicate()
2962 result_fds = set(map(int, output.split(b',')))
2963 unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
2964 p1.stderr.fileno()])
2965
2966 self.assertFalse(result_fds & unwanted_fds,
2967 "Expected no fds from %r to be open in child, "
2968 "found %r" %
2969 (unwanted_fds, result_fds & unwanted_fds))
2970
2971 def test_pipe_cloexec_real_tools(self):
2972 qcat = support.findfile("qcat.py", subdir="subprocessdata")
2973 qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
2974
2975 subdata = b'zxcvbn'
2976 data = subdata * 4 + b'\n'
2977
2978 p1 = subprocess.Popen([sys.executable, qcat],
2979 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2980 close_fds=False)
2981
2982 p2 = subprocess.Popen([sys.executable, qgrep, subdata],
2983 stdin=p1.stdout, stdout=subprocess.PIPE,
2984 close_fds=False)
2985
2986 self.addCleanup(p1.wait)
2987 self.addCleanup(p2.wait)
2988 def kill_p1():
2989 try:
2990 p1.terminate()
2991 except ProcessLookupError:
2992 pass
2993 def kill_p2():
2994 try:
2995 p2.terminate()
2996 except ProcessLookupError:
2997 pass
2998 self.addCleanup(kill_p1)
2999 self.addCleanup(kill_p2)
3000
3001 p1.stdin.write(data)
3002 p1.stdin.close()
3003
3004 readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
3005
3006 self.assertTrue(readfiles, "The child hung")
3007 self.assertEqual(p2.stdout.read(), data)
3008
3009 p1.stdout.close()
3010 p2.stdout.close()
3011
3012 def test_close_fds(self):
3013 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
3014
3015 fds = os.pipe()
3016 self.addCleanup(os.close, fds[0])
3017 self.addCleanup(os.close, fds[1])
3018
3019 open_fds = set(fds)
3020 # add a bunch more fds
3021 for _ in range(9):
3022 fd = os.open(os.devnull, os.O_RDONLY)
3023 self.addCleanup(os.close, fd)
3024 open_fds.add(fd)
3025
3026 for fd in open_fds:
3027 os.set_inheritable(fd, True)
3028
3029 p = subprocess.Popen([sys.executable, fd_status],
3030 stdout=subprocess.PIPE, close_fds=False)
3031 output, ignored = p.communicate()
3032 remaining_fds = set(map(int, output.split(b',')))
3033
3034 self.assertEqual(remaining_fds & open_fds, open_fds,
3035 "Some fds were closed")
3036
3037 p = subprocess.Popen([sys.executable, fd_status],
3038 stdout=subprocess.PIPE, close_fds=True)
3039 output, ignored = p.communicate()
3040 remaining_fds = set(map(int, output.split(b',')))
3041
3042 self.assertFalse(remaining_fds & open_fds,
3043 "Some fds were left open")
3044 self.assertIn(1, remaining_fds, "Subprocess failed")
3045
3046 # Keep some of the fd's we opened open in the subprocess.
3047 # This tests _posixsubprocess.c's proper handling of fds_to_keep.
3048 fds_to_keep = set(open_fds.pop() for _ in range(8))
3049 p = subprocess.Popen([sys.executable, fd_status],
3050 stdout=subprocess.PIPE, close_fds=True,
3051 pass_fds=fds_to_keep)
3052 output, ignored = p.communicate()
3053 remaining_fds = set(map(int, output.split(b',')))
3054
3055 self.assertFalse((remaining_fds - fds_to_keep) & open_fds,
3056 "Some fds not in pass_fds were left open")
3057 self.assertIn(1, remaining_fds, "Subprocess failed")
3058
3059
3060 @unittest.skipIf(sys.platform.startswith("freebsd") and
3061 os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
3062 "Requires fdescfs mounted on /dev/fd on FreeBSD")
3063 def test_close_fds_when_max_fd_is_lowered(self):
3064 """Confirm that issue21618 is fixed (may fail under valgrind)."""
3065 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
3066
3067 # This launches the meat of the test in a child process to
3068 # avoid messing with the larger unittest processes maximum
3069 # number of file descriptors.
3070 # This process launches:
3071 # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
3072 # a bunch of high open fds above the new lower rlimit.
3073 # Those are reported via stdout before launching a new
3074 # process with close_fds=False to run the actual test:
3075 # +--> The TEST: This one launches a fd_status.py
3076 # subprocess with close_fds=True so we can find out if
3077 # any of the fds above the lowered rlimit are still open.
3078 p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
3079 '''
3080 import os, resource, subprocess, sys, textwrap
3081 open_fds = set()
3082 # Add a bunch more fds to pass down.
3083 for _ in range(40):
3084 fd = os.open(os.devnull, os.O_RDONLY)
3085 open_fds.add(fd)
3086
3087 # Leave a two pairs of low ones available for use by the
3088 # internal child error pipe and the stdout pipe.
3089 # We also leave 10 more open as some Python buildbots run into
3090 # "too many open files" errors during the test if we do not.
3091 for fd in sorted(open_fds)[:14]:
3092 os.close(fd)
3093 open_fds.remove(fd)
3094
3095 for fd in open_fds:
3096 #self.addCleanup(os.close, fd)
3097 os.set_inheritable(fd, True)
3098
3099 max_fd_open = max(open_fds)
3100
3101 # Communicate the open_fds to the parent unittest.TestCase process.
3102 print(','.join(map(str, sorted(open_fds))))
3103 sys.stdout.flush()
3104
3105 rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
3106 try:
3107 # 29 is lower than the highest fds we are leaving open.
3108 resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
3109 # Launch a new Python interpreter with our low fd rlim_cur that
3110 # inherits open fds above that limit. It then uses subprocess
3111 # with close_fds=True to get a report of open fds in the child.
3112 # An explicit list of fds to check is passed to fd_status.py as
3113 # letting fd_status rely on its default logic would miss the
3114 # fds above rlim_cur as it normally only checks up to that limit.
3115 subprocess.Popen(
3116 [sys.executable, '-c',
3117 textwrap.dedent("""
3118 import subprocess, sys
3119 subprocess.Popen([sys.executable, %r] +
3120 [str(x) for x in range({max_fd})],
3121 close_fds=True).wait()
3122 """.format(max_fd=max_fd_open+1))],
3123 close_fds=False).wait()
3124 finally:
3125 resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
3126 ''' % fd_status)], stdout=subprocess.PIPE)
3127
3128 output, unused_stderr = p.communicate()
3129 output_lines = output.splitlines()
3130 self.assertEqual(len(output_lines), 2,
3131 msg="expected exactly two lines of output:\n%r" % output)
3132 opened_fds = set(map(int, output_lines[0].strip().split(b',')))
3133 remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
3134
3135 self.assertFalse(remaining_fds & opened_fds,
3136 msg="Some fds were left open.")
3137
3138
3139 # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
3140 # descriptor of a pipe closed in the parent process is valid in the
3141 # child process according to fstat(), but the mode of the file
3142 # descriptor is invalid, and read or write raise an error.
3143 @support.requires_mac_ver(10, 5)
3144 def test_pass_fds(self):
3145 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
3146
3147 open_fds = set()
3148
3149 for x in range(5):
3150 fds = os.pipe()
3151 self.addCleanup(os.close, fds[0])
3152 self.addCleanup(os.close, fds[1])
3153 os.set_inheritable(fds[0], True)
3154 os.set_inheritable(fds[1], True)
3155 open_fds.update(fds)
3156
3157 for fd in open_fds:
3158 p = subprocess.Popen([sys.executable, fd_status],
3159 stdout=subprocess.PIPE, close_fds=True,
3160 pass_fds=(fd, ))
3161 output, ignored = p.communicate()
3162
3163 remaining_fds = set(map(int, output.split(b',')))
3164 to_be_closed = open_fds - {fd}
3165
3166 self.assertIn(fd, remaining_fds, "fd to be passed not passed")
3167 self.assertFalse(remaining_fds & to_be_closed,
3168 "fd to be closed passed")
3169
3170 # pass_fds overrides close_fds with a warning.
3171 with self.assertWarns(RuntimeWarning) as context:
3172 self.assertFalse(subprocess.call(
3173 ZERO_RETURN_CMD,
3174 close_fds=False, pass_fds=(fd, )))
3175 self.assertIn('overriding close_fds', str(context.warning))
3176
3177 def test_pass_fds_inheritable(self):
3178 script = support.findfile("fd_status.py", subdir="subprocessdata")
3179
3180 inheritable, non_inheritable = os.pipe()
3181 self.addCleanup(os.close, inheritable)
3182 self.addCleanup(os.close, non_inheritable)
3183 os.set_inheritable(inheritable, True)
3184 os.set_inheritable(non_inheritable, False)
3185 pass_fds = (inheritable, non_inheritable)
3186 args = [sys.executable, script]
3187 args += list(map(str, pass_fds))
3188
3189 p = subprocess.Popen(args,
3190 stdout=subprocess.PIPE, close_fds=True,
3191 pass_fds=pass_fds)
3192 output, ignored = p.communicate()
3193 fds = set(map(int, output.split(b',')))
3194
3195 # the inheritable file descriptor must be inherited, so its inheritable
3196 # flag must be set in the child process after fork() and before exec()
3197 self.assertEqual(fds, set(pass_fds), "output=%a" % output)
3198
3199 # inheritable flag must not be changed in the parent process
3200 self.assertEqual(os.get_inheritable(inheritable), True)
3201 self.assertEqual(os.get_inheritable(non_inheritable), False)
3202
3203
3204 # bpo-32270: Ensure that descriptors specified in pass_fds
3205 # are inherited even if they are used in redirections.
3206 # Contributed by @izbyshev.
3207 def test_pass_fds_redirected(self):
3208 """Regression test for https://bugs.python.org/issue32270."""
3209 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
3210 pass_fds = []
3211 for _ in range(2):
3212 fd = os.open(os.devnull, os.O_RDWR)
3213 self.addCleanup(os.close, fd)
3214 pass_fds.append(fd)
3215
3216 stdout_r, stdout_w = os.pipe()
3217 self.addCleanup(os.close, stdout_r)
3218 self.addCleanup(os.close, stdout_w)
3219 pass_fds.insert(1, stdout_w)
3220
3221 with subprocess.Popen([sys.executable, fd_status],
3222 stdin=pass_fds[0],
3223 stdout=pass_fds[1],
3224 stderr=pass_fds[2],
3225 close_fds=True,
3226 pass_fds=pass_fds):
3227 output = os.read(stdout_r, 1024)
3228 fds = {int(num) for num in output.split(b',')}
3229
3230 self.assertEqual(fds, {0, 1, 2} | frozenset(pass_fds), f"output={output!a}")
3231
3232
3233 def test_stdout_stdin_are_single_inout_fd(self):
3234 with io.open(os.devnull, "r+") as inout:
3235 p = subprocess.Popen(ZERO_RETURN_CMD,
3236 stdout=inout, stdin=inout)
3237 p.wait()
3238
3239 def test_stdout_stderr_are_single_inout_fd(self):
3240 with io.open(os.devnull, "r+") as inout:
3241 p = subprocess.Popen(ZERO_RETURN_CMD,
3242 stdout=inout, stderr=inout)
3243 p.wait()
3244
3245 def test_stderr_stdin_are_single_inout_fd(self):
3246 with io.open(os.devnull, "r+") as inout:
3247 p = subprocess.Popen(ZERO_RETURN_CMD,
3248 stderr=inout, stdin=inout)
3249 p.wait()
3250
3251 def test_wait_when_sigchild_ignored(self):
3252 # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
3253 sigchild_ignore = support.findfile("sigchild_ignore.py",
3254 subdir="subprocessdata")
3255 p = subprocess.Popen([sys.executable, sigchild_ignore],
3256 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
3257 stdout, stderr = p.communicate()
3258 self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
3259 " non-zero with this error:\n%s" %
3260 stderr.decode('utf-8'))
3261
3262 def test_select_unbuffered(self):
3263 # Issue #11459: bufsize=0 should really set the pipes as
3264 # unbuffered (and therefore let select() work properly).
3265 select = import_helper.import_module("select")
3266 p = subprocess.Popen([sys.executable, "-c",
3267 'import sys;'
3268 'sys.stdout.write("apple")'],
3269 stdout=subprocess.PIPE,
3270 bufsize=0)
3271 f = p.stdout
3272 self.addCleanup(f.close)
3273 try:
3274 self.assertEqual(f.read(4), b"appl")
3275 self.assertIn(f, select.select([f], [], [], 0.0)[0])
3276 finally:
3277 p.wait()
3278
3279 def test_zombie_fast_process_del(self):
3280 # Issue #12650: on Unix, if Popen.__del__() was called before the
3281 # process exited, it wouldn't be added to subprocess._active, and would
3282 # remain a zombie.
3283 # spawn a Popen, and delete its reference before it exits
3284 p = subprocess.Popen([sys.executable, "-c",
3285 'import sys, time;'
3286 'time.sleep(0.2)'],
3287 stdout=subprocess.PIPE,
3288 stderr=subprocess.PIPE)
3289 self.addCleanup(p.stdout.close)
3290 self.addCleanup(p.stderr.close)
3291 ident = id(p)
3292 pid = p.pid
3293 with warnings_helper.check_warnings(('', ResourceWarning)):
3294 p = None
3295
3296 if mswindows:
3297 # subprocess._active is not used on Windows and is set to None.
3298 self.assertIsNone(subprocess._active)
3299 else:
3300 # check that p is in the active processes list
3301 self.assertIn(ident, [id(o) for o in subprocess._active])
3302
3303 def test_leak_fast_process_del_killed(self):
3304 # Issue #12650: on Unix, if Popen.__del__() was called before the
3305 # process exited, and the process got killed by a signal, it would never
3306 # be removed from subprocess._active, which triggered a FD and memory
3307 # leak.
3308 # spawn a Popen, delete its reference and kill it
3309 p = subprocess.Popen([sys.executable, "-c",
3310 'import time;'
3311 'time.sleep(3)'],
3312 stdout=subprocess.PIPE,
3313 stderr=subprocess.PIPE)
3314 self.addCleanup(p.stdout.close)
3315 self.addCleanup(p.stderr.close)
3316 ident = id(p)
3317 pid = p.pid
3318 with warnings_helper.check_warnings(('', ResourceWarning)):
3319 p = None
3320 support.gc_collect() # For PyPy or other GCs.
3321
3322 os.kill(pid, signal.SIGKILL)
3323 if mswindows:
3324 # subprocess._active is not used on Windows and is set to None.
3325 self.assertIsNone(subprocess._active)
3326 else:
3327 # check that p is in the active processes list
3328 self.assertIn(ident, [id(o) for o in subprocess._active])
3329
3330 # let some time for the process to exit, and create a new Popen: this
3331 # should trigger the wait() of p
3332 time.sleep(0.2)
3333 with self.assertRaises(OSError):
3334 with subprocess.Popen(NONEXISTING_CMD,
3335 stdout=subprocess.PIPE,
3336 stderr=subprocess.PIPE) as proc:
3337 pass
3338 # p should have been wait()ed on, and removed from the _active list
3339 self.assertRaises(OSError, os.waitpid, pid, 0)
3340 if mswindows:
3341 # subprocess._active is not used on Windows and is set to None.
3342 self.assertIsNone(subprocess._active)
3343 else:
3344 self.assertNotIn(ident, [id(o) for o in subprocess._active])
3345
3346 def test_close_fds_after_preexec(self):
3347 fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
3348
3349 # this FD is used as dup2() target by preexec_fn, and should be closed
3350 # in the child process
3351 fd = os.dup(1)
3352 self.addCleanup(os.close, fd)
3353
3354 p = subprocess.Popen([sys.executable, fd_status],
3355 stdout=subprocess.PIPE, close_fds=True,
3356 preexec_fn=lambda: os.dup2(1, fd))
3357 output, ignored = p.communicate()
3358
3359 remaining_fds = set(map(int, output.split(b',')))
3360
3361 self.assertNotIn(fd, remaining_fds)
3362
3363 @support.cpython_only
3364 def test_fork_exec(self):
3365 # Issue #22290: fork_exec() must not crash on memory allocation failure
3366 # or other errors
3367 import _posixsubprocess
3368 gc_enabled = gc.isenabled()
3369 try:
3370 # Use a preexec function and enable the garbage collector
3371 # to force fork_exec() to re-enable the garbage collector
3372 # on error.
3373 func = lambda: None
3374 gc.enable()
3375
3376 for args, exe_list, cwd, env_list in (
3377 (123, [b"exe"], None, [b"env"]),
3378 ([b"arg"], 123, None, [b"env"]),
3379 ([b"arg"], [b"exe"], 123, [b"env"]),
3380 ([b"arg"], [b"exe"], None, 123),
3381 ):
3382 with self.assertRaises(TypeError) as err:
3383 _posixsubprocess.fork_exec(
3384 args, exe_list,
3385 True, (), cwd, env_list,
3386 -1, -1, -1, -1,
3387 1, 2, 3, 4,
3388 True, True, 0,
3389 False, [], 0, -1,
3390 func, False)
3391 # Attempt to prevent
3392 # "TypeError: fork_exec() takes exactly N arguments (M given)"
3393 # from passing the test. More refactoring to have us start
3394 # with a valid *args list, confirm a good call with that works
3395 # before mutating it in various ways to ensure that bad calls
3396 # with individual arg type errors raise a typeerror would be
3397 # ideal. Saving that for a future PR...
3398 self.assertNotIn('takes exactly', str(err.exception))
3399 finally:
3400 if not gc_enabled:
3401 gc.disable()
3402
3403 @support.cpython_only
3404 def test_fork_exec_sorted_fd_sanity_check(self):
3405 # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
3406 import _posixsubprocess
3407 class BadInt:
3408 first = True
3409 def __init__(self, value):
3410 self.value = value
3411 def __int__(self):
3412 if self.first:
3413 self.first = False
3414 return self.value
3415 raise ValueError
3416
3417 gc_enabled = gc.isenabled()
3418 try:
3419 gc.enable()
3420
3421 for fds_to_keep in (
3422 (-1, 2, 3, 4, 5), # Negative number.
3423 ('str', 4), # Not an int.
3424 (18, 23, 42, 2**63), # Out of range.
3425 (5, 4), # Not sorted.
3426 (6, 7, 7, 8), # Duplicate.
3427 (BadInt(1), BadInt(2)),
3428 ):
3429 with self.assertRaises(
3430 ValueError,
3431 msg='fds_to_keep={}'.format(fds_to_keep)) as c:
3432 _posixsubprocess.fork_exec(
3433 [b"false"], [b"false"],
3434 True, fds_to_keep, None, [b"env"],
3435 -1, -1, -1, -1,
3436 1, 2, 3, 4,
3437 True, True, 0,
3438 None, None, None, -1,
3439 None, True)
3440 self.assertIn('fds_to_keep', str(c.exception))
3441 finally:
3442 if not gc_enabled:
3443 gc.disable()
3444
3445 def test_communicate_BrokenPipeError_stdin_close(self):
3446 # By not setting stdout or stderr or a timeout we force the fast path
3447 # that just calls _stdin_write() internally due to our mock.
3448 proc = subprocess.Popen(ZERO_RETURN_CMD)
3449 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3450 mock_proc_stdin.close.side_effect = BrokenPipeError
3451 proc.communicate() # Should swallow BrokenPipeError from close.
3452 mock_proc_stdin.close.assert_called_with()
3453
3454 def test_communicate_BrokenPipeError_stdin_write(self):
3455 # By not setting stdout or stderr or a timeout we force the fast path
3456 # that just calls _stdin_write() internally due to our mock.
3457 proc = subprocess.Popen(ZERO_RETURN_CMD)
3458 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3459 mock_proc_stdin.write.side_effect = BrokenPipeError
3460 proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
3461 mock_proc_stdin.write.assert_called_once_with(b'stuff')
3462 mock_proc_stdin.close.assert_called_once_with()
3463
3464 def test_communicate_BrokenPipeError_stdin_flush(self):
3465 # Setting stdin and stdout forces the ._communicate() code path.
3466 # python -h exits faster than python -c pass (but spams stdout).
3467 proc = subprocess.Popen([sys.executable, '-h'],
3468 stdin=subprocess.PIPE,
3469 stdout=subprocess.PIPE)
3470 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
3471 open(os.devnull, 'wb') as dev_null:
3472 mock_proc_stdin.flush.side_effect = BrokenPipeError
3473 # because _communicate registers a selector using proc.stdin...
3474 mock_proc_stdin.fileno.return_value = dev_null.fileno()
3475 # _communicate() should swallow BrokenPipeError from flush.
3476 proc.communicate(b'stuff')
3477 mock_proc_stdin.flush.assert_called_once_with()
3478
3479 def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
3480 # Setting stdin and stdout forces the ._communicate() code path.
3481 # python -h exits faster than python -c pass (but spams stdout).
3482 proc = subprocess.Popen([sys.executable, '-h'],
3483 stdin=subprocess.PIPE,
3484 stdout=subprocess.PIPE)
3485 with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
3486 mock_proc_stdin.close.side_effect = BrokenPipeError
3487 # _communicate() should swallow BrokenPipeError from close.
3488 proc.communicate(timeout=999)
3489 mock_proc_stdin.close.assert_called_once_with()
3490
3491 @unittest.skipUnless(_testcapi is not None
3492 and hasattr(_testcapi, 'W_STOPCODE'),
3493 'need _testcapi.W_STOPCODE')
3494 def test_stopped(self):
3495 """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
3496 args = ZERO_RETURN_CMD
3497 proc = subprocess.Popen(args)
3498
3499 # Wait until the real process completes to avoid zombie process
3500 support.wait_process(proc.pid, exitcode=0)
3501
3502 status = _testcapi.W_STOPCODE(3)
3503 with mock.patch('subprocess.os.waitpid', return_value=(proc.pid, status)):
3504 returncode = proc.wait()
3505
3506 self.assertEqual(returncode, -3)
3507
3508 def test_send_signal_race(self):
3509 # bpo-38630: send_signal() must poll the process exit status to reduce
3510 # the risk of sending the signal to the wrong process.
3511 proc = subprocess.Popen(ZERO_RETURN_CMD)
3512
3513 # wait until the process completes without using the Popen APIs.
3514 support.wait_process(proc.pid, exitcode=0)
3515
3516 # returncode is still None but the process completed.
3517 self.assertIsNone(proc.returncode)
3518
3519 with mock.patch("os.kill") as mock_kill:
3520 proc.send_signal(signal.SIGTERM)
3521
3522 # send_signal() didn't call os.kill() since the process already
3523 # completed.
3524 mock_kill.assert_not_called()
3525
3526 # Don't check the returncode value: the test reads the exit status,
3527 # so Popen failed to read it and uses a default returncode instead.
3528 self.assertIsNotNone(proc.returncode)
3529
3530 def test_send_signal_race2(self):
3531 # bpo-40550: the process might exist between the returncode check and
3532 # the kill operation
3533 p = subprocess.Popen([sys.executable, '-c', 'exit(1)'])
3534
3535 # wait for process to exit
3536 while not p.returncode:
3537 p.poll()
3538
3539 with mock.patch.object(p, 'poll', new=lambda: None):
3540 p.returncode = None
3541 p.send_signal(signal.SIGTERM)
3542 p.kill()
3543
3544 def test_communicate_repeated_call_after_stdout_close(self):
3545 proc = subprocess.Popen([sys.executable, '-c',
3546 'import os, time; os.close(1), time.sleep(2)'],
3547 stdout=subprocess.PIPE)
3548 while True:
3549 try:
3550 proc.communicate(timeout=0.1)
3551 return
3552 except subprocess.TimeoutExpired:
3553 pass
3554
3555 def test_preexec_at_exit(self):
3556 code = f"""if 1:
3557 import atexit
3558 import subprocess
3559
3560 def dummy():
3561 pass
3562
3563 class AtFinalization:
3564 def __del__(self):
3565 print("OK")
3566 subprocess.Popen({ZERO_RETURN_CMD}, preexec_fn=dummy)
3567 print("shouldn't be printed")
3568 at_finalization = AtFinalization()
3569 """
3570 _, out, err = assert_python_ok("-c", code)
3571 self.assertEqual(out.strip(), b"OK")
3572 self.assertIn(b"preexec_fn not supported at interpreter shutdown", err)
3573
3574 @unittest.skipIf(not sysconfig.get_config_var("HAVE_VFORK"),
3575 "vfork() not enabled by configure.")
3576 @mock.patch("subprocess._fork_exec")
3577 @mock.patch("subprocess._USE_POSIX_SPAWN", new=False)
3578 def test__use_vfork(self, mock_fork_exec):
3579 self.assertTrue(subprocess._USE_VFORK) # The default value regardless.
3580 mock_fork_exec.side_effect = RuntimeError("just testing args")
3581 with self.assertRaises(RuntimeError):
3582 subprocess.run([sys.executable, "-c", "pass"])
3583 mock_fork_exec.assert_called_once()
3584 # NOTE: These assertions are *ugly* as they require the last arg
3585 # to remain the have_vfork boolean. We really need to refactor away
3586 # from the giant "wall of args" internal C extension API.
3587 self.assertTrue(mock_fork_exec.call_args.args[-1])
3588 with mock.patch.object(subprocess, '_USE_VFORK', False):
3589 with self.assertRaises(RuntimeError):
3590 subprocess.run([sys.executable, "-c", "pass"])
3591 self.assertFalse(mock_fork_exec.call_args_list[-1].args[-1])
3592
3593 @unittest.skipIf(not sysconfig.get_config_var("HAVE_VFORK"),
3594 "vfork() not enabled by configure.")
3595 @unittest.skipIf(sys.platform != "linux", "Linux only, requires strace.")
3596 @mock.patch("subprocess._USE_POSIX_SPAWN", new=False)
3597 def test_vfork_used_when_expected(self):
3598 # This is a performance regression test to ensure we default to using
3599 # vfork() when possible.
3600 # Technically this test could pass when posix_spawn is used as well
3601 # because libc tends to implement that internally using vfork. But
3602 # that'd just be testing a libc+kernel implementation detail.
3603 strace_binary = "/usr/bin/strace"
3604 # The only system calls we are interested in.
3605 strace_filter = "--trace=clone,clone2,clone3,fork,vfork,exit,exit_group"
3606 true_binary = "/bin/true"
3607 strace_command = [strace_binary, strace_filter]
3608
3609 try:
3610 does_strace_work_process = subprocess.run(
3611 strace_command + [true_binary],
3612 stderr=subprocess.PIPE,
3613 stdout=subprocess.DEVNULL,
3614 )
3615 rc = does_strace_work_process.returncode
3616 stderr = does_strace_work_process.stderr
3617 except OSError:
3618 rc = -1
3619 stderr = ""
3620 if rc or (b"+++ exited with 0 +++" not in stderr):
3621 self.skipTest("strace not found or not working as expected.")
3622
3623 with self.subTest(name="default_is_vfork"):
3624 vfork_result = assert_python_ok(
3625 "-c",
3626 textwrap.dedent(f"""\
3627 import subprocess
3628 subprocess.check_call([{true_binary!r}])"""),
3629 __run_using_command=strace_command,
3630 )
3631 # Match both vfork() and clone(..., flags=...|CLONE_VFORK|...)
3632 self.assertRegex(vfork_result.err, br"(?i)vfork")
3633 # Do NOT check that fork() or other clones did not happen.
3634 # If the OS denys the vfork it'll fallback to plain fork().
3635
3636 # Test that each individual thing that would disable the use of vfork
3637 # actually disables it.
3638 for sub_name, preamble, sp_kwarg, expect_permission_error in (
3639 ("!use_vfork", "subprocess._USE_VFORK = False", "", False),
3640 ("preexec", "", "preexec_fn=lambda: None", False),
3641 ("setgid", "", f"group={os.getgid()}", True),
3642 ("setuid", "", f"user={os.getuid()}", True),
3643 ("setgroups", "", "extra_groups=[]", True),
3644 ):
3645 with self.subTest(name=sub_name):
3646 non_vfork_result = assert_python_ok(
3647 "-c",
3648 textwrap.dedent(f"""\
3649 import subprocess
3650 {preamble}
3651 try:
3652 subprocess.check_call(
3653 [{true_binary!r}], **dict({sp_kwarg}))
3654 except PermissionError:
3655 if not {expect_permission_error}:
3656 raise"""),
3657 __run_using_command=strace_command,
3658 )
3659 # Ensure neither vfork() or clone(..., flags=...|CLONE_VFORK|...).
3660 self.assertNotRegex(non_vfork_result.err, br"(?i)vfork")
3661
3662
3663 @unittest.skipUnless(mswindows, "Windows specific tests")
3664 class Win32ProcessTestCase(BaseTestCase):
3665
3666 def test_startupinfo(self):
3667 # startupinfo argument
3668 # We uses hardcoded constants, because we do not want to
3669 # depend on win32all.
3670 STARTF_USESHOWWINDOW = 1
3671 SW_MAXIMIZE = 3
3672 startupinfo = subprocess.STARTUPINFO()
3673 startupinfo.dwFlags = STARTF_USESHOWWINDOW
3674 startupinfo.wShowWindow = SW_MAXIMIZE
3675 # Since Python is a console process, it won't be affected
3676 # by wShowWindow, but the argument should be silently
3677 # ignored
3678 subprocess.call(ZERO_RETURN_CMD,
3679 startupinfo=startupinfo)
3680
3681 def test_startupinfo_keywords(self):
3682 # startupinfo argument
3683 # We use hardcoded constants, because we do not want to
3684 # depend on win32all.
3685 STARTF_USERSHOWWINDOW = 1
3686 SW_MAXIMIZE = 3
3687 startupinfo = subprocess.STARTUPINFO(
3688 dwFlags=STARTF_USERSHOWWINDOW,
3689 wShowWindow=SW_MAXIMIZE
3690 )
3691 # Since Python is a console process, it won't be affected
3692 # by wShowWindow, but the argument should be silently
3693 # ignored
3694 subprocess.call(ZERO_RETURN_CMD,
3695 startupinfo=startupinfo)
3696
3697 def test_startupinfo_copy(self):
3698 # bpo-34044: Popen must not modify input STARTUPINFO structure
3699 startupinfo = subprocess.STARTUPINFO()
3700 startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
3701 startupinfo.wShowWindow = subprocess.SW_HIDE
3702
3703 # Call Popen() twice with the same startupinfo object to make sure
3704 # that it's not modified
3705 for _ in range(2):
3706 cmd = ZERO_RETURN_CMD
3707 with open(os.devnull, 'w') as null:
3708 proc = subprocess.Popen(cmd,
3709 stdout=null,
3710 stderr=subprocess.STDOUT,
3711 startupinfo=startupinfo)
3712 with proc:
3713 proc.communicate()
3714 self.assertEqual(proc.returncode, 0)
3715
3716 self.assertEqual(startupinfo.dwFlags,
3717 subprocess.STARTF_USESHOWWINDOW)
3718 self.assertIsNone(startupinfo.hStdInput)
3719 self.assertIsNone(startupinfo.hStdOutput)
3720 self.assertIsNone(startupinfo.hStdError)
3721 self.assertEqual(startupinfo.wShowWindow, subprocess.SW_HIDE)
3722 self.assertEqual(startupinfo.lpAttributeList, {"handle_list": []})
3723
3724 def test_creationflags(self):
3725 # creationflags argument
3726 CREATE_NEW_CONSOLE = 16
3727 sys.stderr.write(" a DOS box should flash briefly ...\n")
3728 subprocess.call(sys.executable +
3729 ' -c "import time; time.sleep(0.25)"',
3730 creationflags=CREATE_NEW_CONSOLE)
3731
3732 def test_invalid_args(self):
3733 # invalid arguments should raise ValueError
3734 self.assertRaises(ValueError, subprocess.call,
3735 [sys.executable, "-c",
3736 "import sys; sys.exit(47)"],
3737 preexec_fn=lambda: 1)
3738
3739 @support.cpython_only
3740 def test_issue31471(self):
3741 # There shouldn't be an assertion failure in Popen() in case the env
3742 # argument has a bad keys() method.
3743 class BadEnv(dict):
3744 keys = None
3745 with self.assertRaises(TypeError):
3746 subprocess.Popen(ZERO_RETURN_CMD, env=BadEnv())
3747
3748 def test_close_fds(self):
3749 # close file descriptors
3750 rc = subprocess.call([sys.executable, "-c",
3751 "import sys; sys.exit(47)"],
3752 close_fds=True)
3753 self.assertEqual(rc, 47)
3754
3755 def test_close_fds_with_stdio(self):
3756 import msvcrt
3757
3758 fds = os.pipe()
3759 self.addCleanup(os.close, fds[0])
3760 self.addCleanup(os.close, fds[1])
3761
3762 handles = []
3763 for fd in fds:
3764 os.set_inheritable(fd, True)
3765 handles.append(msvcrt.get_osfhandle(fd))
3766
3767 p = subprocess.Popen([sys.executable, "-c",
3768 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3769 stdout=subprocess.PIPE, close_fds=False)
3770 stdout, stderr = p.communicate()
3771 self.assertEqual(p.returncode, 0)
3772 int(stdout.strip()) # Check that stdout is an integer
3773
3774 p = subprocess.Popen([sys.executable, "-c",
3775 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3776 stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
3777 stdout, stderr = p.communicate()
3778 self.assertEqual(p.returncode, 1)
3779 self.assertIn(b"OSError", stderr)
3780
3781 # The same as the previous call, but with an empty handle_list
3782 handle_list = []
3783 startupinfo = subprocess.STARTUPINFO()
3784 startupinfo.lpAttributeList = {"handle_list": handle_list}
3785 p = subprocess.Popen([sys.executable, "-c",
3786 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3787 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3788 startupinfo=startupinfo, close_fds=True)
3789 stdout, stderr = p.communicate()
3790 self.assertEqual(p.returncode, 1)
3791 self.assertIn(b"OSError", stderr)
3792
3793 # Check for a warning due to using handle_list and close_fds=False
3794 with warnings_helper.check_warnings((".*overriding close_fds",
3795 RuntimeWarning)):
3796 startupinfo = subprocess.STARTUPINFO()
3797 startupinfo.lpAttributeList = {"handle_list": handles[:]}
3798 p = subprocess.Popen([sys.executable, "-c",
3799 "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
3800 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
3801 startupinfo=startupinfo, close_fds=False)
3802 stdout, stderr = p.communicate()
3803 self.assertEqual(p.returncode, 0)
3804
3805 def test_empty_attribute_list(self):
3806 startupinfo = subprocess.STARTUPINFO()
3807 startupinfo.lpAttributeList = {}
3808 subprocess.call(ZERO_RETURN_CMD,
3809 startupinfo=startupinfo)
3810
3811 def test_empty_handle_list(self):
3812 startupinfo = subprocess.STARTUPINFO()
3813 startupinfo.lpAttributeList = {"handle_list": []}
3814 subprocess.call(ZERO_RETURN_CMD,
3815 startupinfo=startupinfo)
3816
3817 def test_shell_sequence(self):
3818 # Run command through the shell (sequence)
3819 newenv = os.environ.copy()
3820 newenv["FRUIT"] = "physalis"
3821 p = subprocess.Popen(["set"], shell=1,
3822 stdout=subprocess.PIPE,
3823 env=newenv)
3824 with p:
3825 self.assertIn(b"physalis", p.stdout.read())
3826
3827 def test_shell_string(self):
3828 # Run command through the shell (string)
3829 newenv = os.environ.copy()
3830 newenv["FRUIT"] = "physalis"
3831 p = subprocess.Popen("set", shell=1,
3832 stdout=subprocess.PIPE,
3833 env=newenv)
3834 with p:
3835 self.assertIn(b"physalis", p.stdout.read())
3836
3837 def test_shell_encodings(self):
3838 # Run command through the shell (string)
3839 for enc in ['ansi', 'oem']:
3840 newenv = os.environ.copy()
3841 newenv["FRUIT"] = "physalis"
3842 p = subprocess.Popen("set", shell=1,
3843 stdout=subprocess.PIPE,
3844 env=newenv,
3845 encoding=enc)
3846 with p:
3847 self.assertIn("physalis", p.stdout.read(), enc)
3848
3849 def test_call_string(self):
3850 # call() function with string argument on Windows
3851 rc = subprocess.call(sys.executable +
3852 ' -c "import sys; sys.exit(47)"')
3853 self.assertEqual(rc, 47)
3854
3855 def _kill_process(self, method, *args):
3856 # Some win32 buildbot raises EOFError if stdin is inherited
3857 p = subprocess.Popen([sys.executable, "-c", """if 1:
3858 import sys, time
3859 sys.stdout.write('x\\n')
3860 sys.stdout.flush()
3861 time.sleep(30)
3862 """],
3863 stdin=subprocess.PIPE,
3864 stdout=subprocess.PIPE,
3865 stderr=subprocess.PIPE)
3866 with p:
3867 # Wait for the interpreter to be completely initialized before
3868 # sending any signal.
3869 p.stdout.read(1)
3870 getattr(p, method)(*args)
3871 _, stderr = p.communicate()
3872 self.assertEqual(stderr, b'')
3873 returncode = p.wait()
3874 self.assertNotEqual(returncode, 0)
3875
3876 def _kill_dead_process(self, method, *args):
3877 p = subprocess.Popen([sys.executable, "-c", """if 1:
3878 import sys, time
3879 sys.stdout.write('x\\n')
3880 sys.stdout.flush()
3881 sys.exit(42)
3882 """],
3883 stdin=subprocess.PIPE,
3884 stdout=subprocess.PIPE,
3885 stderr=subprocess.PIPE)
3886 with p:
3887 # Wait for the interpreter to be completely initialized before
3888 # sending any signal.
3889 p.stdout.read(1)
3890 # The process should end after this
3891 time.sleep(1)
3892 # This shouldn't raise even though the child is now dead
3893 getattr(p, method)(*args)
3894 _, stderr = p.communicate()
3895 self.assertEqual(stderr, b'')
3896 rc = p.wait()
3897 self.assertEqual(rc, 42)
3898
3899 def test_send_signal(self):
3900 self._kill_process('send_signal', signal.SIGTERM)
3901
3902 def test_kill(self):
3903 self._kill_process('kill')
3904
3905 def test_terminate(self):
3906 self._kill_process('terminate')
3907
3908 def test_send_signal_dead(self):
3909 self._kill_dead_process('send_signal', signal.SIGTERM)
3910
3911 def test_kill_dead(self):
3912 self._kill_dead_process('kill')
3913
3914 def test_terminate_dead(self):
3915 self._kill_dead_process('terminate')
3916
3917 class MiscTests(unittest.TestCase):
3918
3919 class RecordingPopen(subprocess.Popen):
3920 """A Popen that saves a reference to each instance for testing."""
3921 instances_created = []
3922
3923 def __init__(self, *args, **kwargs):
3924 super().__init__(*args, **kwargs)
3925 self.instances_created.append(self)
3926
3927 @mock.patch.object(subprocess.Popen, "_communicate")
3928 def _test_keyboardinterrupt_no_kill(self, popener, mock__communicate,
3929 **kwargs):
3930 """Fake a SIGINT happening during Popen._communicate() and ._wait().
3931
3932 This avoids the need to actually try and get test environments to send
3933 and receive signals reliably across platforms. The net effect of a ^C
3934 happening during a blocking subprocess execution which we want to clean
3935 up from is a KeyboardInterrupt coming out of communicate() or wait().
3936 """
3937
3938 mock__communicate.side_effect = KeyboardInterrupt
3939 try:
3940 with mock.patch.object(subprocess.Popen, "_wait") as mock__wait:
3941 # We patch out _wait() as no signal was involved so the
3942 # child process isn't actually going to exit rapidly.
3943 mock__wait.side_effect = KeyboardInterrupt
3944 with mock.patch.object(subprocess, "Popen",
3945 self.RecordingPopen):
3946 with self.assertRaises(KeyboardInterrupt):
3947 popener([sys.executable, "-c",
3948 "import time\ntime.sleep(9)\nimport sys\n"
3949 "sys.stderr.write('\\n!runaway child!\\n')"],
3950 stdout=subprocess.DEVNULL, **kwargs)
3951 for call in mock__wait.call_args_list[1:]:
3952 self.assertNotEqual(
3953 call, mock.call(timeout=None),
3954 "no open-ended wait() after the first allowed: "
3955 f"{mock__wait.call_args_list}")
3956 sigint_calls = []
3957 for call in mock__wait.call_args_list:
3958 if call == mock.call(timeout=0.25): # from Popen.__init__
3959 sigint_calls.append(call)
3960 self.assertLessEqual(mock__wait.call_count, 2,
3961 msg=mock__wait.call_args_list)
3962 self.assertEqual(len(sigint_calls), 1,
3963 msg=mock__wait.call_args_list)
3964 finally:
3965 # cleanup the forgotten (due to our mocks) child process
3966 process = self.RecordingPopen.instances_created.pop()
3967 process.kill()
3968 process.wait()
3969 self.assertEqual([], self.RecordingPopen.instances_created)
3970
3971 def test_call_keyboardinterrupt_no_kill(self):
3972 self._test_keyboardinterrupt_no_kill(subprocess.call, timeout=6.282)
3973
3974 def test_run_keyboardinterrupt_no_kill(self):
3975 self._test_keyboardinterrupt_no_kill(subprocess.run, timeout=6.282)
3976
3977 def test_context_manager_keyboardinterrupt_no_kill(self):
3978 def popen_via_context_manager(*args, **kwargs):
3979 with subprocess.Popen(*args, **kwargs) as unused_process:
3980 raise KeyboardInterrupt # Test how __exit__ handles ^C.
3981 self._test_keyboardinterrupt_no_kill(popen_via_context_manager)
3982
3983 def test_getoutput(self):
3984 self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
3985 self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
3986 (0, 'xyzzy'))
3987
3988 # we use mkdtemp in the next line to create an empty directory
3989 # under our exclusive control; from that, we can invent a pathname
3990 # that we _know_ won't exist. This is guaranteed to fail.
3991 dir = None
3992 try:
3993 dir = tempfile.mkdtemp()
3994 name = os.path.join(dir, "foo")
3995 status, output = subprocess.getstatusoutput(
3996 ("type " if mswindows else "cat ") + name)
3997 self.assertNotEqual(status, 0)
3998 finally:
3999 if dir is not None:
4000 os.rmdir(dir)
4001
4002 def test__all__(self):
4003 """Ensure that __all__ is populated properly."""
4004 intentionally_excluded = {"list2cmdline", "Handle", "pwd", "grp", "fcntl"}
4005 exported = set(subprocess.__all__)
4006 possible_exports = set()
4007 import types
4008 for name, value in subprocess.__dict__.items():
4009 if name.startswith('_'):
4010 continue
4011 if isinstance(value, (types.ModuleType,)):
4012 continue
4013 possible_exports.add(name)
4014 self.assertEqual(exported, possible_exports - intentionally_excluded)
4015
4016
4017 @unittest.skipUnless(hasattr(selectors, 'PollSelector'),
4018 "Test needs selectors.PollSelector")
4019 class ProcessTestCaseNoPoll(ProcessTestCase):
4020 def setUp(self):
4021 self.orig_selector = subprocess._PopenSelector
4022 subprocess._PopenSelector = selectors.SelectSelector
4023 ProcessTestCase.setUp(self)
4024
4025 def tearDown(self):
4026 subprocess._PopenSelector = self.orig_selector
4027 ProcessTestCase.tearDown(self)
4028
4029
4030 @unittest.skipUnless(mswindows, "Windows-specific tests")
4031 class CommandsWithSpaces (BaseTestCase):
4032
4033 def setUp(self):
4034 super().setUp()
4035 f, fname = tempfile.mkstemp(".py", "te st")
4036 self.fname = fname.lower ()
4037 os.write(f, b"import sys;"
4038 b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
4039 )
4040 os.close(f)
4041
4042 def tearDown(self):
4043 os.remove(self.fname)
4044 super().tearDown()
4045
4046 def with_spaces(self, *args, **kwargs):
4047 kwargs['stdout'] = subprocess.PIPE
4048 p = subprocess.Popen(*args, **kwargs)
4049 with p:
4050 self.assertEqual(
4051 p.stdout.read ().decode("mbcs"),
4052 "2 [%r, 'ab cd']" % self.fname
4053 )
4054
4055 def test_shell_string_with_spaces(self):
4056 # call() function with string argument with spaces on Windows
4057 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
4058 "ab cd"), shell=1)
4059
4060 def test_shell_sequence_with_spaces(self):
4061 # call() function with sequence argument with spaces on Windows
4062 self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
4063
4064 def test_noshell_string_with_spaces(self):
4065 # call() function with string argument with spaces on Windows
4066 self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
4067 "ab cd"))
4068
4069 def test_noshell_sequence_with_spaces(self):
4070 # call() function with sequence argument with spaces on Windows
4071 self.with_spaces([sys.executable, self.fname, "ab cd"])
4072
4073
4074 class ContextManagerTests(BaseTestCase):
4075
4076 def test_pipe(self):
4077 with subprocess.Popen([sys.executable, "-c",
4078 "import sys;"
4079 "sys.stdout.write('stdout');"
4080 "sys.stderr.write('stderr');"],
4081 stdout=subprocess.PIPE,
4082 stderr=subprocess.PIPE) as proc:
4083 self.assertEqual(proc.stdout.read(), b"stdout")
4084 self.assertEqual(proc.stderr.read(), b"stderr")
4085
4086 self.assertTrue(proc.stdout.closed)
4087 self.assertTrue(proc.stderr.closed)
4088
4089 def test_returncode(self):
4090 with subprocess.Popen([sys.executable, "-c",
4091 "import sys; sys.exit(100)"]) as proc:
4092 pass
4093 # __exit__ calls wait(), so the returncode should be set
4094 self.assertEqual(proc.returncode, 100)
4095
4096 def test_communicate_stdin(self):
4097 with subprocess.Popen([sys.executable, "-c",
4098 "import sys;"
4099 "sys.exit(sys.stdin.read() == 'context')"],
4100 stdin=subprocess.PIPE) as proc:
4101 proc.communicate(b"context")
4102 self.assertEqual(proc.returncode, 1)
4103
4104 def test_invalid_args(self):
4105 with self.assertRaises(NONEXISTING_ERRORS):
4106 with subprocess.Popen(NONEXISTING_CMD,
4107 stdout=subprocess.PIPE,
4108 stderr=subprocess.PIPE) as proc:
4109 pass
4110
4111 def test_broken_pipe_cleanup(self):
4112 """Broken pipe error should not prevent wait() (Issue 21619)"""
4113 proc = subprocess.Popen(ZERO_RETURN_CMD,
4114 stdin=subprocess.PIPE,
4115 bufsize=support.PIPE_MAX_SIZE*2)
4116 proc = proc.__enter__()
4117 # Prepare to send enough data to overflow any OS pipe buffering and
4118 # guarantee a broken pipe error. Data is held in BufferedWriter
4119 # buffer until closed.
4120 proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
4121 self.assertIsNone(proc.returncode)
4122 # EPIPE expected under POSIX; EINVAL under Windows
4123 self.assertRaises(OSError, proc.__exit__, None, None, None)
4124 self.assertEqual(proc.returncode, 0)
4125 self.assertTrue(proc.stdin.closed)
4126
4127
4128 if __name__ == "__main__":
4129 unittest.main()