]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-122873: Allow "python -m json" to work (#122884)
authorTrey Hunner <trey@treyhunner.com>
Tue, 13 Aug 2024 16:09:38 +0000 (09:09 -0700)
committerGitHub <noreply@github.com>
Tue, 13 Aug 2024 16:09:38 +0000 (17:09 +0100)
Co-authored-by: Adam Turner <9087854+AA-Turner@users.noreply.github.com>
Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
Co-authored-by: Alyssa Coghlan <ncoghlan@gmail.com>
Doc/library/cmdline.rst
Doc/library/json.rst
Doc/whatsnew/3.14.rst
Lib/json/__init__.py
Lib/json/__main__.py [new file with mode: 0644]
Lib/json/tool.py
Lib/test/test_json/test_tool.py
Misc/NEWS.d/next/Library/2024-08-10-14-16-59.gh-issue-122873.XlHaUn.rst [new file with mode: 0644]

index 5174515ffc23edd8f309b8e63de53dffca36fd4f..dd538cdb754efb6f13843435167fbb7d621ee536 100644 (file)
@@ -23,7 +23,7 @@ The following modules have a command-line interface.
 * :ref:`http.server <http-server-cli>`
 * :mod:`!idlelib`
 * :ref:`inspect <inspect-module-cli>`
-* :ref:`json.tool <json-commandline>`
+* :ref:`json <json-commandline>`
 * :mod:`mimetypes`
 * :mod:`pdb`
 * :mod:`pickle`
index 42cb1f850fe9c5abfbc98deb2ee3ba3733b62c1a..26f85b5ddf8d820bdcc12d486732f1004c06ef80 100644 (file)
@@ -116,15 +116,15 @@ Extending :class:`JSONEncoder`::
     ['[2.0', ', 1.0', ']']
 
 
-Using :mod:`json.tool` from the shell to validate and pretty-print:
+Using :mod:`json` from the shell to validate and pretty-print:
 
 .. code-block:: shell-session
 
-    $ echo '{"json":"obj"}' | python -m json.tool
+    $ echo '{"json":"obj"}' | python -m json
     {
         "json": "obj"
     }
-    $ echo '{1.2:3.4}' | python -m json.tool
+    $ echo '{1.2:3.4}' | python -m json
     Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
 
 See :ref:`json-commandline` for detailed documentation.
@@ -678,31 +678,32 @@ when serializing instances of "exotic" numerical types such as
 
 
 .. _json-commandline:
-.. program:: json.tool
+.. program:: json
 
-Command Line Interface
+Command-line interface
 ----------------------
 
 .. module:: json.tool
-    :synopsis: A command line to validate and pretty-print JSON.
+    :synopsis: A command-line interface to validate and pretty-print JSON.
 
 **Source code:** :source:`Lib/json/tool.py`
 
 --------------
 
-The :mod:`json.tool` module provides a simple command line interface to validate
-and pretty-print JSON objects.
+The :mod:`json` module can be invoked as a script via ``python -m json``
+to validate and pretty-print JSON objects. The :mod:`json.tool` submodule
+implements this interface.
 
 If the optional ``infile`` and ``outfile`` arguments are not
 specified, :data:`sys.stdin` and :data:`sys.stdout` will be used respectively:
 
 .. code-block:: shell-session
 
-    $ echo '{"json": "obj"}' | python -m json.tool
+    $ echo '{"json": "obj"}' | python -m json
     {
         "json": "obj"
     }
-    $ echo '{1.2:3.4}' | python -m json.tool
+    $ echo '{1.2:3.4}' | python -m json
     Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
 
 .. versionchanged:: 3.5
@@ -710,8 +711,13 @@ specified, :data:`sys.stdin` and :data:`sys.stdout` will be used respectively:
    :option:`--sort-keys` option to sort the output of dictionaries
    alphabetically by key.
 
+.. versionchanged:: 3.14
+   The :mod:`json` module may now be directly executed as
+   ``python -m json``. For backwards compatibility, invoking
+   the CLI as ``python -m json.tool`` remains supported.
 
-Command line options
+
+Command-line options
 ^^^^^^^^^^^^^^^^^^^^
 
 .. option:: infile
@@ -720,7 +726,7 @@ Command line options
 
    .. code-block:: shell-session
 
-      $ python -m json.tool mp_films.json
+      $ python -m json mp_films.json
       [
           {
               "title": "And Now for Something Completely Different",
index 3f53f6b940027b3b4c65b775d8c947206fe9bf9e..267860712b9967da37015cc2320d8dd2ae5adab9 100644 (file)
@@ -124,6 +124,10 @@ Add notes for JSON serialization errors that allow to identify the source
 of the error.
 (Contributed by Serhiy Storchaka in :gh:`122163`.)
 
+Enable :mod:`json` module to work as a script using the :option:`-m` switch: ``python -m json``.
+See the :ref:`JSON command-line interface <json-commandline>` documentation.
+(Contributed by Trey Hunner in :gh:`122873`.)
+
 operator
 --------
 
index ed2c74771ea87ddc9349099c37b17d3cda213040..1d972d22ded072a0a4c9b1d2cfabe3552d25fcc2 100644 (file)
@@ -86,13 +86,13 @@ Specializing JSON object encoding::
     '[2.0, 1.0]'
 
 
-Using json.tool from the shell to validate and pretty-print::
+Using json from the shell to validate and pretty-print::
 
-    $ echo '{"json":"obj"}' | python -m json.tool
+    $ echo '{"json":"obj"}' | python -m json
     {
         "json": "obj"
     }
-    $ echo '{ 1.2:3.4}' | python -m json.tool
+    $ echo '{ 1.2:3.4}' | python -m json
     Expecting property name enclosed in double quotes: line 1 column 3 (char 2)
 """
 __version__ = '2.0.9'
diff --git a/Lib/json/__main__.py b/Lib/json/__main__.py
new file mode 100644 (file)
index 0000000..1808ead
--- /dev/null
@@ -0,0 +1,20 @@
+"""Command-line tool to validate and pretty-print JSON
+
+Usage::
+
+    $ echo '{"json":"obj"}' | python -m json
+    {
+        "json": "obj"
+    }
+    $ echo '{ 1.2:3.4}' | python -m json
+    Expecting property name enclosed in double quotes: line 1 column 3 (char 2)
+
+"""
+import json.tool
+
+
+if __name__ == '__main__':
+    try:
+        json.tool.main()
+    except BrokenPipeError as exc:
+        raise SystemExit(exc.errno)
index fdfc3372bcca02e6ae298c90b727bd127356fb0b..9028e517fb9f7dfcf66ffd0f040dd94b30634a43 100644 (file)
@@ -1,14 +1,7 @@
-r"""Command-line tool to validate and pretty-print JSON
-
-Usage::
-
-    $ echo '{"json":"obj"}' | python -m json.tool
-    {
-        "json": "obj"
-    }
-    $ echo '{ 1.2:3.4}' | python -m json.tool
-    Expecting property name enclosed in double quotes: line 1 column 3 (char 2)
+"""Command-line tool to validate and pretty-print JSON
 
+See `json.__main__` for a usage example (invocation as
+`python -m json.tool` is supported for backwards compatibility).
 """
 import argparse
 import json
@@ -16,7 +9,7 @@ import sys
 
 
 def main():
-    prog = 'python -m json.tool'
+    prog = 'python -m json'
     description = ('A simple command line interface for json module '
                    'to validate and pretty-print JSON objects.')
     parser = argparse.ArgumentParser(prog=prog, description=description)
@@ -86,4 +79,4 @@ if __name__ == '__main__':
     try:
         main()
     except BrokenPipeError as exc:
-        sys.exit(exc.errno)
+        raise SystemExit(exc.errno)
index 2b63810d53981e97fdc13d83942d5bfef719e0ff..5da7cdcad709fa0522021963613212671769057b 100644 (file)
@@ -11,7 +11,7 @@ from test.support.script_helper import assert_python_ok
 
 
 @support.requires_subprocess()
-class TestTool(unittest.TestCase):
+class TestMain(unittest.TestCase):
     data = """
 
         [["blorpie"],[ "whoops" ] , [
@@ -19,6 +19,7 @@ class TestTool(unittest.TestCase):
         "i-vhbjkhnth", {"nifty":87}, {"morefield" :\tfalse,"field"
             :"yes"}  ]
            """
+    module = 'json'
 
     expect_without_sort_keys = textwrap.dedent("""\
     [
@@ -87,7 +88,7 @@ class TestTool(unittest.TestCase):
     """)
 
     def test_stdin_stdout(self):
-        args = sys.executable, '-m', 'json.tool'
+        args = sys.executable, '-m', self.module
         process = subprocess.run(args, input=self.data, capture_output=True, text=True, check=True)
         self.assertEqual(process.stdout, self.expect)
         self.assertEqual(process.stderr, '')
@@ -101,7 +102,7 @@ class TestTool(unittest.TestCase):
 
     def test_infile_stdout(self):
         infile = self._create_infile()
-        rc, out, err = assert_python_ok('-m', 'json.tool', infile)
+        rc, out, err = assert_python_ok('-m', self.module, infile)
         self.assertEqual(rc, 0)
         self.assertEqual(out.splitlines(), self.expect.encode().splitlines())
         self.assertEqual(err, b'')
@@ -115,7 +116,7 @@ class TestTool(unittest.TestCase):
         ''').encode()
 
         infile = self._create_infile(data)
-        rc, out, err = assert_python_ok('-m', 'json.tool', infile)
+        rc, out, err = assert_python_ok('-m', self.module, infile)
 
         self.assertEqual(rc, 0)
         self.assertEqual(out.splitlines(), expect.splitlines())
@@ -124,7 +125,7 @@ class TestTool(unittest.TestCase):
     def test_infile_outfile(self):
         infile = self._create_infile()
         outfile = os_helper.TESTFN + '.out'
-        rc, out, err = assert_python_ok('-m', 'json.tool', infile, outfile)
+        rc, out, err = assert_python_ok('-m', self.module, infile, outfile)
         self.addCleanup(os.remove, outfile)
         with open(outfile, "r", encoding="utf-8") as fp:
             self.assertEqual(fp.read(), self.expect)
@@ -134,7 +135,7 @@ class TestTool(unittest.TestCase):
 
     def test_writing_in_place(self):
         infile = self._create_infile()
-        rc, out, err = assert_python_ok('-m', 'json.tool', infile, infile)
+        rc, out, err = assert_python_ok('-m', self.module, infile, infile)
         with open(infile, "r", encoding="utf-8") as fp:
             self.assertEqual(fp.read(), self.expect)
         self.assertEqual(rc, 0)
@@ -142,20 +143,20 @@ class TestTool(unittest.TestCase):
         self.assertEqual(err, b'')
 
     def test_jsonlines(self):
-        args = sys.executable, '-m', 'json.tool', '--json-lines'
+        args = sys.executable, '-m', self.module, '--json-lines'
         process = subprocess.run(args, input=self.jsonlines_raw, capture_output=True, text=True, check=True)
         self.assertEqual(process.stdout, self.jsonlines_expect)
         self.assertEqual(process.stderr, '')
 
     def test_help_flag(self):
-        rc, out, err = assert_python_ok('-m', 'json.tool', '-h')
+        rc, out, err = assert_python_ok('-m', self.module, '-h')
         self.assertEqual(rc, 0)
         self.assertTrue(out.startswith(b'usage: '))
         self.assertEqual(err, b'')
 
     def test_sort_keys_flag(self):
         infile = self._create_infile()
-        rc, out, err = assert_python_ok('-m', 'json.tool', '--sort-keys', infile)
+        rc, out, err = assert_python_ok('-m', self.module, '--sort-keys', infile)
         self.assertEqual(rc, 0)
         self.assertEqual(out.splitlines(),
                          self.expect_without_sort_keys.encode().splitlines())
@@ -169,7 +170,7 @@ class TestTool(unittest.TestCase):
           2
         ]
         ''')
-        args = sys.executable, '-m', 'json.tool', '--indent', '2'
+        args = sys.executable, '-m', self.module, '--indent', '2'
         process = subprocess.run(args, input=input_, capture_output=True, text=True, check=True)
         self.assertEqual(process.stdout, expect)
         self.assertEqual(process.stderr, '')
@@ -177,7 +178,7 @@ class TestTool(unittest.TestCase):
     def test_no_indent(self):
         input_ = '[1,\n2]'
         expect = '[1, 2]\n'
-        args = sys.executable, '-m', 'json.tool', '--no-indent'
+        args = sys.executable, '-m', self.module, '--no-indent'
         process = subprocess.run(args, input=input_, capture_output=True, text=True, check=True)
         self.assertEqual(process.stdout, expect)
         self.assertEqual(process.stderr, '')
@@ -185,7 +186,7 @@ class TestTool(unittest.TestCase):
     def test_tab(self):
         input_ = '[1, 2]'
         expect = '[\n\t1,\n\t2\n]\n'
-        args = sys.executable, '-m', 'json.tool', '--tab'
+        args = sys.executable, '-m', self.module, '--tab'
         process = subprocess.run(args, input=input_, capture_output=True, text=True, check=True)
         self.assertEqual(process.stdout, expect)
         self.assertEqual(process.stderr, '')
@@ -193,7 +194,7 @@ class TestTool(unittest.TestCase):
     def test_compact(self):
         input_ = '[ 1 ,\n 2]'
         expect = '[1,2]\n'
-        args = sys.executable, '-m', 'json.tool', '--compact'
+        args = sys.executable, '-m', self.module, '--compact'
         process = subprocess.run(args, input=input_, capture_output=True, text=True, check=True)
         self.assertEqual(process.stdout, expect)
         self.assertEqual(process.stderr, '')
@@ -202,7 +203,7 @@ class TestTool(unittest.TestCase):
         infile = self._create_infile('{"key":"💩"}')
         outfile = os_helper.TESTFN + '.out'
         self.addCleanup(os.remove, outfile)
-        assert_python_ok('-m', 'json.tool', '--no-ensure-ascii', infile, outfile)
+        assert_python_ok('-m', self.module, '--no-ensure-ascii', infile, outfile)
         with open(outfile, "rb") as f:
             lines = f.read().splitlines()
         # asserting utf-8 encoded output file
@@ -213,7 +214,7 @@ class TestTool(unittest.TestCase):
         infile = self._create_infile('{"key":"💩"}')
         outfile = os_helper.TESTFN + '.out'
         self.addCleanup(os.remove, outfile)
-        assert_python_ok('-m', 'json.tool', infile, outfile)
+        assert_python_ok('-m', self.module, infile, outfile)
         with open(outfile, "rb") as f:
             lines = f.read().splitlines()
         # asserting an ascii encoded output file
@@ -222,11 +223,16 @@ class TestTool(unittest.TestCase):
 
     @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']
+        cmd = [sys.executable, '-m', self.module]
         proc = subprocess.Popen(cmd,
                                 stdout=subprocess.PIPE,
                                 stdin=subprocess.PIPE)
-        # bpo-39828: Closing before json.tool attempts to write into stdout.
+        # bpo-39828: Closing before json attempts to write into stdout.
         proc.stdout.close()
         proc.communicate(b'"{}"')
         self.assertEqual(proc.returncode, errno.EPIPE)
+
+
+@support.requires_subprocess()
+class TestTool(TestMain):
+    module = 'json.tool'
diff --git a/Misc/NEWS.d/next/Library/2024-08-10-14-16-59.gh-issue-122873.XlHaUn.rst b/Misc/NEWS.d/next/Library/2024-08-10-14-16-59.gh-issue-122873.XlHaUn.rst
new file mode 100644 (file)
index 0000000..002ebd9
--- /dev/null
@@ -0,0 +1,3 @@
+Enable :mod:`json` module to work as a script using the :option:`-m` switch: ``python -m json``.
+See the :ref:`JSON command-line interface <json-commandline>` documentation.
+Patch by Trey Hunner.