Debian Codegraph @

lib-python/3/test/test_subprocess.py

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