changeset: 101314:5f46ecaf8c6e branch: 2.7 parent: 101310:907b13eb24d0 user: Martin Panter date: Fri May 13 01:54:44 2016 +0000 files: Lib/subprocess.py Lib/test/test_subprocess.py Misc/NEWS description: Issue #22274: Redirect stderr=STDOUT when stdout not redirected, by Akira Li diff -r 907b13eb24d0 -r 5f46ecaf8c6e Lib/subprocess.py --- a/Lib/subprocess.py Thu May 12 23:12:21 2016 -0700 +++ b/Lib/subprocess.py Fri May 13 01:54:44 2016 +0000 @@ -1142,7 +1142,10 @@ errread, errwrite = self.pipe_cloexec() to_close.update((errread, errwrite)) elif stderr == STDOUT: - errwrite = c2pwrite + if c2pwrite is not None: + errwrite = c2pwrite + else: # child's stdout is not set, use parent's stdout + errwrite = sys.__stdout__.fileno() elif isinstance(stderr, int): errwrite = stderr else: diff -r 907b13eb24d0 -r 5f46ecaf8c6e Lib/test/test_subprocess.py --- a/Lib/test/test_subprocess.py Thu May 12 23:12:21 2016 -0700 +++ b/Lib/test/test_subprocess.py Fri May 13 01:54:44 2016 +0000 @@ -285,6 +285,27 @@ tf.seek(0) self.assertStderrEqual(tf.read(), "strawberry") + def test_stderr_redirect_with_no_stdout_redirect(self): + # test stderr=STDOUT while stdout=None (not set) + + # - grandchild prints to stderr + # - child redirects grandchild's stderr to its stdout + # - the parent should get grandchild's stderr in child's stdout + p = subprocess.Popen([sys.executable, "-c", + 'import sys, subprocess;' + 'rc = subprocess.call([sys.executable, "-c",' + ' "import sys;"' + ' "sys.stderr.write(\'42\')"],' + ' stderr=subprocess.STDOUT);' + 'sys.exit(rc)'], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + stdout, stderr = p.communicate() + #NOTE: stdout should get stderr from grandchild + self.assertStderrEqual(stdout, b'42') + self.assertStderrEqual(stderr, b'') # should be empty + self.assertEqual(p.returncode, 0) + def test_stdout_stderr_pipe(self): # capture stdout and stderr to the same pipe p = subprocess.Popen([sys.executable, "-c", diff -r 907b13eb24d0 -r 5f46ecaf8c6e Misc/NEWS --- a/Misc/NEWS Thu May 12 23:12:21 2016 -0700 +++ b/Misc/NEWS Fri May 13 01:54:44 2016 +0000 @@ -77,6 +77,9 @@ Library ------- +- Issue #22274: In the subprocess module, allow stderr to be redirected to + stdout even when stdout is not redirected. Patch by Akira Li. + - Issue #12045: Avoid duplicate execution of command in ctypes.util._get_soname(). Patch by Sijin Joseph.