diff options
author | Benjamin Peterson <benjamin@python.org> | 2014-03-22 04:17:29 (GMT) |
---|---|---|
committer | Benjamin Peterson <benjamin@python.org> | 2014-03-22 04:17:29 (GMT) |
commit | 940e2074123f7d18236e2e8ee08044b400261c42 (patch) | |
tree | a4fc953776d5b9a2e223b47089dfde3678dbed66 /Lib | |
parent | a191b91a4373937e7545b92d875160a5f66a2f3e (diff) | |
download | cpython-940e2074123f7d18236e2e8ee08044b400261c42.zip cpython-940e2074123f7d18236e2e8ee08044b400261c42.tar.gz cpython-940e2074123f7d18236e2e8ee08044b400261c42.tar.bz2 |
improve the command-line interface of json.tool (closes #21000)
A patch from Berker Peksag.
Diffstat (limited to 'Lib')
-rw-r--r-- | Lib/json/tool.py | 27 | ||||
-rw-r--r-- | Lib/test/test_json/test_tool.py | 8 |
2 files changed, 23 insertions, 12 deletions
diff --git a/Lib/json/tool.py b/Lib/json/tool.py index 7db4528..cd57e4f 100644 --- a/Lib/json/tool.py +++ b/Lib/json/tool.py @@ -10,21 +10,24 @@ Usage:: Expecting property name enclosed in double quotes: line 1 column 3 (char 2) """ -import sys +import argparse import json +import sys + def main(): - if len(sys.argv) == 1: - infile = sys.stdin - outfile = sys.stdout - elif len(sys.argv) == 2: - infile = open(sys.argv[1], 'r') - outfile = sys.stdout - elif len(sys.argv) == 3: - infile = open(sys.argv[1], 'r') - outfile = open(sys.argv[2], 'w') - else: - raise SystemExit(sys.argv[0] + " [infile [outfile]]") + prog = 'python -m json.tool' + description = ('A simple command line interface for json module ' + 'to validate and pretty-print JSON objects.') + parser = argparse.ArgumentParser(prog=prog, description=description) + parser.add_argument('infile', nargs='?', type=argparse.FileType(), + help='a JSON file to be validated or pretty-printed') + parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'), + help='write the output of infile to outfile') + options = parser.parse_args() + + infile = options.infile or sys.stdin + outfile = options.outfile or sys.stdout with infile: try: obj = json.load(infile) diff --git a/Lib/test/test_json/test_tool.py b/Lib/test/test_json/test_tool.py index 0c39e56..5484a8a 100644 --- a/Lib/test/test_json/test_tool.py +++ b/Lib/test/test_json/test_tool.py @@ -55,6 +55,7 @@ class TestTool(unittest.TestCase): def test_infile_stdout(self): infile = self._create_infile() rc, out, err = assert_python_ok('-m', 'json.tool', infile) + self.assertEqual(rc, 0) self.assertEqual(out.splitlines(), self.expect.encode().splitlines()) self.assertEqual(err, b'') @@ -65,5 +66,12 @@ class TestTool(unittest.TestCase): self.addCleanup(os.remove, outfile) with open(outfile, "r") as fp: self.assertEqual(fp.read(), self.expect) + self.assertEqual(rc, 0) self.assertEqual(out, b'') self.assertEqual(err, b'') + + def test_help_flag(self): + rc, out, err = assert_python_ok('-m', 'json.tool', '-h') + self.assertEqual(rc, 0) + self.assertTrue(out.startswith(b'usage: ')) + self.assertEqual(err, b'') |