[Python-checkins] [3.7] bpo-39828: Fix json.tool to catch BrokenPipeError (GH-18779). (GH-18895)

Dong-hee Na webhook-mailer at python.org
Tue Mar 10 04:30:56 EDT 2020


https://github.com/python/cpython/commit/633957d7e3f926e20fed023c635ae2216efd2198
commit: 633957d7e3f926e20fed023c635ae2216efd2198
branch: 3.7
author: Dong-hee Na <donghee.na92 at gmail.com>
committer: GitHub <noreply at github.com>
date: 2020-03-10T01:30:49-07:00
summary:

[3.7] bpo-39828: Fix json.tool to catch BrokenPipeError (GH-18779). (GH-18895)



(cherry picked from commit 700cb587303461d5a96456c56902cfdd8ad50e2d)

Co-authored-by: Dong-hee Na <donghee.na92 at gmail.com>

Automerge-Triggered-By: @vstinner

files:
A Misc/NEWS.d/next/Library/2020-03-05-00-57-49.bpo-39828.yWq9NJ.rst
M Lib/json/tool.py
M Lib/test/test_json/test_tool.py

diff --git a/Lib/json/tool.py b/Lib/json/tool.py
index 8e63dbdd4e188..c136fb7d3b6b7 100644
--- a/Lib/json/tool.py
+++ b/Lib/json/tool.py
@@ -42,4 +42,7 @@ def main():
 
 
 if __name__ == '__main__':
-    main()
+    try:
+        main()
+    except BrokenPipeError as exc:
+        sys.exit(exc.errno)
diff --git a/Lib/test/test_json/test_tool.py b/Lib/test/test_json/test_tool.py
index 2999dc1ef3718..8dfbe8ad53302 100644
--- a/Lib/test/test_json/test_tool.py
+++ b/Lib/test/test_json/test_tool.py
@@ -1,7 +1,9 @@
+import errno
 import os
 import sys
 import textwrap
 import unittest
+
 from subprocess import Popen, PIPE
 from test import support
 from test.support.script_helper import assert_python_ok
@@ -120,3 +122,12 @@ def test_sort_keys_flag(self):
         self.assertEqual(out.splitlines(),
                          self.expect_without_sort_keys.encode().splitlines())
         self.assertEqual(err, b'')
+
+    @unittest.skipIf(sys.platform =="win32", "The test is failed with ValueError on Windows")
+    def test_broken_pipe_error(self):
+        cmd = [sys.executable, '-m', 'json.tool']
+        proc = Popen(cmd, stdout=PIPE, stdin=PIPE)
+        # bpo-39828: Closing before json.tool attempts to write into stdout.
+        proc.stdout.close()
+        proc.communicate(b'"{}"')
+        self.assertEqual(proc.returncode, errno.EPIPE)
diff --git a/Misc/NEWS.d/next/Library/2020-03-05-00-57-49.bpo-39828.yWq9NJ.rst b/Misc/NEWS.d/next/Library/2020-03-05-00-57-49.bpo-39828.yWq9NJ.rst
new file mode 100644
index 0000000000000..04c61b94c45d6
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2020-03-05-00-57-49.bpo-39828.yWq9NJ.rst
@@ -0,0 +1 @@
+Fix :mod:`json.tool` to catch :exc:`BrokenPipeError`. Patch by Dong-hee Na.



More information about the Python-checkins mailing list