summaryrefslogtreecommitdiffstats
path: root/Lib/ast.py
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/ast.py
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/ast.py')
-rw-r--r--Lib/ast.py14
1 files changed, 9 insertions, 5 deletions
diff --git a/Lib/ast.py b/Lib/ast.py
index f7888d1..7d3cd48 100644
--- a/Lib/ast.py
+++ b/Lib/ast.py
@@ -1812,8 +1812,7 @@ def main():
import argparse
parser = argparse.ArgumentParser(prog='python -m ast')
- parser.add_argument('infile', type=argparse.FileType(mode='rb'), nargs='?',
- default='-',
+ parser.add_argument('infile', nargs='?', default='-',
help='the file to parse; defaults to stdin')
parser.add_argument('-m', '--mode', default='exec',
choices=('exec', 'single', 'eval', 'func_type'),
@@ -1827,9 +1826,14 @@ def main():
help='indentation of nodes (number of spaces)')
args = parser.parse_args()
- with args.infile as infile:
- source = infile.read()
- tree = parse(source, args.infile.name, args.mode, type_comments=args.no_type_comments)
+ if args.infile == '-':
+ name = '<stdin>'
+ source = sys.stdin.buffer.read()
+ else:
+ name = args.infile
+ with open(args.infile, 'rb') as infile:
+ source = infile.read()
+ tree = parse(source, name, args.mode, type_comments=args.no_type_comments)
print(dump(tree, include_attributes=args.include_attributes, indent=args.indent))
if __name__ == '__main__':