summaryrefslogtreecommitdiffstats
path: root/Lib/json
diff options
context:
space:
mode:
authorSerhiy Storchaka <storchaka@gmail.com>2024-01-10 13:07:19 (GMT)
committerGitHub <noreply@github.com>2024-01-10 13:07:19 (GMT)
commitb3d2427f2280fa8dae3515036c518d74ba43ebd1 (patch)
treee9fda1fdaf580c57ca6bda8c0d7e7bfc965f91d5 /Lib/json
parenta8629816c6c0e6770248a60529fd7c9ba08aad55 (diff)
downloadcpython-b3d2427f2280fa8dae3515036c518d74ba43ebd1.zip
cpython-b3d2427f2280fa8dae3515036c518d74ba43ebd1.tar.gz
cpython-b3d2427f2280fa8dae3515036c518d74ba43ebd1.tar.bz2
gh-58032: Do not use argparse.FileType in module CLIs and scripts (GH-113649)
Open and close files manually. It prevents from leaking files, preliminary creation of output files, and accidental closing of stdin and stdout.
Diffstat (limited to 'Lib/json')
-rw-r--r--Lib/json/tool.py34
1 files changed, 19 insertions, 15 deletions
diff --git a/Lib/json/tool.py b/Lib/json/tool.py
index 0490b8c..fdfc337 100644
--- a/Lib/json/tool.py
+++ b/Lib/json/tool.py
@@ -13,7 +13,6 @@ Usage::
import argparse
import json
import sys
-from pathlib import Path
def main():
@@ -22,11 +21,9 @@ def main():
'to validate and pretty-print JSON objects.')
parser = argparse.ArgumentParser(prog=prog, description=description)
parser.add_argument('infile', nargs='?',
- type=argparse.FileType(encoding="utf-8"),
help='a JSON file to be validated or pretty-printed',
- default=sys.stdin)
+ default='-')
parser.add_argument('outfile', nargs='?',
- type=Path,
help='write the output of infile to outfile',
default=None)
parser.add_argument('--sort-keys', action='store_true', default=False,
@@ -59,23 +56,30 @@ def main():
dump_args['indent'] = None
dump_args['separators'] = ',', ':'
- with options.infile as infile:
+ try:
+ if options.infile == '-':
+ infile = sys.stdin
+ else:
+ infile = open(options.infile, encoding='utf-8')
try:
if options.json_lines:
objs = (json.loads(line) for line in infile)
else:
objs = (json.load(infile),)
+ finally:
+ if infile is not sys.stdin:
+ infile.close()
- if options.outfile is None:
- out = sys.stdout
- else:
- out = options.outfile.open('w', encoding='utf-8')
- with out as outfile:
- for obj in objs:
- json.dump(obj, outfile, **dump_args)
- outfile.write('\n')
- except ValueError as e:
- raise SystemExit(e)
+ if options.outfile is None:
+ outfile = sys.stdout
+ else:
+ outfile = open(options.outfile, 'w', encoding='utf-8')
+ with outfile:
+ for obj in objs:
+ json.dump(obj, outfile, **dump_args)
+ outfile.write('\n')
+ except ValueError as e:
+ raise SystemExit(e)
if __name__ == '__main__':