Skip to content

bpo-45644: json.tool: Use staged write for outfile. #30659

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
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 25 additions & 4 deletions Lib/json/tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,28 @@

"""
import argparse
import contextlib
import json
import os.path
import sys
from pathlib import Path
import tempfile


@contextlib.contextmanager
def _staged_outfile(path):
# Use tempfile to support outfile == infile case.
# See https://discuss.python.org/t/adding-atomicwrite-in-stdlib/11899
dir, base = os.path.split(path)
fd, tempname = tempfile.mkstemp(prefix=base + '.', dir=dir)
file = os.fdopen(fd, "w", encoding="utf-8")
try:
with file:
yield file
except:
os.remove(tempname)
raise
else:
os.replace(tempname, path)


def main():
Expand All @@ -26,7 +45,7 @@ def main():
help='a JSON file to be validated or pretty-printed',
default=sys.stdin)
parser.add_argument('outfile', nargs='?',
type=Path,
type=str,
help='write the output of infile to outfile',
default=None)
parser.add_argument('--sort-keys', action='store_true', default=False,
Expand Down Expand Up @@ -66,10 +85,12 @@ def main():
else:
objs = (json.load(infile),)

if options.outfile is None:
if options.outfile is None or options.outfile == '-':
# infile (argparse.FileType) supports '-' so outfile
# supports '-' for consistency.
out = sys.stdout
else:
out = options.outfile.open('w', encoding='utf-8')
out = _staged_outfile(options.outfile)
with out as outfile:
for obj in objs:
json.dump(obj, outfile, **dump_args)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
``python -m json.tool infile outfile`` uses staged write idiom for
``outfile``. This allows that outfile is same to infile even when
``--json-lines`` option is used.