#Jonathan Hudson #Student Number 12347890 #Date: 2020-08-26 #Lecture Practice import sys #Enable one of these to 'hack' the arguments #sys.argv = ["4_System_Count_Ints.py"] #sys.argv = ["4_System_Count_Ints.py", "-flag"] #sys.argv = ["4_System_Count_Ints.py", "input.txt"] #sys.argv = ["4_System_Count_Ints.py", "input.txt", "-flag"] def main(): print("Program start") input_filename, flag = checkArguments() print("Flag: %s" % flag) print("Input filename: %s" % input_filename) lines = open_file(input_filename) print("Contents of %s" % input_filename) for i in range(len(lines)): print("Line %d->%s" % (i, lines[i]) count = count_ints(lines) print("Occurrence count of integers in %s" % input_filename) for key in sorted(count.keys()): print("%s occurred %d times" % (key, count[key])) print("Program done") def checkArguments(): print(f"These are the {len(sys.argv)} arguments you entered.") print(sys.argv) input_filename = None flag = False #No arguments, will handle getting filename from prompt later if len(sys.argv) == 1: pass #1 Argument get either flag or assume argument is filename elif len(sys.argv) == 2: if(sys.argv[1] == "-flag"): flag = True else: input_filename = sys.argv[1] #More than 2 arguments error and exit else: sys.stderr.write("Too many arguments!\n") sys.stderr.write("Usage: python 4_System_Count_Ints.py.py\n") sys.stderr.write("Usage: python 4_System_Count_Ints.py.py \n") sys.stderr.write("Usage: python 4_System_Count_Ints.py.py -flag\n") sys.exit(1) #Get filename if not in any argument if input_filename == None: input_filename = input("Enter input filename:") return input_filename, flag def open_file(input_filename): #Try to open the file input_file = None try: input_file = open(input_filename, "r") except Exception as e: sys.stderr.write("Exception message %s.\n" % e) sys.stderr.write("Input file %s cannot be opened.\n" % input_filename) sys.exit(2) #If file opens then read in lines and strip white space from right lines = [] try: for line in input_file: lines.append(line.rstrip()) except Exception as e: sys.stderr.write("Exception message %s.\n" % e) sys.stderr.write("Error reading input file %s.\n" % input_file) sys.exit(3) finally: input_file.close() return lines def count_ints(lines): #Create dictionary count = {} #Loop through lines for i in range(len(lines)): line = lines[i] #Split line into parts based on delimeter parts = line.split(",") #Loop through parts for j in range(len(parts)): part = parts[j] #If part is not an integer we have a problem so exit if not part.isdigit(): sys.stderr.write("%s is not an int in line %d %s and part %d of %s.\n" % (part, i, line, j , parts)) sys.exit(4) #Parse integer key = int(part) #Check if integer has a count already (if not make store 0 to start) if not key in count: count[key] = 0 #Count the integer as having occurred count[key] += 1 return count main()