8000 bpo-33927: Add support for same infile and outfile to json.tool by remilapeyre · Pull Request #7865 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

bpo-33927: Add support for same infile and outfile to json.tool #7865

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Prev Previous commit
Next Next commit
Fix error message on IOError
  • Loading branch information
Rémi Lapeyre committed Jun 26, 2018
commit 23593fb76c999ed96583b87d5d4873d5383215a2
5 changes: 4 additions & 1 deletion Lib/json/tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,10 @@ def main():
except ValueError as e:
raise SystemExit(e)

outfile = sys.stdout if options.outfile == '-' else open(options.outfile, 'w')
try:
outfile = sys.stdout if options.outfile == '-' else open(options.outfile, 'w')
except IOError as e:
parser.error("can't open '{}': {}".format(options.outfile, str(e)))
with outfile:
json.dump(obj, outfile, sort_keys=sort_keys, indent=4)
outfile.write('\n')
Expand Down
11 changes: 10 additions & 1 deletion Lib/test/test_json/test_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import unittest
from subprocess import Popen, PIPE
from test import support
from test.support.script_helper import assert_python_ok
from test.support.script_helper import assert_python_ok, assert_python_failure


class TestTool(unittest.TestCase):
Expand Down Expand Up @@ -99,6 +99,15 @@ def test_infile_same_outfile(self):
self.assertEqual(out, b'')
self.assertEqual(err, b'')

def test_unavailable_outfile(self):
infile = self._create_infile()
rc, out, err = assert_python_failure('-m', 'json.tool', infile, '/bla/outfile')
self.assertEqual(rc, 2)
self.assertEqual(out, b'')
err = err.decode().splitlines()
self.assertEqual(err[0], 'usage: python -m json.tool [-h] [--sort-keys] [infile] [outfile]')
self.assertEqual(err[1], "python -m json.tool: error: can't open '/bla/outfile': [Errno 2] No such file or directory: '/bla/outfile'")

def test_help_flag(self):
rc, out, err = assert_python_ok('-m', 'json.tool', '-h')
self.assertEqual(rc, 0)
Expand Down
0