Skip to content

Commit c763589

Browse files
committed
Issue #22274: Redirect stderr=STDOUT when stdout not redirected, by Akira Li
1 parent 07451dd commit c763589

File tree

3 files changed

+28
-1
lines changed

3 files changed

+28
-1
lines changed

Lib/subprocess.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -1401,7 +1401,10 @@ def _get_handles(self, stdin, stdout, stderr):
14011401
elif stderr == PIPE:
14021402
errread, errwrite = os.pipe()
14031403
elif stderr == STDOUT:
1404-
errwrite = c2pwrite
1404+
if c2pwrite != -1:
1405+
errwrite = c2pwrite
1406+
else: # child's stdout is not set, use parent's stdout
1407+
errwrite = sys.__stdout__.fileno()
14051408
elif stderr == DEVNULL:
14061409
errwrite = self._get_devnull()
14071410
elif isinstance(stderr, int):

Lib/test/test_subprocess.py

+21
Original file line numberDiff line numberDiff line change
@@ -504,6 +504,27 @@ def test_stderr_fileobj(self):
504504
tf.seek(0)
505505
self.assertStderrEqual(tf.read(), b"strawberry")
506506

507+
def test_stderr_redirect_with_no_stdout_redirect(self):
508+
# test stderr=STDOUT while stdout=None (not set)
509+
510+
# - grandchild prints to stderr
511+
# - child redirects grandchild's stderr to its stdout
512+
# - the parent should get grandchild's stderr in child's stdout
513+
p = subprocess.Popen([sys.executable, "-c",
514+
'import sys, subprocess;'
515+
'rc = subprocess.call([sys.executable, "-c",'
516+
' "import sys;"'
517+
' "sys.stderr.write(\'42\')"],'
518+
' stderr=subprocess.STDOUT);'
519+
'sys.exit(rc)'],
520+
stdout=subprocess.PIPE,
521+
stderr=subprocess.PIPE)
522+
stdout, stderr = p.communicate()
523+
#NOTE: stdout should get stderr from grandchild
524+
self.assertStderrEqual(stdout, b'42')
525+
self.assertStderrEqual(stderr, b'') # should be empty
526+
self.assertEqual(p.returncode, 0)
527+
507528
def test_stdout_stderr_pipe(self):
508529
# capture stdout and stderr to the same pipe
509530
p = subprocess.Popen([sys.executable, "-c",

Misc/NEWS

+3
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,9 @@ Core and Builtins
118118
Library
119119
-------
120120

121+
- Issue #22274: In the subprocess module, allow stderr to be redirected to
122+
stdout even when stdout is not redirected. Patch by Akira Li.
123+
121124
- Issue #25745: Fixed leaking a userptr in curses panel destructor.
122125

123126
- Issue #26977: Removed unnecessary, and ignored, call to sum of squares helper

0 commit comments

Comments
 (0)