1+ #!/usr/bin/env python3
2+ """
3+ Format and display a summary from a JSON file.
4+ Takes a JSON file path as a command-line argument.
5+ """
16import json
7+ import sys
8+ from typing import Any
29
3- try :
4- s = json .load (open ('summary.json' ))
5- except Exception :
6- print ('Invalid summary JSON' )
7- raise
810
9- if not isinstance (s , dict ) or s .get ('count' , 0 ) == 0 :
10- print ('No numbers provided' )
11- else :
12- print (f"count={ s ['count' ]} , sum={ s ['sum' ]} , avg={ s ['avg' ]:.2f} , min={ s ['min' ]} , max={ s ['max' ]} " )
11+ def load_json_file (file_path : str ) -> dict [str , Any ]:
12+ """Load and parse a JSON file with proper error handling.
13+
14+ Args:
15+ file_path: Path to the JSON file to load
16+
17+ Returns:
18+ The parsed JSON data as a dictionary
19+
20+ Raises:
21+ SystemExit: On file or JSON parsing errors
22+ """
23+ try :
24+ with open (file_path , 'r' , encoding = 'utf-8' ) as f :
25+ return json .load (f )
26+ except FileNotFoundError :
27+ print (f"Error: File '{ file_path } ' not found" , file = sys .stderr )
28+ sys .exit (2 )
29+ except json .JSONDecodeError as e :
30+ print (f"Error: Invalid JSON in '{ file_path } ': { e } " , file = sys .stderr )
31+ sys .exit (2 )
32+ except OSError as e :
33+ print (f"Error: Failed to read '{ file_path } ': { e } " , file = sys .stderr )
34+ sys .exit (2 )
35+
36+
37+ def main () -> None :
38+ """Load a number summary in json format and output a human readable string instead
39+ """
40+ if len (sys .argv ) != 2 :
41+ print ("Usage: python format_summary.py <summaryfile>" , file = sys .stderr )
42+ sys .exit (1 )
43+
44+ json_file = sys .argv [1 ]
45+ summary = load_json_file (json_file )
46+
47+ if not isinstance (summary , dict ) or summary .get ('count' , 0 ) == 0 :
48+ print ('No numbers provided' )
49+ else :
50+ print (f"count={ summary ['count' ]} , sum={ summary ['sum' ]} , avg={ summary ['avg' ]:.2f} , min={ summary ['min' ]} , max={ summary ['max' ]} " )
51+
52+
53+ if __name__ == "__main__" :
54+ main ()
0 commit comments